diff --git a/Cargo.lock b/Cargo.lock index 4a45d5c602e8..376c8c7d5a6b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -744,6 +744,7 @@ dependencies = [ "cumulus-pallet-xcmp-queue", "cumulus-primitives-core", "cumulus-primitives-utility", + "env_logger 0.10.1", "frame-benchmarking", "frame-executive", "frame-support", @@ -5164,9 +5165,9 @@ dependencies = [ [[package]] name = "env_logger" -version = "0.10.0" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" +checksum = "95b3f3e67048839cb0d0781f445682a35113da7121f7c949db0e2be96a4fbece" dependencies = [ "humantime", "is-terminal", @@ -5426,7 +5427,7 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "84f2e425d9790201ba4af4630191feac6dcc98765b118d4d18e91d23c2353866" dependencies = [ - "env_logger 0.10.0", + "env_logger 0.10.1", "log", ] @@ -21405,6 +21406,7 @@ dependencies = [ "Inflector", "proc-macro2", "quote", + "staging-xcm", "syn 2.0.38", "trybuild", ] diff --git a/bridges/bin/runtime-common/src/messages_benchmarking.rs b/bridges/bin/runtime-common/src/messages_benchmarking.rs index e7e7891461b2..0c7a9ad1a83d 100644 --- a/bridges/bin/runtime-common/src/messages_benchmarking.rs +++ b/bridges/bin/runtime-common/src/messages_benchmarking.rs @@ -38,7 +38,7 @@ use frame_support::weights::Weight; use pallet_bridge_messages::benchmarking::{MessageDeliveryProofParams, MessageProofParams}; use sp_runtime::traits::{Header, Zero}; use sp_std::prelude::*; -use xcm::v3::prelude::*; +use xcm::latest::prelude::*; /// Prepare inbound bridge message according to given message proof parameters. fn prepare_inbound_message( @@ -266,19 +266,19 @@ where /// Returns callback which generates `BridgeMessage` from Polkadot XCM builder based on /// `expected_message_size` for benchmark. pub fn generate_xcm_builder_bridge_message_sample( - destination: InteriorMultiLocation, + destination: InteriorLocation, ) -> impl Fn(usize) -> MessagePayload { move |expected_message_size| -> MessagePayload { // For XCM bridge hubs, it is the message that // will be pushed further to some XCM queue (XCMP/UMP) - let location = xcm::VersionedInteriorMultiLocation::V3(destination); + let location = xcm::VersionedInteriorLocation::V4(destination.clone()); let location_encoded_size = location.encoded_size(); // we don't need to be super-precise with `expected_size` here let xcm_size = expected_message_size.saturating_sub(location_encoded_size); let xcm_data_size = xcm_size.saturating_sub( // minus empty instruction size - xcm::v3::Instruction::<()>::ExpectPallet { + Instruction::<()>::ExpectPallet { index: 0, name: vec![], module_name: vec![], @@ -294,8 +294,8 @@ pub fn generate_xcm_builder_bridge_message_sample( expected_message_size, location_encoded_size, xcm_size, xcm_data_size, ); - let xcm = xcm::VersionedXcm::<()>::V3( - vec![xcm::v3::Instruction::<()>::ExpectPallet { + let xcm = xcm::VersionedXcm::<()>::V4( + vec![Instruction::<()>::ExpectPallet { index: 0, name: vec![42; xcm_data_size], module_name: vec![], diff --git a/bridges/bin/runtime-common/src/messages_xcm_extension.rs b/bridges/bin/runtime-common/src/messages_xcm_extension.rs index 77c23db3b2ba..d6129891d716 100644 --- a/bridges/bin/runtime-common/src/messages_xcm_extension.rs +++ b/bridges/bin/runtime-common/src/messages_xcm_extension.rs @@ -125,14 +125,14 @@ impl< /// over the bridge. pub struct SenderAndLane { /// Sending chain relative location. - pub location: MultiLocation, + pub location: Location, /// Message lane, used by the sending chain. pub lane: LaneId, } impl SenderAndLane { /// Create new object using provided location and lane. - pub fn new(location: MultiLocation, lane: LaneId) -> Self { + pub fn new(location: Location, lane: LaneId) -> Self { SenderAndLane { location, lane } } } @@ -321,7 +321,7 @@ impl LocalXcmQueueManager { /// Send congested signal to the `sending_chain_location`. fn send_congested_signal(sender_and_lane: &SenderAndLane) -> Result<(), SendError> { if let Some(msg) = H::CongestedMessage::get() { - send_xcm::(sender_and_lane.location, msg)?; + send_xcm::(sender_and_lane.location.clone(), msg)?; OutboundLanesCongestedSignals::::insert( sender_and_lane.lane, true, @@ -333,7 +333,7 @@ impl LocalXcmQueueManager { /// Send `uncongested` signal to the `sending_chain_location`. fn send_uncongested_signal(sender_and_lane: &SenderAndLane) -> Result<(), SendError> { if let Some(msg) = H::UncongestedMessage::get() { - send_xcm::(sender_and_lane.location, msg)?; + send_xcm::(sender_and_lane.location.clone(), msg)?; OutboundLanesCongestedSignals::::remove( sender_and_lane.lane, ); @@ -353,7 +353,7 @@ mod tests { parameter_types! { pub TestSenderAndLane: SenderAndLane = SenderAndLane { - location: MultiLocation::new(1, X1(Parachain(1000))), + location: Location::new(1, [Parachain(1000)]), lane: TEST_LANE_ID, }; pub DummyXcmMessage: Xcm<()> = Xcm::new(); @@ -371,7 +371,7 @@ mod tests { type Ticket = (); fn validate( - _destination: &mut Option, + _destination: &mut Option, _message: &mut Option>, ) -> SendResult { Ok(((), Default::default())) diff --git a/bridges/modules/xcm-bridge-hub-router/src/benchmarking.rs b/bridges/modules/xcm-bridge-hub-router/src/benchmarking.rs index c4d1e3971e74..fe59b0389f38 100644 --- a/bridges/modules/xcm-bridge-hub-router/src/benchmarking.rs +++ b/bridges/modules/xcm-bridge-hub-router/src/benchmarking.rs @@ -37,10 +37,10 @@ pub trait Config: crate::Config { /// Returns destination which is valid for this router instance. /// (Needs to pass `T::Bridges`) /// Make sure that `SendXcm` will pass. - fn ensure_bridged_target_destination() -> MultiLocation { - MultiLocation::new( + fn ensure_bridged_target_destination() -> Location { + Location::new( Self::UniversalLocation::get().len() as u8, - X1(GlobalConsensus(Self::BridgedNetworkId::get().unwrap())), + [GlobalConsensus(Self::BridgedNetworkId::get().unwrap())], ) } } diff --git a/bridges/modules/xcm-bridge-hub-router/src/lib.rs b/bridges/modules/xcm-bridge-hub-router/src/lib.rs index cf51ef82412f..ab623860444a 100644 --- a/bridges/modules/xcm-bridge-hub-router/src/lib.rs +++ b/bridges/modules/xcm-bridge-hub-router/src/lib.rs @@ -80,7 +80,7 @@ pub mod pallet { type WeightInfo: WeightInfo; /// Universal location of this runtime. - type UniversalLocation: Get; + type UniversalLocation: Get; /// The bridged network that this config is for if specified. /// Also used for filtering `Bridges` by `BridgedNetworkId`. /// If not specified, allows all networks pass through. @@ -233,9 +233,9 @@ type ViaBridgeHubExporter = SovereignPaidRemoteExporter< impl, I: 'static> ExporterFor for Pallet { fn exporter_for( network: &NetworkId, - remote_location: &InteriorMultiLocation, + remote_location: &InteriorLocation, message: &Xcm<()>, - ) -> Option<(MultiLocation, Option)> { + ) -> Option<(Location, Option)> { // ensure that the message is sent to the expected bridged network (if specified). if let Some(bridged_network) = T::BridgedNetworkId::get() { if *network != bridged_network { @@ -266,7 +266,7 @@ impl, I: 'static> ExporterFor for Pallet { // take `base_fee` from `T::Brides`, but it has to be the same `T::FeeAsset` let base_fee = match maybe_payment { Some(payment) => match payment { - MultiAsset { fun: Fungible(amount), id } if id.eq(&T::FeeAsset::get()) => amount, + Asset { fun: Fungible(amount), id } if id.eq(&T::FeeAsset::get()) => amount, invalid_asset => { log::error!( target: LOG_TARGET, @@ -316,7 +316,7 @@ impl, I: 'static> SendXcm for Pallet { type Ticket = (u32, ::Ticket); fn validate( - dest: &mut Option, + dest: &mut Option, xcm: &mut Option>, ) -> SendResult { // we won't have an access to `dest` and `xcm` in the `delvier` method, so precompute @@ -430,7 +430,7 @@ mod tests { run_test(|| { assert_eq!( send_xcm::( - MultiLocation::new(2, X2(GlobalConsensus(Rococo), Parachain(1000))), + Location::new(2, [GlobalConsensus(Rococo), Parachain(1000)]), vec![].into(), ), Err(SendError::NotApplicable), @@ -443,7 +443,7 @@ mod tests { run_test(|| { assert_eq!( send_xcm::( - MultiLocation::new(2, X2(GlobalConsensus(Rococo), Parachain(1000))), + Location::new(2, [GlobalConsensus(Rococo), Parachain(1000)]), vec![ClearOrigin; HARD_MESSAGE_SIZE_LIMIT as usize].into(), ), Err(SendError::ExceedsMaxMessageSize), @@ -454,14 +454,14 @@ mod tests { #[test] fn returns_proper_delivery_price() { run_test(|| { - let dest = MultiLocation::new(2, X1(GlobalConsensus(BridgedNetworkId::get()))); + let dest = Location::new(2, [GlobalConsensus(BridgedNetworkId::get())]); let xcm: Xcm<()> = vec![ClearOrigin].into(); let msg_size = xcm.encoded_size(); // initially the base fee is used: `BASE_FEE + BYTE_FEE * msg_size + HRMP_FEE` let expected_fee = BASE_FEE + BYTE_FEE * (msg_size as u128) + HRMP_FEE; assert_eq!( - XcmBridgeHubRouter::validate(&mut Some(dest), &mut Some(xcm.clone())) + XcmBridgeHubRouter::validate(&mut Some(dest.clone()), &mut Some(xcm.clone())) .unwrap() .1 .get(0), @@ -490,10 +490,7 @@ mod tests { let old_bridge = XcmBridgeHubRouter::bridge(); assert_eq!( send_xcm::( - MultiLocation::new( - 2, - X2(GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)) - ), + Location::new(2, [GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)]), vec![ClearOrigin].into(), ) .map(drop), @@ -513,10 +510,7 @@ mod tests { let old_bridge = XcmBridgeHubRouter::bridge(); assert_eq!( send_xcm::( - MultiLocation::new( - 2, - X2(GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)) - ), + Location::new(2, [GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)]), vec![ClearOrigin].into(), ) .map(drop), @@ -538,10 +532,7 @@ mod tests { let old_bridge = XcmBridgeHubRouter::bridge(); assert_eq!( send_xcm::( - MultiLocation::new( - 2, - X2(GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)) - ), + Location::new(2, [GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)]), vec![ClearOrigin].into(), ) .map(drop), diff --git a/bridges/modules/xcm-bridge-hub-router/src/mock.rs b/bridges/modules/xcm-bridge-hub-router/src/mock.rs index 2152b4eb28f3..0e80a23ed98a 100644 --- a/bridges/modules/xcm-bridge-hub-router/src/mock.rs +++ b/bridges/modules/xcm-bridge-hub-router/src/mock.rs @@ -50,9 +50,9 @@ construct_runtime! { parameter_types! { pub ThisNetworkId: NetworkId = Polkadot; pub BridgedNetworkId: NetworkId = Kusama; - pub UniversalLocation: InteriorMultiLocation = X2(GlobalConsensus(ThisNetworkId::get()), Parachain(1000)); - pub SiblingBridgeHubLocation: MultiLocation = ParentThen(X1(Parachain(1002))).into(); - pub BridgeFeeAsset: AssetId = MultiLocation::parent().into(); + pub UniversalLocation: InteriorLocation = [GlobalConsensus(ThisNetworkId::get()), Parachain(1000)].into(); + pub SiblingBridgeHubLocation: Location = ParentThen([Parachain(1002)].into()).into(); + pub BridgeFeeAsset: AssetId = Location::parent().into(); pub BridgeTable: Vec = vec![ NetworkExportTableItem::new( @@ -117,7 +117,7 @@ impl SendXcm for TestToBridgeHubSender { type Ticket = (); fn validate( - _destination: &mut Option, + _destination: &mut Option, _message: &mut Option>, ) -> SendResult { Ok(((), (BridgeFeeAsset::get(), HRMP_FEE).into())) diff --git a/cumulus/pallets/xcmp-queue/src/lib.rs b/cumulus/pallets/xcmp-queue/src/lib.rs index d687f83d8b3e..2958b94edacb 100644 --- a/cumulus/pallets/xcmp-queue/src/lib.rs +++ b/cumulus/pallets/xcmp-queue/src/lib.rs @@ -135,7 +135,7 @@ pub mod pallet { /// The origin that is allowed to resume or suspend the XCMP queue. type ControllerOrigin: EnsureOrigin; - /// The conversion function used to attempt to convert an XCM `MultiLocation` origin to a + /// The conversion function used to attempt to convert an XCM `Location` origin to a /// superuser origin. type ControllerOriginConverter: ConvertOrigin; @@ -913,14 +913,14 @@ impl SendXcm for Pallet { type Ticket = (ParaId, VersionedXcm<()>); fn validate( - dest: &mut Option, + dest: &mut Option, msg: &mut Option>, ) -> SendResult<(ParaId, VersionedXcm<()>)> { let d = dest.take().ok_or(SendError::MissingArgument)?; - match &d { + match d.unpack() { // An HRMP message for a sibling parachain. - MultiLocation { parents: 1, interior: X1(Parachain(id)) } => { + (1, [Parachain(id)]) => { let xcm = msg.take().ok_or(SendError::MissingArgument)?; let id = ParaId::from(*id); let price = T::PriceForSiblingDelivery::price_for_delivery(id, &xcm); diff --git a/cumulus/pallets/xcmp-queue/src/mock.rs b/cumulus/pallets/xcmp-queue/src/mock.rs index 7c3a3bd1bd02..ecea95230883 100644 --- a/cumulus/pallets/xcmp-queue/src/mock.rs +++ b/cumulus/pallets/xcmp-queue/src/mock.rs @@ -121,8 +121,8 @@ impl cumulus_pallet_parachain_system::Config for Test { } parameter_types! { - pub const RelayChain: MultiLocation = MultiLocation::parent(); - pub UniversalLocation: InteriorMultiLocation = X1(Parachain(1u32)); + pub const RelayChain: Location = Location::parent(); + pub UniversalLocation: InteriorLocation = [Parachain(1u32)].into(); pub UnitWeightCost: Weight = Weight::from_parts(1_000_000, 1024); pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 64; @@ -134,7 +134,7 @@ pub type LocalAssetTransactor = CurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: + // Do a simple punn to convert an AccountId32 Location into a native chain account ID: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -183,17 +183,14 @@ impl ConvertOrigin for SystemParachainAsSuperuser { fn convert_origin( - origin: impl Into, + origin: impl Into, kind: OriginKind, - ) -> Result { + ) -> Result { let origin = origin.into(); if kind == OriginKind::Superuser && matches!( - origin, - MultiLocation { - parents: 1, - interior: X1(Parachain(id)), - } if ParaId::from(id).is_system(), + origin.unpack(), + (1, [Parachain(id)]) if ParaId::from(*id).is_system(), ) { Ok(RuntimeOrigin::root()) } else { @@ -252,7 +249,7 @@ impl> EnqueueMessage for EnqueueToLocalStorage parameter_types! { /// The asset ID for the asset that we use to pay for message delivery fees. - pub FeeAssetId: AssetId = Concrete(RelayChain::get()); + pub FeeAssetId: AssetId = AssetId(RelayChain::get()); /// The base fee for the message delivery fees. pub const BaseDeliveryFee: Balance = 300_000_000; /// The fee per byte diff --git a/cumulus/pallets/xcmp-queue/src/tests.rs b/cumulus/pallets/xcmp-queue/src/tests.rs index 30dba6ead340..a3a9fdc2e454 100644 --- a/cumulus/pallets/xcmp-queue/src/tests.rs +++ b/cumulus/pallets/xcmp-queue/src/tests.rs @@ -340,11 +340,11 @@ struct OkFixedXcmHashWithAssertingRequiredInputsSender; impl OkFixedXcmHashWithAssertingRequiredInputsSender { const FIXED_XCM_HASH: [u8; 32] = [9; 32]; - fn fixed_delivery_asset() -> MultiAssets { - MultiAssets::new() + fn fixed_delivery_asset() -> Assets { + Assets::new() } - fn expected_delivery_result() -> Result<(XcmHash, MultiAssets), SendError> { + fn expected_delivery_result() -> Result<(XcmHash, Assets), SendError> { Ok((Self::FIXED_XCM_HASH, Self::fixed_delivery_asset())) } } @@ -352,7 +352,7 @@ impl SendXcm for OkFixedXcmHashWithAssertingRequiredInputsSender { type Ticket = (); fn validate( - destination: &mut Option, + destination: &mut Option, message: &mut Option>, ) -> SendResult { assert!(destination.is_some()); @@ -399,8 +399,8 @@ fn xcmp_queue_consumes_dest_and_msg_on_ok_validate() { let message = Xcm(vec![Trap(5)]); // XcmpQueue - check dest/msg is valid - let dest = (Parent, X1(Parachain(5555))); - let mut dest_wrapper = Some(dest.into()); + let dest: Location = (Parent, Parachain(5555)).into(); + let mut dest_wrapper = Some(dest.clone()); let mut msg_wrapper = Some(message.clone()); new_test_ext().execute_with(|| { @@ -423,7 +423,7 @@ fn xcmp_queue_consumes_dest_and_msg_on_ok_validate() { #[test] fn xcmp_queue_validate_nested_xcm_works() { - let dest = (Parent, X1(Parachain(5555))); + let dest = (Parent, Parachain(5555)); // Message that is not too deeply nested: let mut good = Xcm(vec![ClearOrigin]); for _ in 0..MAX_XCM_DECODE_DEPTH - 1 { @@ -448,7 +448,7 @@ fn xcmp_queue_validate_nested_xcm_works() { #[test] fn send_xcm_nested_works() { - let dest = (Parent, X1(Parachain(HRMP_PARA_ID))); + let dest = (Parent, Parachain(HRMP_PARA_ID)); // Message that is not too deeply nested: let mut good = Xcm(vec![ClearOrigin]); for _ in 0..MAX_XCM_DECODE_DEPTH - 1 { @@ -462,7 +462,7 @@ fn send_xcm_nested_works() { XcmpQueue::take_outbound_messages(usize::MAX), vec![( HRMP_PARA_ID.into(), - (XcmpMessageFormat::ConcatenatedVersionedXcm, VersionedXcm::V3(good.clone())) + (XcmpMessageFormat::ConcatenatedVersionedXcm, VersionedXcm::V4(good.clone())) .encode(), )] ); @@ -481,7 +481,7 @@ fn hrmp_signals_are_prioritized() { let message = Xcm(vec![Trap(5)]); let sibling_para_id = ParaId::from(12345); - let dest = (Parent, X1(Parachain(sibling_para_id.into()))); + let dest = (Parent, Parachain(sibling_para_id.into())); let mut dest_wrapper = Some(dest.into()); let mut msg_wrapper = Some(message.clone()); @@ -518,7 +518,7 @@ fn hrmp_signals_are_prioritized() { // Without a signal we get the messages in order: let mut expected_msg = XcmpMessageFormat::ConcatenatedVersionedXcm.encode(); for _ in 0..31 { - expected_msg.extend(VersionedXcm::V3(message.clone()).encode()); + expected_msg.extend(VersionedXcm::V4(message.clone()).encode()); } hypothetically!({ @@ -597,7 +597,7 @@ fn take_first_concatenated_xcm_good_recursion_depth_works() { for _ in 0..MAX_XCM_DECODE_DEPTH - 1 { good = Xcm(vec![SetAppendix(good)]); } - let good = VersionedXcm::V3(good); + let good = VersionedXcm::V4(good); let page = good.encode(); assert_ok!(XcmpQueue::take_first_concatenated_xcm(&mut &page[..], &mut WeightMeter::new())); @@ -610,7 +610,7 @@ fn take_first_concatenated_xcm_good_bad_depth_errors() { for _ in 0..MAX_XCM_DECODE_DEPTH { bad = Xcm(vec![SetAppendix(bad)]); } - let bad = VersionedXcm::V3(bad); + let bad = VersionedXcm::V4(bad); let page = bad.encode(); assert_err!( @@ -706,12 +706,12 @@ fn lazy_migration_noop_when_out_of_weight() { fn xcmp_queue_send_xcm_works() { new_test_ext().execute_with(|| { let sibling_para_id = ParaId::from(12345); - let dest = (Parent, X1(Parachain(sibling_para_id.into()))).into(); + let dest: Location = (Parent, Parachain(sibling_para_id.into())).into(); let msg = Xcm(vec![ClearOrigin]); // try to send without opened HRMP channel to the sibling_para_id assert_eq!( - send_xcm::(dest, msg.clone()), + send_xcm::(dest.clone(), msg.clone()), Err(SendError::Transport("NoChannel")), ); @@ -737,7 +737,7 @@ fn verify_fee_factor_increase_and_decrease() { use sp_runtime::FixedU128; let sibling_para_id = ParaId::from(12345); - let destination = (Parent, Parachain(sibling_para_id.into())).into(); + let destination: Location = (Parent, Parachain(sibling_para_id.into())).into(); let xcm = Xcm(vec![ClearOrigin; 100]); let versioned_xcm = VersionedXcm::from(xcm.clone()); let mut xcmp_message = XcmpMessageFormat::ConcatenatedVersionedXcm.encode(); @@ -762,15 +762,15 @@ fn verify_fee_factor_increase_and_decrease() { // Fee factor is only increased in `send_fragment`, which is called by `send_xcm`. // When queue is not congested, fee factor doesn't change. - assert_ok!(send_xcm::(destination, xcm.clone())); // Size 104 - assert_ok!(send_xcm::(destination, xcm.clone())); // Size 208 - assert_ok!(send_xcm::(destination, xcm.clone())); // Size 312 - assert_ok!(send_xcm::(destination, xcm.clone())); // Size 416 + assert_ok!(send_xcm::(destination.clone(), xcm.clone())); // Size 104 + assert_ok!(send_xcm::(destination.clone(), xcm.clone())); // Size 208 + assert_ok!(send_xcm::(destination.clone(), xcm.clone())); // Size 312 + assert_ok!(send_xcm::(destination.clone(), xcm.clone())); // Size 416 assert_eq!(DeliveryFeeFactor::::get(sibling_para_id), initial); // Sending the message right now is cheap let (_, delivery_fees) = - validate_send::(destination, xcm.clone()).expect("message can be sent; qed"); + validate_send::(destination.clone(), xcm.clone()).expect("message can be sent; qed"); let Fungible(delivery_fee_amount) = delivery_fees.inner()[0].fun else { unreachable!("asset is fungible; qed"); }; @@ -780,18 +780,18 @@ fn verify_fee_factor_increase_and_decrease() { // When we get to half of `max_total_size`, because `THRESHOLD_FACTOR` is 2, // then the fee factor starts to increase. - assert_ok!(send_xcm::(destination, xcm.clone())); // Size 520 + assert_ok!(send_xcm::(destination.clone(), xcm.clone())); // Size 520 assert_eq!(DeliveryFeeFactor::::get(sibling_para_id), FixedU128::from_float(1.05)); for _ in 0..12 { // We finish at size 929 - assert_ok!(send_xcm::(destination, smaller_xcm.clone())); + assert_ok!(send_xcm::(destination.clone(), smaller_xcm.clone())); } assert!(DeliveryFeeFactor::::get(sibling_para_id) > FixedU128::from_float(1.88)); // Sending the message right now is expensive let (_, delivery_fees) = - validate_send::(destination, xcm.clone()).expect("message can be sent; qed"); + validate_send::(destination.clone(), xcm.clone()).expect("message can be sent; qed"); let Fungible(delivery_fee_amount) = delivery_fees.inner()[0].fun else { unreachable!("asset is fungible; qed"); }; diff --git a/cumulus/parachain-template/runtime/src/xcm_config.rs b/cumulus/parachain-template/runtime/src/xcm_config.rs index 752137c96f18..48c9ec27f727 100644 --- a/cumulus/parachain-template/runtime/src/xcm_config.rs +++ b/cumulus/parachain-template/runtime/src/xcm_config.rs @@ -3,8 +3,8 @@ use super::{ Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee, XcmpQueue, }; use frame_support::{ - match_types, parameter_types, - traits::{ConstU32, Everything, Nothing}, + parameter_types, + traits::{ConstU32, Contains, Everything, Nothing}, weights::Weight, }; use frame_system::EnsureRoot; @@ -23,13 +23,13 @@ use xcm_builder::{ use xcm_executor::XcmExecutor; parameter_types! { - pub const RelayLocation: MultiLocation = MultiLocation::parent(); + pub const RelayLocation: Location = Location::parent(); pub const RelayNetwork: Option = None; pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); + pub UniversalLocation: InteriorLocation = Parachain(ParachainInfo::parachain_id().into()).into(); } -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( @@ -47,7 +47,7 @@ pub type LocalAssetTransactor = CurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: + // Do a simple punn to convert an AccountId32 Location into a native chain account ID: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -83,11 +83,11 @@ parameter_types! { pub const MaxAssetsIntoHolding: u32 = 64; } -match_types! { - pub type ParentOrParentsExecutivePlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) } - }; +pub struct ParentOrParentsExecutivePlurality; +impl Contains for ParentOrParentsExecutivePlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [Plurality { id: BodyId::Executive, .. }])) + } } pub type Barrier = TrailingSetTopicAsId< diff --git a/cumulus/parachains/common/src/impls.rs b/cumulus/parachains/common/src/impls.rs index 81d78baba548..95f137c72179 100644 --- a/cumulus/parachains/common/src/impls.rs +++ b/cumulus/parachains/common/src/impls.rs @@ -23,7 +23,7 @@ use frame_support::traits::{ use pallet_asset_tx_payment::HandleCredit; use sp_runtime::traits::Zero; use sp_std::marker::PhantomData; -use xcm::latest::{AssetId, Fungibility::Fungible, MultiAsset, MultiLocation}; +use xcm::latest::{Asset, AssetId, Fungibility::Fungible, Location}; /// Type alias to conveniently refer to the `Currency::NegativeImbalance` associated type. pub type NegativeImbalance = as Currency< @@ -109,11 +109,11 @@ where /// Asset filter that allows all assets from a certain location. pub struct AssetsFrom(PhantomData); -impl> ContainsPair for AssetsFrom { - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool { +impl> ContainsPair for AssetsFrom { + fn contains(asset: &Asset, origin: &Location) -> bool { let loc = T::get(); &loc == origin && - matches!(asset, MultiAsset { id: AssetId::Concrete(asset_loc), fun: Fungible(_a) } + matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) } if asset_loc.match_and_split(&loc).is_some()) } } @@ -266,13 +266,13 @@ mod tests { #[test] fn assets_from_filters_correctly() { parameter_types! { - pub SomeSiblingParachain: MultiLocation = MultiLocation::new(1, X1(Parachain(1234))); + pub SomeSiblingParachain: Location = Location::new(1, [Parachain(1234)]); } let asset_location = SomeSiblingParachain::get() .pushed_with_interior(GeneralIndex(42)) - .expect("multilocation will only have 2 junctions; qed"); - let asset = MultiAsset { id: Concrete(asset_location), fun: 1_000_000u128.into() }; + .expect("location will only have 2 junctions; qed"); + let asset = Asset { id: AssetId(asset_location), fun: 1_000_000u128.into() }; assert!( AssetsFrom::::contains(&asset, &SomeSiblingParachain::get()), "AssetsFrom should allow assets from any of its interior locations" diff --git a/cumulus/parachains/common/src/xcm_config.rs b/cumulus/parachains/common/src/xcm_config.rs index 4b0215d672b2..1db56da0d2d7 100644 --- a/cumulus/parachains/common/src/xcm_config.rs +++ b/cumulus/parachains/common/src/xcm_config.rs @@ -66,57 +66,55 @@ where } } -/// Accepts an asset if it is a native asset from a particular `MultiLocation`. -pub struct ConcreteNativeAssetFrom(PhantomData); -impl> ContainsPair - for ConcreteNativeAssetFrom +/// Accepts an asset if it is a native asset from a particular `Location`. +pub struct ConcreteNativeAssetFrom(PhantomData); +impl> ContainsPair + for ConcreteNativeAssetFrom { - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool { + fn contains(asset: &Asset, origin: &Location) -> bool { log::trace!(target: "xcm::filter_asset_location", "ConcreteNativeAsset asset: {:?}, origin: {:?}, location: {:?}", - asset, origin, Location::get()); - matches!(asset.id, Concrete(ref id) if id == origin && origin == &Location::get()) + asset, origin, LocationValue::get()); + matches!(asset.id, AssetId(ref id) if id == origin && origin == &LocationValue::get()) } } pub struct RelayOrOtherSystemParachains< - SystemParachainMatcher: Contains, + SystemParachainMatcher: Contains, Runtime: parachain_info::Config, > { _runtime: PhantomData<(SystemParachainMatcher, Runtime)>, } -impl, Runtime: parachain_info::Config> - Contains for RelayOrOtherSystemParachains +impl, Runtime: parachain_info::Config> + Contains for RelayOrOtherSystemParachains { - fn contains(l: &MultiLocation) -> bool { + fn contains(l: &Location) -> bool { let self_para_id: u32 = parachain_info::Pallet::::get().into(); - if let MultiLocation { parents: 0, interior: X1(Parachain(para_id)) } = l { + if let (0, [Parachain(para_id)]) = l.unpack() { if *para_id == self_para_id { return false } } - matches!(l, MultiLocation { parents: 1, interior: Here }) || - SystemParachainMatcher::contains(l) + matches!(l.unpack(), (1, HERE)) || SystemParachainMatcher::contains(l) } } /// Accepts an asset if it is a concrete asset from the system (Relay Chain or system parachain). pub struct ConcreteAssetFromSystem(PhantomData); -impl> ContainsPair +impl> ContainsPair for ConcreteAssetFromSystem { - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool { + fn contains(asset: &Asset, origin: &Location) -> bool { log::trace!(target: "xcm::contains", "ConcreteAssetFromSystem asset: {:?}, origin: {:?}", asset, origin); - let is_system = match origin { + let is_system = match origin.unpack() { // The Relay Chain - MultiLocation { parents: 1, interior: Here } => true, + (1, []) => true, // System parachain - MultiLocation { parents: 1, interior: X1(Parachain(id)) } => - ParaId::from(*id).is_system(), + (1, [Parachain(id)]) => ParaId::from(*id).is_system(), // Others _ => false, }; - matches!(asset.id, Concrete(id) if id == AssetLocation::get()) && is_system + asset.id.0 == AssetLocation::get() && is_system } } @@ -125,18 +123,18 @@ mod tests { use frame_support::parameter_types; use super::{ - ConcreteAssetFromSystem, ContainsPair, GeneralIndex, Here, MultiAsset, MultiLocation, + ConcreteAssetFromSystem, ContainsPair, GeneralIndex, Here, Asset, Location, PalletInstance, Parachain, Parent, }; parameter_types! { - pub const RelayLocation: MultiLocation = MultiLocation::parent(); + pub const RelayLocation: Location = Location::parent(); } #[test] fn concrete_asset_from_relay_works() { - let expected_asset: MultiAsset = (Parent, 1000000).into(); - let expected_origin: MultiLocation = (Parent, Here).into(); + let expected_asset: Asset = (Parent, 1000000).into(); + let expected_origin: Location = (Parent, Here).into(); assert!(>::contains( &expected_asset, @@ -146,12 +144,12 @@ mod tests { #[test] fn concrete_asset_from_sibling_system_para_fails_for_wrong_asset() { - let unexpected_assets: Vec = vec![ + let unexpected_assets: Vec = vec![ (Here, 1000000).into(), ((PalletInstance(50), GeneralIndex(1)), 1000000).into(), ((Parent, Parachain(1000), PalletInstance(50), GeneralIndex(1)), 1000000).into(), ]; - let expected_origin: MultiLocation = (Parent, Parachain(1000)).into(); + let expected_origin: Location = (Parent, Parachain(1000)).into(); unexpected_assets.iter().for_each(|asset| { assert!(!>::contains(asset, &expected_origin)); @@ -170,10 +168,10 @@ mod tests { (2001, false), // Not a System Parachain ]; - let expected_asset: MultiAsset = (Parent, 1000000).into(); + let expected_asset: Asset = (Parent, 1000000).into(); for (para_id, expected_result) in test_data { - let origin: MultiLocation = (Parent, Parachain(para_id)).into(); + let origin: Location = (Parent, Parachain(para_id)).into(); assert_eq!( expected_result, >::contains(&expected_asset, &origin) diff --git a/cumulus/parachains/integration-tests/emulated/bridges/bridge-hub-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/bridges/bridge-hub-rococo/src/lib.rs new file mode 100644 index 000000000000..d8ba99dbe9a6 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/bridges/bridge-hub-rococo/src/lib.rs @@ -0,0 +1,61 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub use bp_messages::LaneId; +pub use frame_support::assert_ok; +pub use integration_tests_common::{ + constants::{ + bridge_hub_rococo::ED as BRIDGE_HUB_ROCOCO_ED, rococo::ED as ROCOCO_ED, + PROOF_SIZE_THRESHOLD, REF_TIME_THRESHOLD, XCM_V3, + }, + test_parachain_is_trusted_teleporter, + xcm_helpers::{xcm_transact_paid_execution, xcm_transact_unpaid_execution}, + AssetHubRococo, AssetHubRococoReceiver, AssetHubWococo, BridgeHubRococo, BridgeHubRococoPallet, + BridgeHubRococoSender, BridgeHubWococo, PenpalRococoA, Rococo, RococoPallet, +}; +pub use parachains_common::{AccountId, Balance}; +pub use xcm::prelude::{AccountId32 as AccountId32Junction, *}; +pub use xcm_emulator::{ + assert_expected_events, bx, helpers::weight_within_threshold, Chain, Parachain as Para, + RelayChain as Relay, Test, TestArgs, TestContext, TestExt, +}; + +pub const ASSET_ID: u32 = 1; +pub const ASSET_MIN_BALANCE: u128 = 1000; +pub const ASSETS_PALLET_ID: u8 = 50; + +pub type RelayToSystemParaTest = Test; +pub type SystemParaToRelayTest = Test; +pub type SystemParaToParaTest = Test; + +/// Returns a `TestArgs` instance to de used for the Relay Chain accross integraton tests +pub fn relay_test_args(amount: Balance) -> TestArgs { + TestArgs { + dest: Rococo::child_location_of(AssetHubRococo::para_id()), + beneficiary: AccountId32Junction { + network: None, + id: AssetHubRococoReceiver::get().into(), + } + .into(), + amount, + assets: (Here, amount).into(), + asset_id: None, + fee_asset_item: 0, + weight_limit: WeightLimit::Unlimited, + } +} + +#[cfg(test)] +mod tests; diff --git a/cumulus/parachains/integration-tests/emulated/common/src/impls.rs b/cumulus/parachains/integration-tests/emulated/common/src/impls.rs index 82f27b932008..3ed106cd5d9e 100644 --- a/cumulus/parachains/integration-tests/emulated/common/src/impls.rs +++ b/cumulus/parachains/integration-tests/emulated/common/src/impls.rs @@ -38,8 +38,8 @@ pub use polkadot_runtime_parachains::{ inclusion::{AggregateMessageOrigin, UmpQueueId}, }; pub use xcm::{ - prelude::{MultiLocation, OriginKind, Outcome, VersionedXcm}, - v3::Error, + prelude::{Location, OriginKind, Outcome, VersionedXcm}, + v4::Error as XcmError, DoubleEncoded, }; @@ -203,7 +203,7 @@ macro_rules! impl_assert_events_helpers_for_relay_chain { Self, vec![ [<$chain RuntimeEvent>]::::XcmPallet( - $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Complete(weight) } + $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Complete { used: weight } } ) => { weight: $crate::impls::weight_within_threshold( ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), @@ -218,21 +218,21 @@ macro_rules! impl_assert_events_helpers_for_relay_chain { /// Asserts a dispatchable is incompletely executed and XCM sent pub fn assert_xcm_pallet_attempted_incomplete( expected_weight: Option<$crate::impls::Weight>, - expected_error: Option<$crate::impls::Error>, + expected_error: Option<$crate::impls::XcmError>, ) { $crate::impls::assert_expected_events!( Self, vec![ // Dispatchable is properly executed and XCM message sent [<$chain RuntimeEvent>]::::XcmPallet( - $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Incomplete(weight, error) } + $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Incomplete { used: weight, error } } ) => { weight: $crate::impls::weight_within_threshold( ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), expected_weight.unwrap_or(*weight), *weight ), - error: *error == expected_error.unwrap_or(*error), + error: *error == expected_error.unwrap_or((*error).into()).into(), }, ] ); @@ -358,7 +358,7 @@ macro_rules! impl_send_transact_helpers_for_relay_chain { ::execute_with(|| { let root_origin = ::RuntimeOrigin::root(); - let destination: $crate::impls::MultiLocation = ::child_location_of(recipient); + let destination: $crate::impls::Location = ::child_location_of(recipient); let xcm = $crate::impls::xcm_transact_unpaid_execution(call, $crate::impls::OriginKind::Superuser); // Send XCM `Transact` @@ -410,7 +410,7 @@ macro_rules! impl_assert_events_helpers_for_parachain { Self, vec![ [<$chain RuntimeEvent>]::::PolkadotXcm( - $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Complete(weight) } + $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Complete { used: weight } } ) => { weight: $ignore_weight || $crate::impls::weight_within_threshold( ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), @@ -425,36 +425,36 @@ macro_rules! impl_assert_events_helpers_for_parachain { /// Asserts a dispatchable is incompletely executed and XCM sent pub fn assert_xcm_pallet_attempted_incomplete( expected_weight: Option<$crate::impls::Weight>, - expected_error: Option<$crate::impls::Error>, + expected_error: Option<$crate::impls::XcmError>, ) { $crate::impls::assert_expected_events!( Self, vec![ // Dispatchable is properly executed and XCM message sent [<$chain RuntimeEvent>]::::PolkadotXcm( - $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Incomplete(weight, error) } + $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Incomplete { used: weight, error } } ) => { weight: $ignore_weight || $crate::impls::weight_within_threshold( ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), expected_weight.unwrap_or(*weight), *weight ), - error: *error == expected_error.unwrap_or(*error), + error: *error == expected_error.unwrap_or((*error).into()).into(), }, ] ); } /// Asserts a dispatchable throws and error when trying to be sent - pub fn assert_xcm_pallet_attempted_error(expected_error: Option<$crate::impls::Error>) { + pub fn assert_xcm_pallet_attempted_error(expected_error: Option<$crate::impls::XcmError>) { $crate::impls::assert_expected_events!( Self, vec![ // Execution fails in the origin with `Barrier` [<$chain RuntimeEvent>]::::PolkadotXcm( - $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Error(error) } + $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Error { error } } ) => { - error: *error == expected_error.unwrap_or(*error), + error: *error == expected_error.unwrap_or((*error).into()).into(), }, ] ); diff --git a/cumulus/parachains/integration-tests/emulated/common/src/lib.rs b/cumulus/parachains/integration-tests/emulated/common/src/lib.rs index 952b053f2aa2..0443a97571ab 100644 --- a/cumulus/parachains/integration-tests/emulated/common/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/common/src/lib.rs @@ -42,6 +42,7 @@ use polkadot_service::chain_spec::get_authority_keys_from_seed_no_beefy; pub const XCM_V2: u32 = 2; pub const XCM_V3: u32 = 3; +pub const XCM_V4: u32 = 4; pub const REF_TIME_THRESHOLD: u64 = 33; pub const PROOF_SIZE_THRESHOLD: u64 = 33; diff --git a/cumulus/parachains/integration-tests/emulated/common/src/macros.rs b/cumulus/parachains/integration-tests/emulated/common/src/macros.rs index 6ea3524ed4a3..cb9338d6d34d 100644 --- a/cumulus/parachains/integration-tests/emulated/common/src/macros.rs +++ b/cumulus/parachains/integration-tests/emulated/common/src/macros.rs @@ -48,7 +48,7 @@ macro_rules! test_parachain_is_trusted_teleporter { <$receiver_para as $crate::macros::Chain>::account_data_of(receiver.clone()).free; let para_destination = <$sender_para>::sibling_location_of(<$receiver_para>::para_id()); - let beneficiary: MultiLocation = + let beneficiary: Location = $crate::macros::AccountId32 { network: None, id: receiver.clone().into() }.into(); // Send XCM message from Origin Parachain @@ -57,8 +57,8 @@ macro_rules! test_parachain_is_trusted_teleporter { <$sender_para>::execute_with(|| { assert_ok!(<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::limited_teleport_assets( origin.clone(), - bx!(para_destination.into()), - bx!(beneficiary.into()), + bx!(para_destination.clone().into()), + bx!(beneficiary.clone().into()), bx!($assets.clone().into()), fee_asset_item, weight_limit.clone(), diff --git a/cumulus/parachains/integration-tests/emulated/common/src/xcm_helpers.rs b/cumulus/parachains/integration-tests/emulated/common/src/xcm_helpers.rs index 47e92ed075fa..733921bbb160 100644 --- a/cumulus/parachains/integration-tests/emulated/common/src/xcm_helpers.rs +++ b/cumulus/parachains/integration-tests/emulated/common/src/xcm_helpers.rs @@ -23,12 +23,12 @@ use xcm::{prelude::*, DoubleEncoded}; pub fn xcm_transact_paid_execution( call: DoubleEncoded<()>, origin_kind: OriginKind, - native_asset: MultiAsset, + native_asset: Asset, beneficiary: AccountId, ) -> VersionedXcm<()> { let weight_limit = WeightLimit::Unlimited; let require_weight_at_most = Weight::from_parts(1000000000, 200000); - let native_assets: MultiAssets = native_asset.clone().into(); + let native_assets: Assets = native_asset.clone().into(); VersionedXcm::from(Xcm(vec![ WithdrawAsset(native_assets), @@ -37,9 +37,9 @@ pub fn xcm_transact_paid_execution( RefundSurplus, DepositAsset { assets: All.into(), - beneficiary: MultiLocation { + beneficiary: Location { parents: 0, - interior: X1(AccountId32 { network: None, id: beneficiary.into() }), + interior: [AccountId32 { network: None, id: beneficiary.into() }].into(), }, }, ])) diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/lib.rs index 3ff8c37c6465..1d10dba17569 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/lib.rs @@ -68,7 +68,7 @@ pub type ParaToSystemParaTest = Test; /// Returns a `TestArgs` instance to be used for the Relay Chain across integration tests pub fn relay_test_args( - dest: MultiLocation, + dest: Location, beneficiary_id: AccountId32, amount: Balance, ) -> TestArgs { @@ -85,10 +85,10 @@ pub fn relay_test_args( /// Returns a `TestArgs` instance to be used by parachains across integration tests pub fn para_test_args( - dest: MultiLocation, + dest: Location, beneficiary_id: AccountId32, amount: Balance, - assets: MultiAssets, + assets: Assets, asset_id: Option, fee_asset_item: u32, ) -> TestArgs { diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/reserve_transfer.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/reserve_transfer.rs index d0e9b72176bc..70912c6b8981 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/reserve_transfer.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/reserve_transfer.rs @@ -32,7 +32,7 @@ fn relay_to_para_sender_assertions(t: RelayToParaTest) { ) => { from: *from == t.sender.account_id, to: *to == Rococo::sovereign_account_id_of( - t.args.dest + t.args.dest.clone() ), amount: *amount == t.args.amount, }, @@ -70,7 +70,7 @@ fn system_para_to_para_sender_assertions(t: SystemParaToParaTest) { ) => { from: *from == t.sender.account_id, to: *to == AssetHubRococo::sovereign_account_id_of( - t.args.dest + t.args.dest.clone() ), amount: *amount == t.args.amount, }, @@ -153,7 +153,7 @@ fn system_para_to_para_assets_sender_assertions(t: SystemParaToParaTest) { asset_id: *asset_id == ASSET_ID, from: *from == t.sender.account_id, to: *to == AssetHubRococo::sovereign_account_id_of( - t.args.dest + t.args.dest.clone() ), amount: *amount == t.args.amount, }, @@ -213,10 +213,10 @@ fn para_to_system_para_limited_reserve_transfer_assets(t: ParaToSystemParaTest) fn reserve_transfer_native_asset_from_relay_to_system_para_fails() { let signed_origin = ::RuntimeOrigin::signed(RococoSender::get().into()); let destination = Rococo::child_location_of(AssetHubRococo::para_id()); - let beneficiary: MultiLocation = + let beneficiary: Location = AccountId32Junction { network: None, id: AssetHubRococoReceiver::get().into() }.into(); let amount_to_send: Balance = ROCOCO_ED * 1000; - let assets: MultiAssets = (Here, amount_to_send).into(); + let assets: Assets = (Here, amount_to_send).into(); let fee_asset_item = 0; // this should fail @@ -248,11 +248,11 @@ fn reserve_transfer_native_asset_from_system_para_to_relay_fails() { ::RuntimeOrigin::signed(AssetHubRococoSender::get().into()); let destination = AssetHubRococo::parent_location(); let beneficiary_id = RococoReceiver::get(); - let beneficiary: MultiLocation = + let beneficiary: Location = AccountId32Junction { network: None, id: beneficiary_id.into() }.into(); let amount_to_send: Balance = ASSET_HUB_ROCOCO_ED * 1000; - let assets: MultiAssets = (Parent, amount_to_send).into(); + let assets: Assets = (Parent, amount_to_send).into(); let fee_asset_item = 0; // this should fail @@ -429,9 +429,9 @@ fn reserve_transfer_assets_from_system_para_to_para() { let beneficiary_id = PenpalAReceiver::get(); let fee_amount_to_send = ASSET_HUB_ROCOCO_ED * 1000; let asset_amount_to_send = ASSET_MIN_BALANCE * 1000; - let assets: MultiAssets = vec![ + let assets: Assets = vec![ (Parent, fee_amount_to_send).into(), - (X2(PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())), asset_amount_to_send) + ([PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())], asset_amount_to_send) .into(), ] .into(); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/send.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/send.rs index 7be0463d2ec4..3c9e76a34e36 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/send.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/send.rs @@ -58,7 +58,7 @@ fn send_xcm_from_para_to_system_para_paying_fee_with_assets_works() { let origin_kind = OriginKind::SovereignAccount; let fee_amount = ASSET_MIN_BALANCE * 1000000; let native_asset = - (X2(PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())), fee_amount).into(); + ([PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())], fee_amount).into(); let root_origin = ::RuntimeOrigin::root(); let system_para_destination = PenpalA::sibling_location_of(AssetHubRococo::para_id()).into(); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/set_xcm_versions.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/set_xcm_versions.rs index 8faba50fc888..c8acb7e61b49 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/set_xcm_versions.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/set_xcm_versions.rs @@ -19,14 +19,14 @@ use crate::*; fn relay_sets_system_para_xcm_supported_version() { // Init tests variables let sudo_origin = ::RuntimeOrigin::root(); - let system_para_destination: MultiLocation = + let system_para_destination: Location = Rococo::child_location_of(AssetHubRococo::para_id()); // Relay Chain sets supported version for Asset Parachain Rococo::execute_with(|| { assert_ok!(::XcmPallet::force_xcm_version( sudo_origin, - bx!(system_para_destination), + bx!(system_para_destination.clone()), XCM_V3 )); @@ -52,7 +52,7 @@ fn system_para_sets_relay_xcm_supported_version() { ::RuntimeCall::PolkadotXcm(pallet_xcm::Call::< ::Runtime, >::force_xcm_version { - location: bx!(parent_location), + location: bx!(parent_location.clone()), version: XCM_V3, }) .encode() diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/swap.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/swap.rs index e08af50c14ee..324b914052cf 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/swap.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/swap.rs @@ -21,10 +21,7 @@ use sp_runtime::{DispatchError, ModuleError}; #[test] fn swap_locally_on_chain_using_local_assets() { let asset_native = Box::new(asset_hub_rococo_runtime::xcm_config::TokenLocation::get()); - let asset_one = Box::new(MultiLocation { - parents: 0, - interior: X2(PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())), - }); + let asset_one = Box::new(Location::new(0, [PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())])); AssetHubRococo::execute_with(|| { type RuntimeEvent = ::RuntimeEvent; @@ -122,21 +119,17 @@ fn swap_locally_on_chain_using_foreign_assets() { let asset_native = Box::new(asset_hub_rococo_runtime::xcm_config::TokenLocation::get()); - let foreign_asset1_at_asset_hub_rococo = Box::new(MultiLocation { - parents: 1, - interior: X3( - Parachain(PenpalA::para_id().into()), - PalletInstance(ASSETS_PALLET_ID), - GeneralIndex(ASSET_ID.into()), - ), - }); + let foreign_asset1_at_asset_hub_rococo = Box::new(Location::new(1, [ + Parachain(PenpalA::para_id().into()), + PalletInstance(ASSETS_PALLET_ID), + GeneralIndex(ASSET_ID.into()), + ])); - let assets_para_destination: VersionedMultiLocation = - MultiLocation { parents: 1, interior: X1(Parachain(AssetHubRococo::para_id().into())) } - .into(); + let assets_para_destination: VersionedLocation = + Location::new(1, [Parachain(AssetHubRococo::para_id().into())]).into(); let penpal_location = - MultiLocation { parents: 1, interior: X1(Parachain(PenpalA::para_id().into())) }; + Location::new(1, [Parachain(PenpalA::para_id().into())]); // 1. Create asset on penpal: PenpalA::execute_with(|| { @@ -162,20 +155,17 @@ fn swap_locally_on_chain_using_foreign_assets() { (sov_penpal_on_asset_hub_rococo.clone().into(), 1000_000_000_000_000_000 * ROCOCO_ED), ]); - let sov_penpal_on_asset_hub_rococo_as_location: MultiLocation = MultiLocation { - parents: 0, - interior: X1(AccountId32Junction { - network: None, - id: sov_penpal_on_asset_hub_rococo.clone().into(), - }), - }; + let sov_penpal_on_asset_hub_rococo_as_location: Location = Location::new(0, [AccountId32Junction { + network: None, + id: sov_penpal_on_asset_hub_rococo.clone().into(), + }]); let call_foreign_assets_create = ::RuntimeCall::ForeignAssets(pallet_assets::Call::< ::Runtime, Instance2, >::create { - id: *foreign_asset1_at_asset_hub_rococo, + id: *foreign_asset1_at_asset_hub_rococo.clone(), min_balance: 1000, admin: sov_penpal_on_asset_hub_rococo.clone().into(), }) @@ -185,8 +175,8 @@ fn swap_locally_on_chain_using_foreign_assets() { let buy_execution_fee_amount = parachains_common::rococo::fee::WeightToFee::weight_to_fee( &Weight::from_parts(10_100_000_000_000, 300_000), ); - let buy_execution_fee = MultiAsset { - id: Concrete(MultiLocation { parents: 1, interior: Here }), + let buy_execution_fee = Asset { + id: AssetId(Location::new(1, Here)), fun: Fungible(buy_execution_fee_amount), }; @@ -223,7 +213,7 @@ fn swap_locally_on_chain_using_foreign_assets() { // Receive XCM message in Assets Parachain AssetHubRococo::execute_with(|| { assert!(::ForeignAssets::asset_exists( - *foreign_asset1_at_asset_hub_rococo + *foreign_asset1_at_asset_hub_rococo.clone() )); // 3: Mint foreign asset on asset_hub_rococo: @@ -237,7 +227,7 @@ fn swap_locally_on_chain_using_foreign_assets() { ::RuntimeOrigin::signed( sov_penpal_on_asset_hub_rococo.clone().into() ), - *foreign_asset1_at_asset_hub_rococo, + *foreign_asset1_at_asset_hub_rococo.clone(), sov_penpal_on_asset_hub_rococo.clone().into(), 3_000_000_000_000, )); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/teleport.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/teleport.rs index f8017f7a1c54..65881700620c 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/teleport.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/teleport.rs @@ -401,7 +401,7 @@ fn teleport_native_assets_from_system_para_to_relay_fails() { #[test] fn teleport_to_other_system_parachains_works() { let amount = ASSET_HUB_ROCOCO_ED * 100; - let native_asset: MultiAssets = (Parent, amount).into(); + let native_asset: Assets = (Parent, amount).into(); test_parachain_is_trusted_teleporter!( AssetHubRococo, // Origin diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs index 83a867e6ae31..e887a30ae4ad 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs @@ -84,10 +84,10 @@ pub fn relay_test_args(amount: Balance) -> TestArgs { /// Returns a `TestArgs` instance to be used for the System Parachain across integration tests pub fn system_para_test_args( - dest: MultiLocation, + dest: Location, beneficiary_id: AccountId32, amount: Balance, - assets: MultiAssets, + assets: Assets, asset_id: Option, ) -> TestArgs { TestArgs { diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/reserve_transfer.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/reserve_transfer.rs index 5b2c648b7b08..becfd8b0ae66 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/reserve_transfer.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/reserve_transfer.rs @@ -33,7 +33,7 @@ fn system_para_to_para_sender_assertions(t: SystemParaToParaTest) { ) => { from: *from == t.sender.account_id, to: *to == AssetHubWestend::sovereign_account_id_of( - t.args.dest + t.args.dest.clone() ), amount: *amount == t.args.amount, }, @@ -72,7 +72,7 @@ fn system_para_to_para_assets_assertions(t: SystemParaToParaTest) { asset_id: *asset_id == ASSET_ID, from: *from == t.sender.account_id, to: *to == AssetHubWestend::sovereign_account_id_of( - t.args.dest + t.args.dest.clone() ), amount: *amount == t.args.amount, }, @@ -96,10 +96,10 @@ fn system_para_to_para_limited_reserve_transfer_assets(t: SystemParaToParaTest) fn reserve_transfer_native_asset_from_relay_to_system_para_fails() { let signed_origin = ::RuntimeOrigin::signed(WestendSender::get().into()); let destination = Westend::child_location_of(AssetHubWestend::para_id()); - let beneficiary: MultiLocation = + let beneficiary: Location = AccountId32Junction { network: None, id: AssetHubWestendReceiver::get().into() }.into(); let amount_to_send: Balance = WESTEND_ED * 1000; - let assets: MultiAssets = (Here, amount_to_send).into(); + let assets: Assets = (Here, amount_to_send).into(); let fee_asset_item = 0; // this should fail @@ -131,10 +131,10 @@ fn reserve_transfer_native_asset_from_system_para_to_relay_fails() { ::RuntimeOrigin::signed(AssetHubWestendSender::get().into()); let destination = AssetHubWestend::parent_location(); let beneficiary_id = WestendReceiver::get(); - let beneficiary: MultiLocation = + let beneficiary: Location = AccountId32Junction { network: None, id: beneficiary_id.into() }.into(); let amount_to_send: Balance = ASSET_HUB_WESTEND_ED * 1000; - let assets: MultiAssets = (Parent, amount_to_send).into(); + let assets: Assets = (Parent, amount_to_send).into(); let fee_asset_item = 0; // this should fail @@ -220,9 +220,7 @@ fn reserve_transfer_asset_from_system_para_to_para() { let destination = AssetHubWestend::sibling_location_of(PenpalA::para_id()); let beneficiary_id = PenpalAReceiver::get(); let amount_to_send = ASSET_MIN_BALANCE * 1000; - let assets = - (X2(PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())), amount_to_send) - .into(); + let assets = ([PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())], amount_to_send).into(); let system_para_test_args = TestContext { sender: AssetHubWestendSender::get(), diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/send.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/send.rs index bda9a3e69c4f..3f67ef6bdfeb 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/send.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/send.rs @@ -57,8 +57,7 @@ fn send_xcm_from_para_to_system_para_paying_fee_with_assets_works() { let origin_kind = OriginKind::SovereignAccount; let fee_amount = ASSET_MIN_BALANCE * 1000000; - let native_asset = - (X2(PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())), fee_amount).into(); + let native_asset = ([PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())], fee_amount).into(); let root_origin = ::RuntimeOrigin::root(); let system_para_destination = PenpalA::sibling_location_of(AssetHubWestend::para_id()).into(); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/set_xcm_versions.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/set_xcm_versions.rs index 2133d5e5fb7c..130454551d2c 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/set_xcm_versions.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/set_xcm_versions.rs @@ -19,14 +19,13 @@ use crate::*; fn relay_sets_system_para_xcm_supported_version() { // Init tests variables let sudo_origin = ::RuntimeOrigin::root(); - let system_para_destination: MultiLocation = - Westend::child_location_of(AssetHubWestend::para_id()); + let system_para_destination: Location = Westend::child_location_of(AssetHubWestend::para_id()); // Relay Chain sets supported version for Asset Parachain Westend::execute_with(|| { assert_ok!(::XcmPallet::force_xcm_version( sudo_origin, - bx!(system_para_destination), + bx!(system_para_destination.clone()), XCM_V3 )); @@ -52,7 +51,7 @@ fn system_para_sets_relay_xcm_supported_version() { ::RuntimeCall::PolkadotXcm(pallet_xcm::Call::< ::Runtime, >::force_xcm_version { - location: bx!(parent_location), + location: bx!(parent_location.clone()), version: XCM_V3, }) .encode() diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/swap.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/swap.rs index a8e19f9ef4b1..1b6ff8a0abca 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/swap.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/swap.rs @@ -18,9 +18,9 @@ use crate::*; #[test] fn swap_locally_on_chain_using_local_assets() { let asset_native = Box::new(asset_hub_westend_runtime::xcm_config::WestendLocation::get()); - let asset_one = Box::new(MultiLocation { + let asset_one = Box::new(Location { parents: 0, - interior: X2(PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())), + interior: [PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())].into(), }); AssetHubWestend::execute_with(|| { @@ -111,21 +111,22 @@ fn swap_locally_on_chain_using_foreign_assets() { let asset_native = Box::new(asset_hub_westend_runtime::xcm_config::WestendLocation::get()); - let foreign_asset1_at_asset_hub_westend = Box::new(MultiLocation { + let foreign_asset1_at_asset_hub_westend = Box::new(Location { parents: 1, - interior: X3( + interior: [ Parachain(PenpalA::para_id().into()), PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into()), - ), + ] + .into(), }); - let assets_para_destination: VersionedMultiLocation = - MultiLocation { parents: 1, interior: X1(Parachain(AssetHubWestend::para_id().into())) } + let assets_para_destination: VersionedLocation = + Location { parents: 1, interior: [Parachain(AssetHubWestend::para_id().into())].into() } .into(); let penpal_location = - MultiLocation { parents: 1, interior: X1(Parachain(PenpalA::para_id().into())) }; + Location { parents: 1, interior: [Parachain(PenpalA::para_id().into())].into() }; // 1. Create asset on penpal: PenpalA::execute_with(|| { @@ -150,12 +151,13 @@ fn swap_locally_on_chain_using_foreign_assets() { (sov_penpal_on_asset_hub_westend.clone().into(), 1000_000_000_000_000_000 * WESTEND_ED), ]); - let sov_penpal_on_asset_hub_westend_as_location: MultiLocation = MultiLocation { + let sov_penpal_on_asset_hub_westend_as_location: Location = Location { parents: 0, - interior: X1(AccountId32Junction { + interior: [AccountId32Junction { network: None, id: sov_penpal_on_asset_hub_westend.clone().into(), - }), + }] + .into(), }; let call_foreign_assets_create = @@ -163,7 +165,7 @@ fn swap_locally_on_chain_using_foreign_assets() { ::Runtime, Instance2, >::create { - id: *foreign_asset1_at_asset_hub_westend, + id: *foreign_asset1_at_asset_hub_westend.clone(), min_balance: 1000, admin: sov_penpal_on_asset_hub_westend.clone().into(), }) @@ -173,10 +175,8 @@ fn swap_locally_on_chain_using_foreign_assets() { let buy_execution_fee_amount = parachains_common::westend::fee::WeightToFee::weight_to_fee( &Weight::from_parts(10_100_000_000_000, 300_000), ); - let buy_execution_fee = MultiAsset { - id: Concrete(MultiLocation { parents: 1, interior: Here }), - fun: Fungible(buy_execution_fee_amount), - }; + let buy_execution_fee = + Asset { id: AssetId(Location::new(1, Here)), fun: Fungible(buy_execution_fee_amount) }; let xcm = VersionedXcm::from(Xcm(vec![ WithdrawAsset { 0: vec![buy_execution_fee.clone()].into() }, @@ -211,7 +211,7 @@ fn swap_locally_on_chain_using_foreign_assets() { // Receive XCM message in Assets Parachain in the next block. AssetHubWestend::execute_with(|| { assert!(::ForeignAssets::asset_exists( - *foreign_asset1_at_asset_hub_westend + *foreign_asset1_at_asset_hub_westend.clone() )); // 3: Mint foreign asset on asset_hub_westend: @@ -225,7 +225,7 @@ fn swap_locally_on_chain_using_foreign_assets() { ::RuntimeOrigin::signed( sov_penpal_on_asset_hub_westend.clone().into() ), - *foreign_asset1_at_asset_hub_westend, + *foreign_asset1_at_asset_hub_westend.clone(), sov_penpal_on_asset_hub_westend.clone().into(), 3_000_000_000_000, )); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/treasury.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/treasury.rs index 32089f7ecec0..8e82059a32d1 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/treasury.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/treasury.rs @@ -24,19 +24,19 @@ fn create_and_claim_treasury_spend() { const ASSET_ID: u32 = 1984; const SPEND_AMOUNT: u128 = 1_000_000; // treasury location from a sibling parachain. - let treasury_location: MultiLocation = MultiLocation::new(1, PalletInstance(37)); + let treasury_location: Location = Location::new(1, PalletInstance(37)); // treasury account on a sibling parachain. let treasury_account = asset_hub_westend_runtime::xcm_config::LocationToAccountId::convert_location( &treasury_location, ) .unwrap(); - let asset_hub_location = MultiLocation::new(0, Parachain(AssetHubWestend::para_id().into())); + let asset_hub_location = Location::new(0, Parachain(AssetHubWestend::para_id().into())); let root = ::RuntimeOrigin::root(); // asset kind to be spend from the treasury. - let asset_kind = VersionedLocatableAsset::V3 { + let asset_kind = VersionedLocatableAsset::V4 { location: asset_hub_location, - asset_id: AssetId::Concrete((PalletInstance(50), GeneralIndex(ASSET_ID.into())).into()), + asset_id: AssetId([PalletInstance(50), GeneralIndex(ASSET_ID.into())].into()), }; // treasury spend beneficiary. let alice: AccountId = Westend::account_id_of(ALICE); @@ -71,7 +71,7 @@ fn create_and_claim_treasury_spend() { root, Box::new(asset_kind), SPEND_AMOUNT, - Box::new(MultiLocation::new(0, Into::<[u8; 32]>::into(alice.clone())).into()), + Box::new(Location::new(0, Into::<[u8; 32]>::into(alice.clone())).into()), None, )); // claim the spend. diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/example.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/example.rs index 35cfa394174c..0112e9885db4 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/example.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/example.rs @@ -29,8 +29,8 @@ fn example() { let xcm = VersionedXcm::from(Xcm(vec![ UnpaidExecution { weight_limit, check_origin }, ExportMessage { - network: WococoId, - destination: X1(Parachain(AssetHubWococo::para_id().into())), + network: NetworkId::Wococo, + destination: [Parachain(AssetHubWococo::para_id().into())].into(), xcm: remote_xcm, }, ])); diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/teleport.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/teleport.rs index f00288a4d8c7..43f8af9244f5 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/teleport.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/teleport.rs @@ -19,7 +19,7 @@ use bridge_hub_rococo_runtime::xcm_config::XcmConfig; #[test] fn teleport_to_other_system_parachains_works() { let amount = BRIDGE_HUB_ROCOCO_ED * 100; - let native_asset: MultiAssets = (Parent, amount).into(); + let native_asset: Assets = (Parent, amount).into(); test_parachain_is_trusted_teleporter!( BridgeHubRococo, // Origin diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs index f406a73d18d5..b3004f945f94 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs @@ -19,7 +19,7 @@ pub use frame_support::assert_ok; // Polkadot pub use xcm::{ prelude::{AccountId32 as AccountId32Junction, *}, - v3::{Error, NetworkId::Rococo as RococoId}, + v4::{Error, NetworkId::Rococo as RococoId}, }; // Bridges diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/example.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/example.rs index 1fdd9441e483..d78eef4cec7d 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/example.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/example.rs @@ -30,7 +30,7 @@ fn example() { UnpaidExecution { weight_limit, check_origin }, ExportMessage { network: RococoId, - destination: X1(Parachain(AssetHubWestend::para_id().into())), + destination: [Parachain(AssetHubWestend::para_id().into())].into(), xcm: remote_xcm, }, ])); diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/teleport.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/teleport.rs index 32639b8614be..285eefc80312 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/teleport.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/teleport.rs @@ -19,7 +19,7 @@ use bridge_hub_westend_runtime::xcm_config::XcmConfig; #[test] fn teleport_to_other_system_parachains_works() { let amount = BRIDGE_HUB_ROCOCO_ED * 100; - let native_asset: MultiAssets = (Parent, amount).into(); + let native_asset: Assets = (Parent, amount).into(); test_parachain_is_trusted_teleporter!( BridgeHubWestend, // Origin diff --git a/cumulus/parachains/pallets/ping/src/lib.rs b/cumulus/parachains/pallets/ping/src/lib.rs index feda3d0b6f9f..a738c05e0366 100644 --- a/cumulus/parachains/pallets/ping/src/lib.rs +++ b/cumulus/parachains/pallets/ping/src/lib.rs @@ -77,9 +77,9 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - PingSent(ParaId, u32, Vec, XcmHash, MultiAssets), + PingSent(ParaId, u32, Vec, XcmHash, Assets), Pinged(ParaId, u32, Vec), - PongSent(ParaId, u32, Vec, XcmHash, MultiAssets), + PongSent(ParaId, u32, Vec, XcmHash, Assets), Ponged(ParaId, u32, Vec, BlockNumberFor), ErrorSendingPing(SendError, ParaId, u32, Vec), ErrorSendingPong(SendError, ParaId, u32, Vec), diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/Cargo.toml b/cumulus/parachains/runtimes/assets/asset-hub-kusama/Cargo.toml index f71499e0c291..56a599c85518 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-kusama/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/Cargo.toml @@ -84,6 +84,7 @@ assets-common = { path = "../common", default-features = false } [dev-dependencies] asset-test-utils = { path = "../test-utils" } +env_logger = "0.10.1" [build-dependencies] substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/lib.rs index e4ed77884bf3..2e81018eabd8 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/lib.rs @@ -29,9 +29,9 @@ pub mod xcm_config; use assets_common::{ foreign_creators::ForeignCreators, - local_and_foreign_assets::{LocalAndForeignAssets, MultiLocationConverter}, + local_and_foreign_assets::{LocalAndForeignAssets, LocationConverter}, matching::FromSiblingParachain, - AssetIdForTrustBackedAssetsConvert, MultiLocationForAssetId, + AssetIdForTrustBackedAssetsConvert, LocationForAssetId, }; use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; @@ -79,7 +79,7 @@ use parachains_common::{ NORMAL_DISPATCH_RATIO, SLOT_DURATION, }; use sp_runtime::RuntimeDebug; -use xcm::opaque::v3::MultiLocation; +use xcm::latest::prelude::Location; use xcm_config::{ FellowshipLocation, ForeignAssetsConvertedConcreteId, GovernanceLocation, KsmLocation, PoolAssetsConvertedConcreteId, TrustBackedAssetsConvertedConcreteId, @@ -94,7 +94,7 @@ use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; use xcm::latest::BodyId; use crate::xcm_config::{ - ForeignCreatorsSovereignAccountOf, LocalAndForeignAssetsMultiLocationMatcher, + ForeignCreatorsSovereignAccountOf, LocalAndForeignAssetsLocationMatcher, TrustBackedAssetsPalletLocation, }; use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; @@ -334,7 +334,7 @@ impl pallet_asset_conversion::Config for Runtime { type HigherPrecisionBalance = sp_core::U256; type Currency = Balances; type AssetBalance = Balance; - type AssetId = MultiLocation; + type AssetId = Location; type Assets = LocalAndForeignAssets< Assets, AssetIdForTrustBackedAssetsConvert, @@ -350,14 +350,14 @@ impl pallet_asset_conversion::Config for Runtime { type PalletId = AssetConversionPalletId; type AllowMultiAssetPools = AllowMultiAssetPools; type MaxSwapPathLength = ConstU32<4>; - type MultiAssetId = Box; + type MultiAssetId = Box; type MultiAssetIdConverter = - MultiLocationConverter; + LocationConverter; type MintMinLiquidity = ConstU128<100>; type WeightInfo = weights::pallet_asset_conversion::WeightInfo; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = - crate::xcm_config::BenchmarkMultiLocationConverter>; + crate::xcm_config::BenchmarkLocationConverter>; } parameter_types! { @@ -378,8 +378,8 @@ pub type ForeignAssetsInstance = pallet_assets::Instance2; impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; - type AssetId = MultiLocationForAssetId; - type AssetIdParameter = MultiLocationForAssetId; + type AssetId = LocationForAssetId; + type AssetIdParameter = LocationForAssetId; type Currency = Balances; type CreateOrigin = ForeignCreators< (FromSiblingParachain>,), @@ -1067,16 +1067,16 @@ impl_runtime_apis! { Block, Balance, u128, - Box, + Box, > for Runtime { - fn quote_price_exact_tokens_for_tokens(asset1: Box, asset2: Box, amount: u128, include_fee: bool) -> Option { + fn quote_price_exact_tokens_for_tokens(asset1: Box, asset2: Box, amount: u128, include_fee: bool) -> Option { AssetConversion::quote_price_exact_tokens_for_tokens(asset1, asset2, amount, include_fee) } - fn quote_price_tokens_for_exact_tokens(asset1: Box, asset2: Box, amount: u128, include_fee: bool) -> Option { + fn quote_price_tokens_for_exact_tokens(asset1: Box, asset2: Box, amount: u128, include_fee: bool) -> Option { AssetConversion::quote_price_tokens_for_exact_tokens(asset1, asset2, amount, include_fee) } - fn get_reserves(asset1: Box, asset2: Box) -> Option<(Balance, Balance)> { + fn get_reserves(asset1: Box, asset2: Box) -> Option<(Balance, Balance)> { AssetConversion::get_reserves(&asset1, &asset2).ok() } } @@ -1130,7 +1130,7 @@ impl_runtime_apis! { AccountId, > for Runtime { - fn query_account_balances(account: AccountId) -> Result { + fn query_account_balances(account: AccountId) -> Result { use assets_common::fungible_conversion::{convert, convert_balance}; Ok([ // collect pallet_balance @@ -1246,31 +1246,31 @@ impl_runtime_apis! { use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsiscsBenchmark; impl pallet_xcm::benchmarking::Config for Runtime { - fn reachable_dest() -> Option { + fn reachable_dest() -> Option { Some(Parent.into()) } - fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { // Relay/native token can be teleported between AH and Relay. Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Parent.into()) + id: AssetId(Parent.into()) }, Parent.into(), )) } - fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { // AH can reserve transfer native token to some random parachain. let random_para_id = 43211234; ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( random_para_id.into() ); Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Parent.into()) + id: AssetId(Parent.into()) }, ParentThen(Parachain(random_para_id).into()).into(), )) @@ -1282,7 +1282,7 @@ impl_runtime_apis! { use pallet_xcm_benchmarks::asset_instance_from; parameter_types! { - pub ExistentialDepositMultiAsset: Option = Some(( + pub ExistentialDepositAsset: Option = Some(( KsmLocation::get(), ExistentialDeposit::get() ).into()); @@ -1292,34 +1292,34 @@ impl_runtime_apis! { type XcmConfig = xcm_config::XcmConfig; type AccountIdConverter = xcm_config::LocationToAccountId; type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< - xcm_config::XcmConfig, - ExistentialDepositMultiAsset, + xcm_config::XcmConfig, + ExistentialDepositAsset, xcm_config::PriceForParentDelivery, >; - fn valid_destination() -> Result { + fn valid_destination() -> Result { Ok(KsmLocation::get()) } - fn worst_case_holding(depositable_count: u32) -> MultiAssets { + fn worst_case_holding(depositable_count: u32) -> Assets { // A mix of fungible, non-fungible, and concrete assets. let holding_non_fungibles = MaxAssetsIntoHolding::get() / 2 - depositable_count; let holding_fungibles = holding_non_fungibles.saturating_sub(1); let fungibles_amount: u128 = 100; let mut assets = (0..holding_fungibles) .map(|i| { - MultiAsset { - id: Concrete(GeneralIndex(i as u128).into()), + Asset { + id: AssetId(GeneralIndex(i as u128).into()), fun: Fungible(fungibles_amount * i as u128), } }) - .chain(core::iter::once(MultiAsset { id: Concrete(Here.into()), fun: Fungible(u128::MAX) })) - .chain((0..holding_non_fungibles).map(|i| MultiAsset { - id: Concrete(GeneralIndex(i as u128).into()), + .chain(core::iter::once(Asset { id: AssetId(Here.into()), fun: Fungible(u128::MAX) })) + .chain((0..holding_non_fungibles).map(|i| Asset { + id: AssetId(GeneralIndex(i as u128).into()), fun: NonFungible(asset_instance_from(i)), })) .collect::>(); - assets.push(MultiAsset { - id: Concrete(KsmLocation::get()), + assets.push(Asset { + id: AssetId(KsmLocation::get()), fun: Fungible(1_000_000 * UNITS), }); assets.into() @@ -1327,12 +1327,12 @@ impl_runtime_apis! { } parameter_types! { - pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + pub const TrustedTeleporter: Option<(Location, Asset)> = Some(( KsmLocation::get(), - MultiAsset { fun: Fungible(UNITS), id: Concrete(KsmLocation::get()) }, + Asset { fun: Fungible(UNITS), id: AssetId(KsmLocation::get()) }, )); pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None; - pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None; + pub const TrustedReserve: Option<(Location, Asset)> = None; } impl pallet_xcm_benchmarks::fungible::Config for Runtime { @@ -1342,9 +1342,9 @@ impl_runtime_apis! { type TrustedTeleporter = TrustedTeleporter; type TrustedReserve = TrustedReserve; - fn get_multi_asset() -> MultiAsset { - MultiAsset { - id: Concrete(KsmLocation::get()), + fn get_asset() -> Asset { + Asset { + id: AssetId(KsmLocation::get()), fun: Fungible(UNITS), } } @@ -1358,39 +1358,39 @@ impl_runtime_apis! { (0u64, Response::Version(Default::default())) } - fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> { Err(BenchmarkError::Skip) } - fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + fn universal_alias() -> Result<(Location, Junction), BenchmarkError> { Err(BenchmarkError::Skip) } - fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> { + fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> { Ok((KsmLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) } - fn subscribe_origin() -> Result { + fn subscribe_origin() -> Result { Ok(KsmLocation::get()) } - fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { + fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> { let origin = KsmLocation::get(); - let assets: MultiAssets = (Concrete(KsmLocation::get()), 1_000 * UNITS).into(); - let ticket = MultiLocation { parents: 0, interior: Here }; + let assets: Assets = (AssetId(KsmLocation::get()), 1_000 * UNITS).into(); + let ticket = Location { parents: 0, interior: Here }; Ok((origin, ticket, assets)) } - fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { + fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> { Err(BenchmarkError::Skip) } fn export_message_origin_and_destination( - ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { + ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> { Err(BenchmarkError::Skip) } - fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { + fn alias_origin() -> Result<(Location, Location), BenchmarkError> { Err(BenchmarkError::Skip) } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/mod.rs index 405d7c72e557..c491f902ee7e 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/mod.rs @@ -23,14 +23,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; -trait WeighMultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight; +trait WeighAssets { + fn weigh_assets(&self, weight: Weight) -> Weight; } const MAX_ASSETS: u64 = 100; -impl WeighMultiAssets for MultiAssetFilter { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for AssetFilter { + fn weigh_assets(&self, weight: Weight) -> Weight { match self { Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64), Self::Wild(asset) => match asset { @@ -49,40 +49,36 @@ impl WeighMultiAssets for MultiAssetFilter { } } -impl WeighMultiAssets for MultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for Assets { + fn weigh_assets(&self, weight: Weight) -> Weight { weight.saturating_mul(self.inner().iter().count() as u64) } } pub struct AssetHubKusamaXcmWeight(core::marker::PhantomData); impl XcmWeightInfo for AssetHubKusamaXcmWeight { - fn withdraw_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::withdraw_asset()) + fn withdraw_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::withdraw_asset()) } - fn reserve_asset_deposited(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::reserve_asset_deposited()) + fn reserve_asset_deposited(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::reserve_asset_deposited()) } - fn receive_teleported_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::receive_teleported_asset()) + fn receive_teleported_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::receive_teleported_asset()) } fn query_response( _query_id: &u64, _response: &Response, _max_weight: &Weight, - _querier: &Option, + _querier: &Option, ) -> Weight { XcmGeneric::::query_response() } - fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_asset()) + fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::transfer_asset()) } - fn transfer_reserve_asset( - assets: &MultiAssets, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_reserve_asset()) + fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } fn transact( _origin_type: &OriginKind, @@ -110,44 +106,36 @@ impl XcmWeightInfo for AssetHubKusamaXcmWeight { fn clear_origin() -> Weight { XcmGeneric::::clear_origin() } - fn descend_origin(_who: &InteriorMultiLocation) -> Weight { + fn descend_origin(_who: &InteriorLocation) -> Weight { XcmGeneric::::descend_origin() } fn report_error(_query_response_info: &QueryResponseInfo) -> Weight { XcmGeneric::::report_error() } - fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_asset()) + fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::deposit_asset()) } - fn deposit_reserve_asset( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_reserve_asset()) + fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::deposit_reserve_asset()) } - fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight { + fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight { Weight::MAX } fn initiate_reserve_withdraw( - assets: &MultiAssetFilter, - _reserve: &MultiLocation, + assets: &AssetFilter, + _reserve: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) + assets.weigh_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) } - fn initiate_teleport( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_teleport()) + fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } - fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight { + fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } - fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight { + fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } fn refund_surplus() -> Weight { @@ -162,7 +150,7 @@ impl XcmWeightInfo for AssetHubKusamaXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } - fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight { + fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } fn trap(_code: &u64) -> Weight { @@ -174,13 +162,13 @@ impl XcmWeightInfo for AssetHubKusamaXcmWeight { fn unsubscribe_version() -> Weight { XcmGeneric::::unsubscribe_version() } - fn burn_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + fn burn_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::burn_asset()) } - fn expect_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + fn expect_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::expect_asset()) } - fn expect_origin(_origin: &Option) -> Weight { + fn expect_origin(_origin: &Option) -> Weight { XcmGeneric::::expect_origin() } fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { @@ -213,16 +201,16 @@ impl XcmWeightInfo for AssetHubKusamaXcmWeight { fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight { Weight::MAX } - fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn lock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn unlock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn note_unlockable(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn request_unlock(_: &Asset, _: &Location) -> Weight { Weight::MAX } fn set_fees_mode(_: &bool) -> Weight { @@ -234,11 +222,11 @@ impl XcmWeightInfo for AssetHubKusamaXcmWeight { fn clear_topic() -> Weight { XcmGeneric::::clear_topic() } - fn alias_origin(_: &MultiLocation) -> Weight { + fn alias_origin(_: &Location) -> Weight { // XCM Executor does not currently support alias origin operations Weight::MAX } - fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { + fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/xcm_config.rs index 05262e074103..aa3770153bc1 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/xcm_config.rs @@ -20,11 +20,11 @@ use super::{ }; use crate::{ForeignAssets, CENTS}; use assets_common::{ - local_and_foreign_assets::MatchesLocalAndForeignAssetsMultiLocation, + local_and_foreign_assets::MatchesLocalAndForeignAssetsLocation, matching::{FromSiblingParachain, IsForeignConcreteAsset}, }; use frame_support::{ - match_types, parameter_types, + parameter_types, traits::{ConstU32, Contains, Everything, Nothing, PalletInfoAccess}, }; use frame_system::EnsureRoot; @@ -53,24 +53,24 @@ use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; use {cumulus_primitives_core::ParaId, sp_core::Get}; parameter_types! { - pub const KsmLocation: MultiLocation = MultiLocation::parent(); + pub const KsmLocation: Location = Location::parent(); pub const RelayNetwork: Option = Some(NetworkId::Kusama); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = - X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocation: InteriorLocation = + [GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into(); pub UniversalLocationNetworkId: NetworkId = UniversalLocation::get().global_consensus().unwrap(); - pub TrustBackedAssetsPalletLocation: MultiLocation = + pub TrustBackedAssetsPalletLocation: Location = PalletInstance(::index() as u8).into(); - pub ForeignAssetsPalletLocation: MultiLocation = + pub ForeignAssetsPalletLocation: Location = PalletInstance(::index() as u8).into(); - pub PoolAssetsPalletLocation: MultiLocation = + pub PoolAssetsPalletLocation: Location = PalletInstance(::index() as u8).into(); pub CheckingAccount: AccountId = PolkadotXcm::check_account(); - pub const GovernanceLocation: MultiLocation = MultiLocation::parent(); - pub const FellowshipLocation: MultiLocation = MultiLocation::parent(); + pub const GovernanceLocation: Location = Location::parent(); + pub const FellowshipLocation: Location = Location::parent(); } -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( @@ -90,7 +90,7 @@ pub type CurrencyTransactor = CurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -108,7 +108,7 @@ pub type FungiblesTransactor = FungiblesAdapter< Assets, // Use this currency when it is a fungible asset matching the given location or name: TrustBackedAssetsConvertedConcreteId, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -125,8 +125,8 @@ pub type ForeignAssetsConvertedConcreteId = assets_common::ForeignAssetsConverte // Ignore `TrustBackedAssets` explicitly StartsWith, // Ignore assets that start explicitly with our `GlobalConsensus(NetworkId)`, means: - // - foreign assets from our consensus should be: `MultiLocation {parents: 1, - // X*(Parachain(xyz), ..)}` + // - foreign assets from our consensus should be: `Location::new(1, [Parachain(xyz), + // ..])` // - foreign assets outside our consensus with the same `GlobalConsensus(NetworkId)` won't // be accepted here StartsWithExplicitGlobalConsensus, @@ -140,7 +140,7 @@ pub type ForeignFungiblesTransactor = FungiblesAdapter< ForeignAssets, // Use this currency when it is a fungible asset matching the given location or name: ForeignAssetsConvertedConcreteId, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -160,7 +160,7 @@ pub type PoolFungiblesTransactor = FungiblesAdapter< PoolAssets, // Use this currency when it is a fungible asset matching the given location or name: PoolAssetsConvertedConcreteId, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -175,20 +175,20 @@ pub type PoolFungiblesTransactor = FungiblesAdapter< pub type AssetTransactors = (CurrencyTransactor, FungiblesTransactor, ForeignFungiblesTransactor, PoolFungiblesTransactor); -/// Simple `MultiLocation` matcher for Local and Foreign asset `MultiLocation`. -pub struct LocalAndForeignAssetsMultiLocationMatcher; -impl MatchesLocalAndForeignAssetsMultiLocation for LocalAndForeignAssetsMultiLocationMatcher { - fn is_local(location: &MultiLocation) -> bool { - use assets_common::fungible_conversion::MatchesMultiLocation; +/// Simple `Location` matcher for Local and Foreign asset `Location`. +pub struct LocalAndForeignAssetsLocationMatcher; +impl MatchesLocalAndForeignAssetsLocation for LocalAndForeignAssetsLocationMatcher { + fn is_local(location: &Location) -> bool { + use assets_common::fungible_conversion::MatchesLocation; TrustBackedAssetsConvertedConcreteId::contains(location) } - fn is_foreign(location: &MultiLocation) -> bool { - use assets_common::fungible_conversion::MatchesMultiLocation; + fn is_foreign(location: &Location) -> bool { + use assets_common::fungible_conversion::MatchesLocation; ForeignAssetsConvertedConcreteId::contains(location) } } -impl Contains for LocalAndForeignAssetsMultiLocationMatcher { - fn contains(location: &MultiLocation) -> bool { +impl Contains for LocalAndForeignAssetsLocationMatcher { + fn contains(location: &Location) -> bool { Self::is_local(location) || Self::is_foreign(location) } } @@ -223,15 +223,18 @@ parameter_types! { pub XcmAssetFeesReceiver: Option = Authorship::author(); } -match_types! { - pub type ParentOrParentsPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { .. }) } - }; - pub type ParentOrSiblings: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(_) } - }; +pub struct ParentOrParentsPlurality; +impl Contains for ParentOrParentsPlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [Plurality { .. }])) + } +} + +pub struct ParentOrSiblings; +impl Contains for ParentOrSiblings { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [_])) + } } /// A call filter for the XCM Transact instruction. This is a temporary measure until we properly @@ -529,13 +532,13 @@ impl xcm_executor::Config for XcmConfig { type Aliasers = Nothing; } -/// Converts a local signed origin into an XCM multilocation. +/// Converts a local signed origin into an XCM location. /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; parameter_types! { /// The asset ID for the asset that we use to pay for message delivery fees. - pub FeeAssetId: AssetId = Concrete(KsmLocation::get()); + pub FeeAssetId: AssetId = AssetId(KsmLocation::get()); /// The base fee for the message delivery fees. pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); } @@ -600,35 +603,35 @@ pub type ForeignCreatorsSovereignAccountOf = ( /// Simple conversion of `u32` into an `AssetId` for use in benchmarking. pub struct XcmBenchmarkHelper; #[cfg(feature = "runtime-benchmarks")] -impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { - fn create_asset_id_parameter(id: u32) -> MultiLocation { - MultiLocation { parents: 1, interior: X1(Parachain(id)) } +impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { + fn create_asset_id_parameter(id: u32) -> Location { + Location { parents: 1, interior: [Parachain(id)].into() } } } #[cfg(feature = "runtime-benchmarks")] -pub struct BenchmarkMultiLocationConverter { +pub struct BenchmarkLocationConverter { _phantom: sp_std::marker::PhantomData, } #[cfg(feature = "runtime-benchmarks")] -impl - pallet_asset_conversion::BenchmarkHelper> - for BenchmarkMultiLocationConverter +impl pallet_asset_conversion::BenchmarkHelper> + for BenchmarkLocationConverter where SelfParaId: Get, { - fn asset_id(asset_id: u32) -> MultiLocation { - MultiLocation { + fn asset_id(asset_id: u32) -> Location { + Location { parents: 1, - interior: X3( + interior: [ Parachain(SelfParaId::get().into()), PalletInstance(::index() as u8), GeneralIndex(asset_id.into()), - ), + ] + .into(), } } - fn multiasset_id(asset_id: u32) -> sp_std::boxed::Box { + fn multiasset_id(asset_id: u32) -> sp_std::boxed::Box { sp_std::boxed::Box::new(Self::asset_id(asset_id)) } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/tests/tests.rs index cdd4290770fd..c092a84494d3 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-kusama/tests/tests.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/tests/tests.rs @@ -39,7 +39,7 @@ use parachains_common::{ kusama::fee::WeightToFee, AccountId, AssetIdForTrustBackedAssets, AuraId, Balance, }; use sp_runtime::traits::MaybeEquivalence; -use xcm::latest::prelude::*; +use xcm::latest::prelude::{Assets as XcmAssets, *}; use xcm_executor::traits::{Identity, JustTry, WeightTrader}; const ALICE: [u8; 32] = [1u8; 32]; @@ -88,8 +88,8 @@ fn test_asset_xcm_trader() { minimum_asset_balance )); - // get asset id as multilocation - let asset_multilocation = + // get asset id as location + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&local_asset_id).unwrap(); // Set Alice as block author, who will receive fees @@ -108,8 +108,8 @@ fn test_asset_xcm_trader() { // Lets pay with: asset_amount_needed + asset_amount_extra let asset_amount_extra = 100_u128; - let asset: MultiAsset = - (asset_multilocation, asset_amount_needed + asset_amount_extra).into(); + let asset: Asset = + (asset_location.clone(), asset_amount_needed + asset_amount_extra).into(); let mut trader = ::Trader::new(); let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; @@ -118,7 +118,7 @@ fn test_asset_xcm_trader() { let unused_assets = trader.buy_weight(bought, asset.into(), &ctx).expect("Expected Ok"); // Check whether a correct amount of unused assets is returned assert_ok!( - unused_assets.ensure_contains(&(asset_multilocation, asset_amount_extra).into()) + unused_assets.ensure_contains(&(asset_location, asset_amount_extra).into()) ); // Drop trader @@ -176,12 +176,12 @@ fn test_asset_xcm_trader_with_refund() { // We are going to buy 4e9 weight let bought = Weight::from_parts(4_000_000_000u64, 0); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); // lets calculate amount needed let amount_bought = WeightToFee::weight_to_fee(&bought); - let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + let asset: Asset = (asset_location.clone(), amount_bought).into(); // Make sure buy_weight does not return an error assert_ok!(trader.buy_weight(bought, asset.clone().into(), &ctx)); @@ -199,7 +199,7 @@ fn test_asset_xcm_trader_with_refund() { assert_eq!( trader.refund_weight(bought - weight_used, &ctx), - Some((asset_multilocation, amount_refunded).into()) + Some((asset_location, amount_refunded).into()) ); // Drop trader @@ -248,7 +248,7 @@ fn test_asset_xcm_trader_refund_not_possible_since_amount_less_than_ed() { // We are going to buy small amount let bought = Weight::from_parts(500_000_000u64, 0); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); let amount_bought = WeightToFee::weight_to_fee(&bought); @@ -257,7 +257,7 @@ fn test_asset_xcm_trader_refund_not_possible_since_amount_less_than_ed() { "we are testing what happens when the amount does not exceed ED" ); - let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + let asset: Asset = (asset_location, amount_bought).into(); // Buy weight should return an error assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); @@ -300,7 +300,7 @@ fn test_that_buying_ed_refund_does_not_refund() { // We are gonna buy ED let bought = Weight::from_parts(ExistentialDeposit::get().try_into().unwrap(), 0); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); let amount_bought = WeightToFee::weight_to_fee(&bought); @@ -311,11 +311,11 @@ fn test_that_buying_ed_refund_does_not_refund() { // We know we will have to buy at least ED, so lets make sure first it will // fail with a payment of less than ED - let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + let asset: Asset = (asset_location.clone(), amount_bought).into(); assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); // Now lets buy ED at least - let asset: MultiAsset = (asset_multilocation, ExistentialDeposit::get()).into(); + let asset: Asset = (asset_location, ExistentialDeposit::get()).into(); // Buy weight should work assert_ok!(trader.buy_weight(bought, asset.into(), &ctx)); @@ -376,9 +376,9 @@ fn test_asset_xcm_trader_not_possible_for_non_sufficient_assets() { // lets calculate amount needed let asset_amount_needed = WeightToFee::weight_to_fee(&bought); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); - let asset: MultiAsset = (asset_multilocation, asset_amount_needed).into(); + let asset: Asset = (asset_location, asset_amount_needed).into(); // Make sure again buy_weight does return an error assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); @@ -408,19 +408,22 @@ fn test_assets_balances_api_works() { .build() .execute_with(|| { let local_asset_id = 1; - let foreign_asset_id_multilocation = - MultiLocation { parents: 1, interior: X2(Parachain(1234), GeneralIndex(12345)) }; + let foreign_asset_id_location = + Location { parents: 1, interior: [Parachain(1234), GeneralIndex(12345)].into() }; // check before assert_eq!(Assets::balance(local_asset_id, AccountId::from(ALICE)), 0); assert_eq!( - ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)), + ForeignAssets::balance( + foreign_asset_id_location.clone(), + AccountId::from(ALICE) + ), 0 ); assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 0); assert!(Runtime::query_account_balances(AccountId::from(ALICE)) .unwrap() - .try_as::() + .try_as::() .unwrap() .is_none()); @@ -451,7 +454,7 @@ fn test_assets_balances_api_works() { let foreign_asset_minimum_asset_balance = 3333333_u128; assert_ok!(ForeignAssets::force_create( RuntimeHelper::root_origin(), - foreign_asset_id_multilocation, + foreign_asset_id_location.clone(), AccountId::from(SOME_ASSET_ADMIN).into(), false, foreign_asset_minimum_asset_balance @@ -460,7 +463,7 @@ fn test_assets_balances_api_works() { // We first mint enough asset for the account to exist for assets assert_ok!(ForeignAssets::mint( RuntimeHelper::origin_of(AccountId::from(SOME_ASSET_ADMIN)), - foreign_asset_id_multilocation, + foreign_asset_id_location.clone(), AccountId::from(ALICE).into(), 6 * foreign_asset_minimum_asset_balance )); @@ -471,12 +474,15 @@ fn test_assets_balances_api_works() { minimum_asset_balance ); assert_eq!( - ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)), + ForeignAssets::balance( + foreign_asset_id_location.clone(), + AccountId::from(ALICE) + ), 6 * minimum_asset_balance ); assert_eq!(Balances::free_balance(AccountId::from(ALICE)), some_currency); - let result: MultiAssets = Runtime::query_account_balances(AccountId::from(ALICE)) + let result: XcmAssets = Runtime::query_account_balances(AccountId::from(ALICE)) .unwrap() .try_into() .unwrap(); @@ -497,7 +503,7 @@ fn test_assets_balances_api_works() { .into()))); // check foreign asset assert!(result.inner().iter().any(|asset| asset.eq(&( - Identity::convert_back(&foreign_asset_id_multilocation).unwrap(), + Identity::convert_back(&foreign_asset_id_location).unwrap(), 6 * foreign_asset_minimum_asset_balance ) .into()))); @@ -585,11 +591,11 @@ asset_test_utils::include_asset_transactor_transfer_with_pallet_assets_instance_ Runtime, XcmConfig, ForeignAssetsInstance, - MultiLocation, + Location, JustTry, collator_session_keys(), ExistentialDeposit::get(), - MultiLocation { parents: 1, interior: X2(Parachain(1313), GeneralIndex(12345)) }, + Location { parents: 1, interior: [Parachain(1313), GeneralIndex(12345)].into() }, Box::new(|| { assert!(Assets::asset_ids().collect::>().is_empty()); }), @@ -604,7 +610,7 @@ asset_test_utils::include_create_and_manage_foreign_assets_for_local_consensus_p WeightToFee, ForeignCreatorsSovereignAccountOf, ForeignAssetsInstance, - MultiLocation, + Location, JustTry, collator_session_keys(), ExistentialDeposit::get(), diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/lib.rs index 6f853b6f56ed..34946b76671c 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/lib.rs @@ -63,7 +63,7 @@ mod weights; pub mod xcm_config; use assets_common::{ - foreign_creators::ForeignCreators, matching::FromSiblingParachain, MultiLocationForAssetId, + foreign_creators::ForeignCreators, matching::FromSiblingParachain, LocationForAssetId, }; use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; @@ -316,8 +316,8 @@ pub type ForeignAssetsInstance = pallet_assets::Instance2; impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; - type AssetId = MultiLocationForAssetId; - type AssetIdParameter = MultiLocationForAssetId; + type AssetId = LocationForAssetId; + type AssetIdParameter = LocationForAssetId; type Currency = Balances; type CreateOrigin = ForeignCreators< (FromSiblingParachain>,), @@ -1018,7 +1018,7 @@ impl_runtime_apis! { AccountId, > for Runtime { - fn query_account_balances(account: AccountId) -> Result { + fn query_account_balances(account: AccountId) -> Result { use assets_common::fungible_conversion::{convert, convert_balance}; Ok([ // collect pallet_balance @@ -1127,31 +1127,31 @@ impl_runtime_apis! { use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsiscsBenchmark; impl pallet_xcm::benchmarking::Config for Runtime { - fn reachable_dest() -> Option { + fn reachable_dest() -> Option { Some(Parent.into()) } - fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { // Relay/native token can be teleported between AH and Relay. Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Parent.into()) + id: AssetId(Parent.into()) }, Parent.into(), )) } - fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { // AH can reserve transfer native token to some random parachain. let random_para_id = 43211234; ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( random_para_id.into() ); Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Parent.into()) + id: AssetId(Parent.into()) }, ParentThen(Parachain(random_para_id).into()).into(), )) @@ -1163,7 +1163,7 @@ impl_runtime_apis! { use pallet_xcm_benchmarks::asset_instance_from; parameter_types! { - pub ExistentialDepositMultiAsset: Option = Some(( + pub ExistentialDepositAsset: Option = Some(( xcm_config::DotLocation::get(), ExistentialDeposit::get() ).into()); @@ -1174,33 +1174,33 @@ impl_runtime_apis! { type AccountIdConverter = xcm_config::LocationToAccountId; type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< xcm_config::XcmConfig, - ExistentialDepositMultiAsset, + ExistentialDepositAsset, xcm_config::PriceForParentDelivery, >; - fn valid_destination() -> Result { + fn valid_destination() -> Result { Ok(DotLocation::get()) } - fn worst_case_holding(depositable_count: u32) -> MultiAssets { + fn worst_case_holding(depositable_count: u32) -> Assets { // A mix of fungible, non-fungible, and concrete assets. let holding_non_fungibles = MaxAssetsIntoHolding::get() / 2 - depositable_count; let holding_fungibles = holding_non_fungibles - 1; let fungibles_amount: u128 = 100; let mut assets = (0..holding_fungibles) .map(|i| { - MultiAsset { - id: Concrete(GeneralIndex(i as u128).into()), + Asset { + id: AssetId(GeneralIndex(i as u128).into()), fun: Fungible(fungibles_amount * i as u128), } }) - .chain(core::iter::once(MultiAsset { id: Concrete(Here.into()), fun: Fungible(u128::MAX) })) - .chain((0..holding_non_fungibles).map(|i| MultiAsset { - id: Concrete(GeneralIndex(i as u128).into()), + .chain(core::iter::once(Asset { id: AssetId(Here.into()), fun: Fungible(u128::MAX) })) + .chain((0..holding_non_fungibles).map(|i| Asset { + id: AssetId(GeneralIndex(i as u128).into()), fun: NonFungible(asset_instance_from(i)), })) .collect::>(); - assets.push(MultiAsset { - id: Concrete(DotLocation::get()), + assets.push(Asset { + id: AssetId(DotLocation::get()), fun: Fungible(1_000_000 * UNITS), }); assets.into() @@ -1208,12 +1208,12 @@ impl_runtime_apis! { } parameter_types! { - pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + pub const TrustedTeleporter: Option<(Location, Asset)> = Some(( DotLocation::get(), - MultiAsset { fun: Fungible(UNITS), id: Concrete(DotLocation::get()) }, + Asset { fun: Fungible(UNITS), id: AssetId(DotLocation::get()) }, )); pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None; - pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None; + pub const TrustedReserve: Option<(Location, Asset)> = None; } impl pallet_xcm_benchmarks::fungible::Config for Runtime { @@ -1223,9 +1223,9 @@ impl_runtime_apis! { type TrustedTeleporter = TrustedTeleporter; type TrustedReserve = TrustedReserve; - fn get_multi_asset() -> MultiAsset { - MultiAsset { - id: Concrete(DotLocation::get()), + fn get_asset() -> Asset { + Asset { + id: AssetId(DotLocation::get()), fun: Fungible(UNITS), } } @@ -1239,39 +1239,39 @@ impl_runtime_apis! { (0u64, Response::Version(Default::default())) } - fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> { Err(BenchmarkError::Skip) } - fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + fn universal_alias() -> Result<(Location, Junction), BenchmarkError> { Err(BenchmarkError::Skip) } - fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> { + fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> { Ok((DotLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) } - fn subscribe_origin() -> Result { + fn subscribe_origin() -> Result { Ok(DotLocation::get()) } - fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { + fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> { let origin = DotLocation::get(); - let assets: MultiAssets = (Concrete(DotLocation::get()), 1_000 * UNITS).into(); - let ticket = MultiLocation { parents: 0, interior: Here }; + let assets: Assets = (AssetId(DotLocation::get()), 1_000 * UNITS).into(); + let ticket = Location { parents: 0, interior: Here }; Ok((origin, ticket, assets)) } - fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { + fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> { Err(BenchmarkError::Skip) } fn export_message_origin_and_destination( - ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { + ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> { Err(BenchmarkError::Skip) } - fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { + fn alias_origin() -> Result<(Location, Location), BenchmarkError> { Err(BenchmarkError::Skip) } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/mod.rs index 44fcb91d6880..9b5d2a9d9fad 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/mod.rs @@ -23,14 +23,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; -trait WeighMultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight; +trait WeighAssets { + fn weigh_assets(&self, weight: Weight) -> Weight; } const MAX_ASSETS: u64 = 100; -impl WeighMultiAssets for MultiAssetFilter { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for AssetFilter { + fn weigh_assets(&self, weight: Weight) -> Weight { match self { Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64), Self::Wild(asset) => match asset { @@ -49,40 +49,36 @@ impl WeighMultiAssets for MultiAssetFilter { } } -impl WeighMultiAssets for MultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for Assets { + fn weigh_assets(&self, weight: Weight) -> Weight { weight.saturating_mul(self.inner().iter().count() as u64) } } pub struct AssetHubPolkadotXcmWeight(core::marker::PhantomData); impl XcmWeightInfo for AssetHubPolkadotXcmWeight { - fn withdraw_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::withdraw_asset()) + fn withdraw_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::withdraw_asset()) } - fn reserve_asset_deposited(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::reserve_asset_deposited()) + fn reserve_asset_deposited(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::reserve_asset_deposited()) } - fn receive_teleported_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::receive_teleported_asset()) + fn receive_teleported_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::receive_teleported_asset()) } fn query_response( _query_id: &u64, _response: &Response, _max_weight: &Weight, - _querier: &Option, + _querier: &Option, ) -> Weight { XcmGeneric::::query_response() } - fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_asset()) + fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::transfer_asset()) } - fn transfer_reserve_asset( - assets: &MultiAssets, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_reserve_asset()) + fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } fn transact( _origin_type: &OriginKind, @@ -110,44 +106,36 @@ impl XcmWeightInfo for AssetHubPolkadotXcmWeight { fn clear_origin() -> Weight { XcmGeneric::::clear_origin() } - fn descend_origin(_who: &InteriorMultiLocation) -> Weight { + fn descend_origin(_who: &InteriorLocation) -> Weight { XcmGeneric::::descend_origin() } fn report_error(_query_response_info: &QueryResponseInfo) -> Weight { XcmGeneric::::report_error() } - fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_asset()) + fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::deposit_asset()) } - fn deposit_reserve_asset( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_reserve_asset()) + fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::deposit_reserve_asset()) } - fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight { + fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight { Weight::MAX } fn initiate_reserve_withdraw( - assets: &MultiAssetFilter, - _reserve: &MultiLocation, + assets: &AssetFilter, + _reserve: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) + assets.weigh_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) } - fn initiate_teleport( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_teleport()) + fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } - fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight { + fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } - fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight { + fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } fn refund_surplus() -> Weight { @@ -162,7 +150,7 @@ impl XcmWeightInfo for AssetHubPolkadotXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } - fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight { + fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } fn trap(_code: &u64) -> Weight { @@ -174,13 +162,13 @@ impl XcmWeightInfo for AssetHubPolkadotXcmWeight { fn unsubscribe_version() -> Weight { XcmGeneric::::unsubscribe_version() } - fn burn_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + fn burn_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::burn_asset()) } - fn expect_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + fn expect_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::expect_asset()) } - fn expect_origin(_origin: &Option) -> Weight { + fn expect_origin(_origin: &Option) -> Weight { XcmGeneric::::expect_origin() } fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { @@ -213,16 +201,16 @@ impl XcmWeightInfo for AssetHubPolkadotXcmWeight { fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight { Weight::MAX } - fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn lock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn unlock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn note_unlockable(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn request_unlock(_: &Asset, _: &Location) -> Weight { Weight::MAX } fn set_fees_mode(_: &bool) -> Weight { @@ -234,11 +222,11 @@ impl XcmWeightInfo for AssetHubPolkadotXcmWeight { fn clear_topic() -> Weight { XcmGeneric::::clear_topic() } - fn alias_origin(_: &MultiLocation) -> Weight { + fn alias_origin(_: &Location) -> Weight { // XCM Executor does not currently support alias origin operations Weight::MAX } - fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { + fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/xcm_config.rs index b3c2ce4da76f..ccd04a0641e6 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/xcm_config.rs @@ -20,7 +20,7 @@ use super::{ }; use assets_common::matching::{FromSiblingParachain, IsForeignConcreteAsset}; use frame_support::{ - match_types, parameter_types, + parameter_types, traits::{ConstU32, Contains, Everything, Nothing, PalletInfoAccess}, }; use frame_system::EnsureRoot; @@ -46,20 +46,20 @@ use xcm_builder::{ use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; parameter_types! { - pub const DotLocation: MultiLocation = MultiLocation::parent(); + pub const DotLocation: Location = Location::parent(); pub const RelayNetwork: Option = Some(NetworkId::Polkadot); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = - X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocation: InteriorLocation = + [GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into(); pub UniversalLocationNetworkId: NetworkId = UniversalLocation::get().global_consensus().unwrap(); - pub TrustBackedAssetsPalletLocation: MultiLocation = + pub TrustBackedAssetsPalletLocation: Location = PalletInstance(::index() as u8).into(); pub CheckingAccount: AccountId = PolkadotXcm::check_account(); - pub FellowshipLocation: MultiLocation = MultiLocation::new(1, Parachain(1001)); - pub const GovernanceLocation: MultiLocation = MultiLocation::parent(); + pub FellowshipLocation: Location = Location::new(1, Parachain(1001)); + pub const GovernanceLocation: Location = Location::parent(); } -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( @@ -80,7 +80,7 @@ pub type CurrencyTransactor = CurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -98,7 +98,7 @@ pub type FungiblesTransactor = FungiblesAdapter< Assets, // Use this currency when it is a fungible asset matching the given location or name: TrustBackedAssetsConvertedConcreteId, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -115,8 +115,8 @@ pub type ForeignAssetsConvertedConcreteId = assets_common::ForeignAssetsConverte // Ignore `TrustBackedAssets` explicitly StartsWith, // Ignore assets that start explicitly with our `GlobalConsensus(NetworkId)`, means: - // - foreign assets from our consensus should be: `MultiLocation {parents: 1, - // X*(Parachain(xyz), ..)}` + // - foreign assets from our consensus should be: `Location {parents: 1, X*(Parachain(xyz), + // ..)}` // - foreign assets outside our consensus with the same `GlobalConsensus(NetworkId)` won't // be accepted here StartsWithExplicitGlobalConsensus, @@ -130,7 +130,7 @@ pub type ForeignFungiblesTransactor = FungiblesAdapter< ForeignAssets, // Use this currency when it is a fungible asset matching the given location or name: ForeignAssetsConvertedConcreteId, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -173,24 +173,39 @@ parameter_types! { pub XcmAssetFeesReceiver: Option = Authorship::author(); } -match_types! { - pub type ParentOrParentsPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { .. }) } - }; - pub type ParentOrSiblings: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(_) } - }; - pub type FellowsPlurality: impl Contains = { - MultiLocation { parents: 1, interior: X2(Parachain(1001), Plurality { id: BodyId::Technical, ..}) } - }; - pub type FellowshipSalaryPallet: impl Contains = { - MultiLocation { parents: 1, interior: X2(Parachain(1001), PalletInstance(64)) } - }; - pub type AmbassadorSalaryPallet: impl Contains = { - MultiLocation { parents: 1, interior: X2(Parachain(1001), PalletInstance(74)) } - }; +pub struct ParentOrParentsPlurality; +impl Contains for ParentOrParentsPlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [Plurality { .. }])) + } +} + +pub struct ParentOrSiblings; +impl Contains for ParentOrSiblings { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [_])) + } +} + +pub struct FellowsPlurality; +impl Contains for FellowsPlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, [Parachain(1001), Plurality { id: BodyId::Technical, .. }])) + } +} + +pub struct FellowshipSalaryPallet; +impl Contains for FellowshipSalaryPallet { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, [Parachain(1001), PalletInstance(64)])) + } +} + +pub struct AmbassadorSalaryPallet; +impl Contains for AmbassadorSalaryPallet { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, [Parachain(1001), PalletInstance(74)])) + } } /// A call filter for the XCM Transact instruction. This is a temporary measure until we properly @@ -453,13 +468,13 @@ impl xcm_executor::Config for XcmConfig { type Aliasers = Nothing; } -/// Converts a local signed origin into an XCM multilocation. +/// Converts a local signed origin into an XCM location. /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; parameter_types! { /// The asset ID for the asset that we use to pay for message delivery fees. - pub FeeAssetId: AssetId = Concrete(DotLocation::get()); + pub FeeAssetId: AssetId = AssetId(DotLocation::get()); /// The base fee for the message delivery fees. pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); } @@ -524,9 +539,9 @@ pub type ForeignCreatorsSovereignAccountOf = ( /// Simple conversion of `u32` into an `AssetId` for use in benchmarking. pub struct XcmBenchmarkHelper; #[cfg(feature = "runtime-benchmarks")] -impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { - fn create_asset_id_parameter(id: u32) -> MultiLocation { - MultiLocation { parents: 1, interior: X1(Parachain(id)) } +impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { + fn create_asset_id_parameter(id: u32) -> Location { + Location { parents: 1, interior: [Parachain(id)].into() } } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/tests/tests.rs index b7e44646ece7..ec0456b10c49 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/tests/tests.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/tests/tests.rs @@ -40,7 +40,7 @@ use parachains_common::{ AssetIdForTrustBackedAssets, Balance, }; use sp_runtime::traits::MaybeEquivalence; -use xcm::latest::prelude::*; +use xcm::latest::prelude::{Assets as XcmAssets, *}; use xcm_executor::traits::{Identity, JustTry, WeightTrader}; const ALICE: [u8; 32] = [1u8; 32]; @@ -89,8 +89,8 @@ fn test_asset_xcm_trader() { minimum_asset_balance )); - // get asset id as multilocation - let asset_multilocation = + // get asset id as location + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&local_asset_id).unwrap(); // Set Alice as block author, who will receive fees @@ -112,8 +112,8 @@ fn test_asset_xcm_trader() { // Lets pay with: asset_amount_needed + asset_amount_extra let asset_amount_extra = 100_u128; - let asset: MultiAsset = - (asset_multilocation, asset_amount_needed + asset_amount_extra).into(); + let asset: Asset = + (asset_location.clone(), asset_amount_needed + asset_amount_extra).into(); let mut trader = ::Trader::new(); let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; @@ -122,7 +122,7 @@ fn test_asset_xcm_trader() { let unused_assets = trader.buy_weight(bought, asset.into(), &ctx).expect("Expected Ok"); // Check whether a correct amount of unused assets is returned assert_ok!( - unused_assets.ensure_contains(&(asset_multilocation, asset_amount_extra).into()) + unused_assets.ensure_contains(&(asset_location, asset_amount_extra).into()) ); // Drop trader @@ -183,12 +183,12 @@ fn test_asset_xcm_trader_with_refund() { // bit more of weight let bought = Weight::from_parts(400_000_000_000u64, 0); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); // lets calculate amount needed let amount_bought = WeightToFee::weight_to_fee(&bought); - let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + let asset: Asset = (asset_location.clone(), amount_bought).into(); // Make sure buy_weight does not return an error assert_ok!(trader.buy_weight(bought, asset.clone().into(), &ctx)); @@ -206,7 +206,7 @@ fn test_asset_xcm_trader_with_refund() { assert_eq!( trader.refund_weight(bought - weight_used, &ctx), - Some((asset_multilocation, amount_refunded).into()) + Some((asset_location, amount_refunded).into()) ); // Drop trader @@ -258,7 +258,7 @@ fn test_asset_xcm_trader_refund_not_possible_since_amount_less_than_ed() { // bit more of weight let bought = Weight::from_parts(50_000_000_000u64, 0); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); let amount_bought = WeightToFee::weight_to_fee(&bought); @@ -267,7 +267,7 @@ fn test_asset_xcm_trader_refund_not_possible_since_amount_less_than_ed() { "we are testing what happens when the amount does not exceed ED" ); - let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + let asset: Asset = (asset_location, amount_bought).into(); // Buy weight should return an error assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); @@ -310,7 +310,7 @@ fn test_that_buying_ed_refund_does_not_refund() { // We are gonna buy ED let bought = Weight::from_parts(ExistentialDeposit::get().try_into().unwrap(), 0); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); let amount_bought = WeightToFee::weight_to_fee(&bought); @@ -321,11 +321,11 @@ fn test_that_buying_ed_refund_does_not_refund() { // We know we will have to buy at least ED, so lets make sure first it will // fail with a payment of less than ED - let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + let asset: Asset = (asset_location.clone(), amount_bought).into(); assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); // Now lets buy ED at least - let asset: MultiAsset = (asset_multilocation, ExistentialDeposit::get()).into(); + let asset: Asset = (asset_location, ExistentialDeposit::get()).into(); // Buy weight should work assert_ok!(trader.buy_weight(bought, asset.into(), &ctx)); @@ -389,9 +389,9 @@ fn test_asset_xcm_trader_not_possible_for_non_sufficient_assets() { // lets calculate amount needed let asset_amount_needed = WeightToFee::weight_to_fee(&bought); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); - let asset: MultiAsset = (asset_multilocation, asset_amount_needed).into(); + let asset: Asset = (asset_location, asset_amount_needed).into(); // Make sure again buy_weight does return an error assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); @@ -421,19 +421,22 @@ fn test_assets_balances_api_works() { .build() .execute_with(|| { let local_asset_id = 1; - let foreign_asset_id_multilocation = - MultiLocation { parents: 1, interior: X2(Parachain(1234), GeneralIndex(12345)) }; + let foreign_asset_id_location = + Location { parents: 1, interior: [Parachain(1234), GeneralIndex(12345)].into() }; // check before assert_eq!(Assets::balance(local_asset_id, AccountId::from(ALICE)), 0); assert_eq!( - ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)), + ForeignAssets::balance( + foreign_asset_id_location.clone(), + AccountId::from(ALICE) + ), 0 ); assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 0); assert!(Runtime::query_account_balances(AccountId::from(ALICE)) .unwrap() - .try_as::() + .try_as::() .unwrap() .is_none()); @@ -464,7 +467,7 @@ fn test_assets_balances_api_works() { let foreign_asset_minimum_asset_balance = 3333333_u128; assert_ok!(ForeignAssets::force_create( RuntimeHelper::root_origin(), - foreign_asset_id_multilocation, + foreign_asset_id_location.clone(), AccountId::from(SOME_ASSET_ADMIN).into(), false, foreign_asset_minimum_asset_balance @@ -473,7 +476,7 @@ fn test_assets_balances_api_works() { // We first mint enough asset for the account to exist for assets assert_ok!(ForeignAssets::mint( RuntimeHelper::origin_of(AccountId::from(SOME_ASSET_ADMIN)), - foreign_asset_id_multilocation, + foreign_asset_id_location.clone(), AccountId::from(ALICE).into(), 6 * foreign_asset_minimum_asset_balance )); @@ -484,12 +487,15 @@ fn test_assets_balances_api_works() { minimum_asset_balance ); assert_eq!( - ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)), + ForeignAssets::balance( + foreign_asset_id_location.clone(), + AccountId::from(ALICE) + ), 6 * minimum_asset_balance ); assert_eq!(Balances::free_balance(AccountId::from(ALICE)), some_currency); - let result: MultiAssets = Runtime::query_account_balances(AccountId::from(ALICE)) + let result: XcmAssets = Runtime::query_account_balances(AccountId::from(ALICE)) .unwrap() .try_into() .unwrap(); @@ -510,7 +516,7 @@ fn test_assets_balances_api_works() { .into()))); // check foreign asset assert!(result.inner().iter().any(|asset| asset.eq(&( - Identity::convert_back(&foreign_asset_id_multilocation).unwrap(), + Identity::convert_back(&foreign_asset_id_location).unwrap(), 6 * foreign_asset_minimum_asset_balance ) .into()))); @@ -602,7 +608,7 @@ asset_test_utils::include_asset_transactor_transfer_with_pallet_assets_instance_ Runtime, XcmConfig, ForeignAssetsInstance, - MultiLocation, + Location, JustTry, asset_test_utils::CollatorSessionKeys::new( AccountId::from(ALICE), @@ -610,7 +616,7 @@ asset_test_utils::include_asset_transactor_transfer_with_pallet_assets_instance_ SessionKeys { aura: AuraId::from(sp_core::ed25519::Public::from_raw(ALICE)) } ), ExistentialDeposit::get(), - MultiLocation { parents: 1, interior: X2(Parachain(1313), GeneralIndex(12345)) }, + Location { parents: 1, interior: [Parachain(1313), GeneralIndex(12345)].into() }, Box::new(|| { assert!(Assets::asset_ids().collect::>().is_empty()); }), @@ -625,7 +631,7 @@ asset_test_utils::include_create_and_manage_foreign_assets_for_local_consensus_p WeightToFee, ForeignCreatorsSovereignAccountOf, ForeignAssetsInstance, - MultiLocation, + Location, JustTry, asset_test_utils::CollatorSessionKeys::new( AccountId::from(ALICE), diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs index 06dcfb99a657..886f9430ef72 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs @@ -35,9 +35,9 @@ pub mod xcm_config; use assets_common::{ foreign_creators::ForeignCreators, - local_and_foreign_assets::{LocalAndForeignAssets, MultiLocationConverter}, + local_and_foreign_assets::{LocalAndForeignAssets, LocationConverter}, matching::FromSiblingParachain, - AssetIdForTrustBackedAssetsConvert, MultiLocationForAssetId, + AssetIdForTrustBackedAssetsConvert, LocationForAssetId, }; use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; use cumulus_primitives_core::AggregateMessageOrigin; @@ -84,9 +84,7 @@ use parachains_common::{ Signature, AVERAGE_ON_INITIALIZE_RATIO, DAYS, HOURS, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO, SLOT_DURATION, }; - use sp_runtime::{Perbill, RuntimeDebug}; -use xcm::opaque::v3::MultiLocation; use xcm_config::{ ForeignAssetsConvertedConcreteId, GovernanceLocation, PoolAssetsConvertedConcreteId, TokenLocation, TrustBackedAssetsConvertedConcreteId, @@ -101,7 +99,7 @@ use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; use xcm::latest::prelude::*; use crate::xcm_config::{ - ForeignCreatorsSovereignAccountOf, LocalAndForeignAssetsMultiLocationMatcher, + ForeignCreatorsSovereignAccountOf, LocalAndForeignAssetsLocationMatcher, TrustBackedAssetsPalletLocation, }; use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; @@ -344,7 +342,7 @@ impl pallet_asset_conversion::Config for Runtime { type HigherPrecisionBalance = sp_core::U256; type Currency = Balances; type AssetBalance = Balance; - type AssetId = MultiLocation; + type AssetId = Location; type Assets = LocalAndForeignAssets< Assets, AssetIdForTrustBackedAssetsConvert, @@ -360,14 +358,14 @@ impl pallet_asset_conversion::Config for Runtime { type PalletId = AssetConversionPalletId; type AllowMultiAssetPools = AllowMultiAssetPools; type MaxSwapPathLength = ConstU32<4>; - type MultiAssetId = Box; + type MultiAssetId = Box; type MultiAssetIdConverter = - MultiLocationConverter; + LocationConverter; type MintMinLiquidity = ConstU128<100>; type WeightInfo = weights::pallet_asset_conversion::WeightInfo; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = - crate::xcm_config::BenchmarkMultiLocationConverter>; + crate::xcm_config::BenchmarkLocationConverter>; } parameter_types! { @@ -388,8 +386,8 @@ pub type ForeignAssetsInstance = pallet_assets::Instance2; impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; - type AssetId = MultiLocationForAssetId; - type AssetIdParameter = MultiLocationForAssetId; + type AssetId = LocationForAssetId; + type AssetIdParameter = LocationForAssetId; type Currency = Balances; type CreateOrigin = ForeignCreators< (FromSiblingParachain>,), @@ -670,7 +668,7 @@ impl cumulus_pallet_aura_ext::Config for Runtime {} parameter_types! { /// The asset ID for the asset that we use to pay for message delivery fees. - pub FeeAssetId: AssetId = Concrete(xcm_config::TokenLocation::get()); + pub FeeAssetId: AssetId = AssetId(xcm_config::TokenLocation::get()); /// The base fee for the message delivery fees. pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); } @@ -1182,16 +1180,16 @@ impl_runtime_apis! { Block, Balance, u128, - Box, + Box, > for Runtime { - fn quote_price_exact_tokens_for_tokens(asset1: Box, asset2: Box, amount: u128, include_fee: bool) -> Option { + fn quote_price_exact_tokens_for_tokens(asset1: Box, asset2: Box, amount: u128, include_fee: bool) -> Option { AssetConversion::quote_price_exact_tokens_for_tokens(asset1, asset2, amount, include_fee) } - fn quote_price_tokens_for_exact_tokens(asset1: Box, asset2: Box, amount: u128, include_fee: bool) -> Option { + fn quote_price_tokens_for_exact_tokens(asset1: Box, asset2: Box, amount: u128, include_fee: bool) -> Option { AssetConversion::quote_price_tokens_for_exact_tokens(asset1, asset2, amount, include_fee) } - fn get_reserves(asset1: Box, asset2: Box) -> Option<(Balance, Balance)> { + fn get_reserves(asset1: Box, asset2: Box) -> Option<(Balance, Balance)> { AssetConversion::get_reserves(&asset1, &asset2).ok() } } @@ -1245,7 +1243,7 @@ impl_runtime_apis! { AccountId, > for Runtime { - fn query_account_balances(account: AccountId) -> Result { + fn query_account_balances(account: AccountId) -> Result { use assets_common::fungible_conversion::{convert, convert_balance}; Ok([ // collect pallet_balance @@ -1371,31 +1369,31 @@ impl_runtime_apis! { use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsiscsBenchmark; impl pallet_xcm::benchmarking::Config for Runtime { - fn reachable_dest() -> Option { + fn reachable_dest() -> Option { Some(Parent.into()) } - fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { // Relay/native token can be teleported between AH and Relay. Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Parent.into()) + id: AssetId(Parent.into()) }, Parent.into(), )) } - fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { // AH can reserve transfer native token to some random parachain. let random_para_id = 43211234; ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( random_para_id.into() ); Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Parent.into()) + id: AssetId(Parent.into()) }, ParentThen(Parachain(random_para_id).into()).into(), )) @@ -1408,7 +1406,7 @@ impl_runtime_apis! { xcm_config::bridging::SiblingBridgeHubParaId::get().into() ); } - fn ensure_bridged_target_destination() -> MultiLocation { + fn ensure_bridged_target_destination() -> Location { ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( xcm_config::bridging::SiblingBridgeHubParaId::get().into() ); @@ -1421,7 +1419,7 @@ impl_runtime_apis! { xcm_config::bridging::SiblingBridgeHubParaId::get().into() ); } - fn ensure_bridged_target_destination() -> MultiLocation { + fn ensure_bridged_target_destination() -> Location { ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( xcm_config::bridging::SiblingBridgeHubParaId::get().into() ); @@ -1434,7 +1432,7 @@ impl_runtime_apis! { xcm_config::bridging::SiblingBridgeHubParaId::get().into() ); } - fn ensure_bridged_target_destination() -> MultiLocation { + fn ensure_bridged_target_destination() -> Location { xcm_config::Flavor::set(&RuntimeFlavor::Wococo); ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( xcm_config::bridging::SiblingBridgeHubParaId::get().into() @@ -1448,7 +1446,7 @@ impl_runtime_apis! { use pallet_xcm_benchmarks::asset_instance_from; parameter_types! { - pub ExistentialDepositMultiAsset: Option = Some(( + pub ExistentialDepositAsset: Option = Some(( TokenLocation::get(), ExistentialDeposit::get() ).into()); @@ -1458,34 +1456,34 @@ impl_runtime_apis! { type XcmConfig = xcm_config::XcmConfig; type AccountIdConverter = xcm_config::LocationToAccountId; type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< - xcm_config::XcmConfig, - ExistentialDepositMultiAsset, + xcm_config::XcmConfig, + ExistentialDepositAsset, xcm_config::PriceForParentDelivery, >; - fn valid_destination() -> Result { + fn valid_destination() -> Result { Ok(TokenLocation::get()) } - fn worst_case_holding(depositable_count: u32) -> MultiAssets { + fn worst_case_holding(depositable_count: u32) -> Assets { // A mix of fungible, non-fungible, and concrete assets. let holding_non_fungibles = MaxAssetsIntoHolding::get() / 2 - depositable_count; let holding_fungibles = holding_non_fungibles.saturating_sub(1); let fungibles_amount: u128 = 100; let mut assets = (0..holding_fungibles) .map(|i| { - MultiAsset { - id: Concrete(GeneralIndex(i as u128).into()), + Asset { + id: GeneralIndex(i as u128).into(), fun: Fungible(fungibles_amount * i as u128), } }) - .chain(core::iter::once(MultiAsset { id: Concrete(Here.into()), fun: Fungible(u128::MAX) })) - .chain((0..holding_non_fungibles).map(|i| MultiAsset { - id: Concrete(GeneralIndex(i as u128).into()), + .chain(core::iter::once(Asset { id: Here.into(), fun: Fungible(u128::MAX) })) + .chain((0..holding_non_fungibles).map(|i| Asset { + id: GeneralIndex(i as u128).into(), fun: NonFungible(asset_instance_from(i)), })) .collect::>(); - assets.push(MultiAsset { - id: Concrete(TokenLocation::get()), + assets.push(Asset { + id: AssetId(TokenLocation::get()), fun: Fungible(1_000_000 * UNITS), }); assets.into() @@ -1493,16 +1491,16 @@ impl_runtime_apis! { } parameter_types! { - pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + pub const TrustedTeleporter: Option<(Location, Asset)> = Some(( TokenLocation::get(), - MultiAsset { fun: Fungible(UNITS), id: Concrete(TokenLocation::get()) }, + Asset { fun: Fungible(UNITS), id: AssetId(TokenLocation::get()) }, )); pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None; // AssetHubRococo trusts AssetHubWococo as reserve for WOCs - pub TrustedReserve: Option<(MultiLocation, MultiAsset)> = Some( + pub TrustedReserve: Option<(Location, Asset)> = Some( ( xcm_config::bridging::to_wococo::AssetHubWococo::get(), - MultiAsset::from((xcm_config::bridging::to_wococo::WocLocation::get(), 1000000000000 as u128)) + Asset::from((xcm_config::bridging::to_wococo::WocLocation::get(), 1000000000000 as u128)) ) ); } @@ -1514,9 +1512,9 @@ impl_runtime_apis! { type TrustedTeleporter = TrustedTeleporter; type TrustedReserve = TrustedReserve; - fn get_multi_asset() -> MultiAsset { - MultiAsset { - id: Concrete(TokenLocation::get()), + fn get_asset() -> Asset { + Asset { + id: AssetId(TokenLocation::get()), fun: Fungible(UNITS), } } @@ -1530,42 +1528,42 @@ impl_runtime_apis! { (0u64, Response::Version(Default::default())) } - fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> { Err(BenchmarkError::Skip) } - fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + fn universal_alias() -> Result<(Location, Junction), BenchmarkError> { match xcm_config::bridging::BridgingBenchmarksHelper::prepare_universal_alias() { Some(alias) => Ok(alias), None => Err(BenchmarkError::Skip) } } - fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> { + fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> { Ok((TokenLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) } - fn subscribe_origin() -> Result { + fn subscribe_origin() -> Result { Ok(TokenLocation::get()) } - fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { + fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> { let origin = TokenLocation::get(); - let assets: MultiAssets = (Concrete(TokenLocation::get()), 1_000 * UNITS).into(); - let ticket = MultiLocation { parents: 0, interior: Here }; + let assets: Assets = (TokenLocation::get(), 1_000 * UNITS).into(); + let ticket = Location { parents: 0, interior: Here }; Ok((origin, ticket, assets)) } - fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { + fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> { Err(BenchmarkError::Skip) } fn export_message_origin_and_destination( - ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { + ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> { Err(BenchmarkError::Skip) } - fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { + fn alias_origin() -> Result<(Location, Location), BenchmarkError> { Err(BenchmarkError::Skip) } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs index 2fbbd61654be..26ef33bf98b0 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs @@ -24,14 +24,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; -trait WeighMultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight; +trait WeighAssets { + fn weigh_assets(&self, weight: Weight) -> Weight; } const MAX_ASSETS: u64 = 100; -impl WeighMultiAssets for MultiAssetFilter { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for AssetFilter { + fn weigh_assets(&self, weight: Weight) -> Weight { match self { Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64), Self::Wild(asset) => match asset { @@ -50,40 +50,40 @@ impl WeighMultiAssets for MultiAssetFilter { } } -impl WeighMultiAssets for MultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for Assets { + fn weigh_assets(&self, weight: Weight) -> Weight { weight.saturating_mul(self.inner().iter().count() as u64) } } pub struct AssetHubRococoXcmWeight(core::marker::PhantomData); impl XcmWeightInfo for AssetHubRococoXcmWeight { - fn withdraw_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::withdraw_asset()) + fn withdraw_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::withdraw_asset()) } - fn reserve_asset_deposited(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::reserve_asset_deposited()) + fn reserve_asset_deposited(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::reserve_asset_deposited()) } - fn receive_teleported_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::receive_teleported_asset()) + fn receive_teleported_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::receive_teleported_asset()) } fn query_response( _query_id: &u64, _response: &Response, _max_weight: &Weight, - _querier: &Option, + _querier: &Option, ) -> Weight { XcmGeneric::::query_response() } - fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_asset()) + fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::transfer_asset()) } fn transfer_reserve_asset( - assets: &MultiAssets, - _dest: &MultiLocation, + assets: &Assets, + _dest: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_reserve_asset()) + assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } fn transact( _origin_type: &OriginKind, @@ -111,43 +111,43 @@ impl XcmWeightInfo for AssetHubRococoXcmWeight { fn clear_origin() -> Weight { XcmGeneric::::clear_origin() } - fn descend_origin(_who: &InteriorMultiLocation) -> Weight { + fn descend_origin(_who: &InteriorLocation) -> Weight { XcmGeneric::::descend_origin() } fn report_error(_query_response_info: &QueryResponseInfo) -> Weight { XcmGeneric::::report_error() } - fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_asset()) + fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::deposit_asset()) } fn deposit_reserve_asset( - assets: &MultiAssetFilter, - _dest: &MultiLocation, + assets: &AssetFilter, + _dest: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_reserve_asset()) + assets.weigh_assets(XcmFungibleWeight::::deposit_reserve_asset()) } - fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight { + fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight { Weight::MAX } fn initiate_reserve_withdraw( - assets: &MultiAssetFilter, - _reserve: &MultiLocation, + assets: &AssetFilter, + _reserve: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) + assets.weigh_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) } fn initiate_teleport( - assets: &MultiAssetFilter, - _dest: &MultiLocation, + assets: &AssetFilter, + _dest: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_teleport()) + assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } - fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight { + fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } - fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight { + fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } fn refund_surplus() -> Weight { @@ -162,7 +162,7 @@ impl XcmWeightInfo for AssetHubRococoXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } - fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight { + fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } fn trap(_code: &u64) -> Weight { @@ -174,13 +174,13 @@ impl XcmWeightInfo for AssetHubRococoXcmWeight { fn unsubscribe_version() -> Weight { XcmGeneric::::unsubscribe_version() } - fn burn_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + fn burn_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::burn_asset()) } - fn expect_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + fn expect_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::expect_asset()) } - fn expect_origin(_origin: &Option) -> Weight { + fn expect_origin(_origin: &Option) -> Weight { XcmGeneric::::expect_origin() } fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { @@ -213,16 +213,16 @@ impl XcmWeightInfo for AssetHubRococoXcmWeight { fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight { Weight::MAX } - fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn lock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn unlock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn note_unlockable(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn request_unlock(_: &Asset, _: &Location) -> Weight { Weight::MAX } fn set_fees_mode(_: &bool) -> Weight { @@ -234,11 +234,11 @@ impl XcmWeightInfo for AssetHubRococoXcmWeight { fn clear_topic() -> Weight { XcmGeneric::::clear_topic() } - fn alias_origin(_: &MultiLocation) -> Weight { + fn alias_origin(_: &Location) -> Weight { // XCM Executor does not currently support alias origin operations Weight::MAX } - fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { + fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs index b0bf9e827296..3c2334ee149f 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs @@ -21,11 +21,11 @@ use super::{ TrustBackedAssetsInstance, WeightToFee, XcmpQueue, }; use assets_common::{ - local_and_foreign_assets::MatchesLocalAndForeignAssetsMultiLocation, + local_and_foreign_assets::MatchesLocalAndForeignAssetsLocation, matching::{FromSiblingParachain, IsForeignConcreteAsset}, }; use frame_support::{ - match_types, parameter_types, + parameter_types, traits::{ConstU32, Contains, Equals, Everything, Get, Nothing, PalletInfoAccess}, }; use frame_system::EnsureRoot; @@ -62,21 +62,21 @@ use cumulus_primitives_core::ParaId; parameter_types! { pub storage Flavor: RuntimeFlavor = RuntimeFlavor::default(); - pub const TokenLocation: MultiLocation = MultiLocation::parent(); + pub const TokenLocation: Location = Location::parent(); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = - X2(GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocation: InteriorLocation = + [GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into(); pub UniversalLocationNetworkId: NetworkId = UniversalLocation::get().global_consensus().unwrap(); - pub TrustBackedAssetsPalletLocation: MultiLocation = + pub TrustBackedAssetsPalletLocation: Location = PalletInstance(::index() as u8).into(); - pub ForeignAssetsPalletLocation: MultiLocation = + pub ForeignAssetsPalletLocation: Location = PalletInstance(::index() as u8).into(); - pub PoolAssetsPalletLocation: MultiLocation = + pub PoolAssetsPalletLocation: Location = PalletInstance(::index() as u8).into(); pub CheckingAccount: AccountId = PolkadotXcm::check_account(); - pub const GovernanceLocation: MultiLocation = MultiLocation::parent(); + pub const GovernanceLocation: Location = Location::parent(); pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating(); - pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into(); + pub RelayTreasuryLocation: Location = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into(); } /// Adapter for resolving `NetworkId` based on `pub storage Flavor: RuntimeFlavor`. @@ -95,7 +95,7 @@ impl Get for RelayNetwork { } } -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( @@ -118,7 +118,7 @@ pub type CurrencyTransactor = CurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -136,7 +136,7 @@ pub type FungiblesTransactor = FungiblesAdapter< Assets, // Use this currency when it is a fungible asset matching the given location or name: TrustBackedAssetsConvertedConcreteId, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -153,7 +153,7 @@ pub type ForeignAssetsConvertedConcreteId = assets_common::ForeignAssetsConverte // Ignore `TrustBackedAssets` explicitly StartsWith, // Ignore assets that start explicitly with our `GlobalConsensus(NetworkId)`, means: - // - foreign assets from our consensus should be: `MultiLocation {parents: 1, + // - foreign assets from our consensus should be: `Location {parents: 1, // X*(Parachain(xyz), ..)}` // - foreign assets outside our consensus with the same `GlobalConsensus(NetworkId)` won't // be accepted here @@ -168,7 +168,7 @@ pub type ForeignFungiblesTransactor = FungiblesAdapter< ForeignAssets, // Use this currency when it is a fungible asset matching the given location or name: ForeignAssetsConvertedConcreteId, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -188,7 +188,7 @@ pub type PoolFungiblesTransactor = FungiblesAdapter< PoolAssets, // Use this currency when it is a fungible asset matching the given location or name: PoolAssetsConvertedConcreteId, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -203,20 +203,20 @@ pub type PoolFungiblesTransactor = FungiblesAdapter< pub type AssetTransactors = (CurrencyTransactor, FungiblesTransactor, ForeignFungiblesTransactor, PoolFungiblesTransactor); -/// Simple `MultiLocation` matcher for Local and Foreign asset `MultiLocation`. -pub struct LocalAndForeignAssetsMultiLocationMatcher; -impl MatchesLocalAndForeignAssetsMultiLocation for LocalAndForeignAssetsMultiLocationMatcher { - fn is_local(location: &MultiLocation) -> bool { - use assets_common::fungible_conversion::MatchesMultiLocation; +/// Simple `Location` matcher for Local and Foreign asset `Location`. +pub struct LocalAndForeignAssetsLocationMatcher; +impl MatchesLocalAndForeignAssetsLocation for LocalAndForeignAssetsLocationMatcher { + fn is_local(location: &Location) -> bool { + use assets_common::fungible_conversion::MatchesLocation; TrustBackedAssetsConvertedConcreteId::contains(location) } - fn is_foreign(location: &MultiLocation) -> bool { - use assets_common::fungible_conversion::MatchesMultiLocation; + fn is_foreign(location: &Location) -> bool { + use assets_common::fungible_conversion::MatchesLocation; ForeignAssetsConvertedConcreteId::contains(location) } } -impl Contains for LocalAndForeignAssetsMultiLocationMatcher { - fn contains(location: &MultiLocation) -> bool { +impl Contains for LocalAndForeignAssetsLocationMatcher { + fn contains(location: &Location) -> bool { Self::is_local(location) || Self::is_foreign(location) } } @@ -251,15 +251,18 @@ parameter_types! { pub XcmAssetFeesReceiver: Option = Authorship::author(); } -match_types! { - pub type ParentOrParentsPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { .. }) } - }; - pub type ParentOrSiblings: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(_) } - }; +pub struct ParentOrParentsPlurality; +impl Contains for ParentOrParentsPlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [Plurality { .. }])) + } +} + +pub struct ParentOrSiblings; +impl Contains for ParentOrSiblings { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [_])) + } } /// A call filter for the XCM Transact instruction. This is a temporary measure until we properly @@ -533,18 +536,12 @@ pub type ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger = ForeignAssetsInstance, >; -match_types! { - pub type SystemParachains: impl Contains = { - MultiLocation { - parents: 1, - interior: X1(Parachain( - system_parachain::ASSET_HUB_ID | - system_parachain::BRIDGE_HUB_ID | - system_parachain::CONTRACTS_ID | - system_parachain::ENCOINTER_ID - )), - } - }; +pub struct SystemParachains; +impl Contains for SystemParachains { + fn contains(location: &Location) -> bool { + use system_parachain::{ASSET_HUB_ID, BRIDGE_HUB_ID, CONTRACTS_ID, ENCOINTER_ID}; + matches!(location.unpack(), (1, [Parachain(ASSET_HUB_ID | BRIDGE_HUB_ID | CONTRACTS_ID | ENCOINTER_ID)])) + } } /// Locations that will not be charged fees in the executor, @@ -637,7 +634,7 @@ impl xcm_executor::Config for XcmConfig { type Aliasers = Nothing; } -/// Converts a local signed origin into an XCM multilocation. +/// Converts a local signed origin into an XCM location. /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; @@ -715,35 +712,32 @@ pub type ForeignCreatorsSovereignAccountOf = ( /// Simple conversion of `u32` into an `AssetId` for use in benchmarking. pub struct XcmBenchmarkHelper; #[cfg(feature = "runtime-benchmarks")] -impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { - fn create_asset_id_parameter(id: u32) -> MultiLocation { - MultiLocation { parents: 1, interior: X1(Parachain(id)) } +impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { + fn create_asset_id_parameter(id: u32) -> Location { + Location::new(1, [Parachain(id)]) } } #[cfg(feature = "runtime-benchmarks")] -pub struct BenchmarkMultiLocationConverter { +pub struct BenchmarkLocationConverter { _phantom: sp_std::marker::PhantomData, } #[cfg(feature = "runtime-benchmarks")] impl - pallet_asset_conversion::BenchmarkHelper> - for BenchmarkMultiLocationConverter + pallet_asset_conversion::BenchmarkHelper> + for BenchmarkLocationConverter where SelfParaId: Get, { - fn asset_id(asset_id: u32) -> MultiLocation { - MultiLocation { - parents: 1, - interior: X3( - Parachain(SelfParaId::get().into()), - PalletInstance(::index() as u8), - GeneralIndex(asset_id.into()), - ), - } + fn asset_id(asset_id: u32) -> Location { + Location::new(1, [ + Parachain(SelfParaId::get().into()), + PalletInstance(::index() as u8), + GeneralIndex(asset_id.into()), + ]) } - fn multiasset_id(asset_id: u32) -> sp_std::boxed::Box { + fn multiasset_id(asset_id: u32) -> sp_std::boxed::Box { sp_std::boxed::Box::new(Self::asset_id(asset_id)) } } @@ -779,7 +773,7 @@ pub mod bridging { RuntimeFlavor::Rococo => bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, RuntimeFlavor::Wococo => bp_bridge_hub_wococo::BRIDGE_HUB_WOCOCO_PARACHAIN_ID, }; - pub SiblingBridgeHub: MultiLocation = MultiLocation::new(1, X1(Parachain(SiblingBridgeHubParaId::get()))); + pub SiblingBridgeHub: Location = Location::new(1, [Parachain(SiblingBridgeHubParaId::get())]); /// Router expects payment with this `AssetId`. /// (`AssetId` has to be aligned with `BridgeTable`) pub XcmBridgeHubRouterFeeAssetId: AssetId = TokenLocation::get().into(); @@ -798,25 +792,25 @@ pub mod bridging { use super::*; parameter_types! { - pub SiblingBridgeHubWithBridgeHubWococoInstance: MultiLocation = MultiLocation::new( + pub SiblingBridgeHubWithBridgeHubWococoInstance: Location = Location::new( 1, - X2( + [ Parachain(SiblingBridgeHubParaId::get()), - PalletInstance(bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WOCOCO_MESSAGES_PALLET_INDEX) - ) + PalletInstance(bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WOCOCO_MESSAGES_PALLET_INDEX), + ] ); pub const WococoNetwork: NetworkId = NetworkId::Wococo; - pub AssetHubWococo: MultiLocation = MultiLocation::new(2, X2(GlobalConsensus(WococoNetwork::get()), Parachain(bp_asset_hub_wococo::ASSET_HUB_WOCOCO_PARACHAIN_ID))); - pub WocLocation: MultiLocation = MultiLocation::new(2, X1(GlobalConsensus(WococoNetwork::get()))); + pub AssetHubWococo: Location = Location::new(2, [GlobalConsensus(WococoNetwork::get()), Parachain(bp_asset_hub_wococo::ASSET_HUB_WOCOCO_PARACHAIN_ID)]); + pub WocLocation: Location = Location::new(2, [GlobalConsensus(WococoNetwork::get())]); - pub WocFromAssetHubWococo: (MultiAssetFilter, MultiLocation) = ( - Wild(AllOf { fun: WildFungible, id: Concrete(WocLocation::get()) }), + pub WocFromAssetHubWococo: (AssetFilter, Location) = ( + Wild(AllOf { fun: WildFungible, id: AssetId(WocLocation::get()) }), AssetHubWococo::get() ); /// Set up exporters configuration. - /// `Option` represents static "base fee" which is used for total delivery fee calculation. + /// `Option` represents static "base fee" which is used for total delivery fee calculation. pub BridgeTable: sp_std::vec::Vec = sp_std::vec![ NetworkExportTableItem::new( WococoNetwork::get(), @@ -833,15 +827,15 @@ pub mod bridging { ]; /// Universal aliases - pub UniversalAliases: BTreeSet<(MultiLocation, Junction)> = BTreeSet::from_iter( + pub UniversalAliases: BTreeSet<(Location, Junction)> = BTreeSet::from_iter( sp_std::vec![ (SiblingBridgeHubWithBridgeHubWococoInstance::get(), GlobalConsensus(WococoNetwork::get())) ] ); } - impl Contains<(MultiLocation, Junction)> for UniversalAliases { - fn contains(alias: &(MultiLocation, Junction)) -> bool { + impl Contains<(Location, Junction)> for UniversalAliases { + fn contains(alias: &(Location, Junction)) -> bool { UniversalAliases::get().contains(alias) } } @@ -874,25 +868,25 @@ pub mod bridging { use super::*; parameter_types! { - pub SiblingBridgeHubWithBridgeHubWestendInstance: MultiLocation = MultiLocation::new( + pub SiblingBridgeHubWithBridgeHubWestendInstance: Location = Location::new( 1, - X2( + [ Parachain(SiblingBridgeHubParaId::get()), PalletInstance(bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WESTEND_MESSAGES_PALLET_INDEX) - ) + ] ); pub const WestendNetwork: NetworkId = NetworkId::Westend; - pub AssetHubWestend: MultiLocation = MultiLocation::new(2, X2(GlobalConsensus(WestendNetwork::get()), Parachain(bp_asset_hub_westend::ASSET_HUB_WESTEND_PARACHAIN_ID))); - pub WndLocation: MultiLocation = MultiLocation::new(2, X1(GlobalConsensus(WestendNetwork::get()))); + pub AssetHubWestend: Location = Location::new(2, [GlobalConsensus(WestendNetwork::get()), Parachain(bp_asset_hub_westend::ASSET_HUB_WESTEND_PARACHAIN_ID)]); + pub WndLocation: Location = Location::new(2, [GlobalConsensus(WestendNetwork::get())]); - pub WndFromAssetHubWestend: (MultiAssetFilter, MultiLocation) = ( - Wild(AllOf { fun: WildFungible, id: Concrete(WndLocation::get()) }), + pub WndFromAssetHubWestend: (AssetFilter, Location) = ( + Wild(AllOf { fun: WildFungible, id: AssetId(WndLocation::get()) }), AssetHubWestend::get() ); /// Set up exporters configuration. - /// `Option` represents static "base fee" which is used for total delivery fee calculation. + /// `Option` represents static "base fee" which is used for total delivery fee calculation. pub BridgeTable: sp_std::vec::Vec = sp_std::vec![ NetworkExportTableItem::new( WestendNetwork::get(), @@ -909,15 +903,15 @@ pub mod bridging { ]; /// Universal aliases - pub UniversalAliases: BTreeSet<(MultiLocation, Junction)> = BTreeSet::from_iter( + pub UniversalAliases: BTreeSet<(Location, Junction)> = BTreeSet::from_iter( sp_std::vec![ (SiblingBridgeHubWithBridgeHubWestendInstance::get(), GlobalConsensus(WestendNetwork::get())) ] ); } - impl Contains<(MultiLocation, Junction)> for UniversalAliases { - fn contains(alias: &(MultiLocation, Junction)) -> bool { + impl Contains<(Location, Junction)> for UniversalAliases { + fn contains(alias: &(Location, Junction)) -> bool { UniversalAliases::get().contains(alias) } } @@ -950,25 +944,25 @@ pub mod bridging { use super::*; parameter_types! { - pub SiblingBridgeHubWithBridgeHubRococoInstance: MultiLocation = MultiLocation::new( + pub SiblingBridgeHubWithBridgeHubRococoInstance: Location = Location::new( 1, - X2( + [ Parachain(SiblingBridgeHubParaId::get()), - PalletInstance(bp_bridge_hub_wococo::WITH_BRIDGE_WOCOCO_TO_ROCOCO_MESSAGES_PALLET_INDEX) - ) + PalletInstance(bp_bridge_hub_wococo::WITH_BRIDGE_WOCOCO_TO_ROCOCO_MESSAGES_PALLET_INDEX), + ] ); pub const RococoNetwork: NetworkId = NetworkId::Rococo; - pub AssetHubRococo: MultiLocation = MultiLocation::new(2, X2(GlobalConsensus(RococoNetwork::get()), Parachain(bp_asset_hub_rococo::ASSET_HUB_ROCOCO_PARACHAIN_ID))); - pub RocLocation: MultiLocation = MultiLocation::new(2, X1(GlobalConsensus(RococoNetwork::get()))); + pub AssetHubRococo: Location = Location::new(2, [GlobalConsensus(RococoNetwork::get()), Parachain(bp_asset_hub_rococo::ASSET_HUB_ROCOCO_PARACHAIN_ID)]); + pub RocLocation: Location = Location::new(2, [GlobalConsensus(RococoNetwork::get())]); - pub RocFromAssetHubRococo: (MultiAssetFilter, MultiLocation) = ( - Wild(AllOf { fun: WildFungible, id: Concrete(RocLocation::get()) }), + pub RocFromAssetHubRococo: (AssetFilter, Location) = ( + Wild(AllOf { fun: WildFungible, id: AssetId(RocLocation::get()) }), AssetHubRococo::get() ); /// Set up exporters configuration. - /// `Option` represents static "base fee" which is used for total delivery fee calculation. + /// `Option` represents static "base fee" which is used for total delivery fee calculation. pub BridgeTable: sp_std::vec::Vec = sp_std::vec![ NetworkExportTableItem::new( RococoNetwork::get(), @@ -985,15 +979,15 @@ pub mod bridging { ]; /// Universal aliases - pub UniversalAliases: BTreeSet<(MultiLocation, Junction)> = BTreeSet::from_iter( + pub UniversalAliases: BTreeSet<(Location, Junction)> = BTreeSet::from_iter( sp_std::vec![ (SiblingBridgeHubWithBridgeHubRococoInstance::get(), GlobalConsensus(RococoNetwork::get())) ] ); } - impl Contains<(MultiLocation, Junction)> for UniversalAliases { - fn contains(alias: &(MultiLocation, Junction)) -> bool { + impl Contains<(Location, Junction)> for UniversalAliases { + fn contains(alias: &(Location, Junction)) -> bool { UniversalAliases::get().contains(alias) } } @@ -1028,7 +1022,7 @@ pub mod bridging { #[cfg(feature = "runtime-benchmarks")] impl BridgingBenchmarksHelper { - pub fn prepare_universal_alias() -> Option<(MultiLocation, Junction)> { + pub fn prepare_universal_alias() -> Option<(Location, Junction)> { let alias = to_westend::UniversalAliases::get() .into_iter() diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs index b4f4e828dde8..423dbc2b4e52 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs @@ -45,7 +45,7 @@ use parachains_common::{ rococo::fee::WeightToFee, AccountId, AssetIdForTrustBackedAssets, AuraId, Balance, }; use sp_runtime::traits::MaybeEquivalence; -use xcm::latest::prelude::*; +use xcm::latest::prelude::{*, Assets as XcmAssets}; use xcm_executor::traits::{Identity, JustTry, WeightTrader}; const ALICE: [u8; 32] = [1u8; 32]; @@ -98,8 +98,8 @@ fn test_asset_xcm_trader() { minimum_asset_balance )); - // get asset id as multilocation - let asset_multilocation = + // get asset id as location + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&local_asset_id).unwrap(); // Set Alice as block author, who will receive fees @@ -118,8 +118,8 @@ fn test_asset_xcm_trader() { // Lets pay with: asset_amount_needed + asset_amount_extra let asset_amount_extra = 100_u128; - let asset: MultiAsset = - (asset_multilocation, asset_amount_needed + asset_amount_extra).into(); + let asset: Asset = + (asset_location.clone(), asset_amount_needed + asset_amount_extra).into(); let mut trader = ::Trader::new(); let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; @@ -128,7 +128,7 @@ fn test_asset_xcm_trader() { let unused_assets = trader.buy_weight(bought, asset.into(), &ctx).expect("Expected Ok"); // Check whether a correct amount of unused assets is returned assert_ok!( - unused_assets.ensure_contains(&(asset_multilocation, asset_amount_extra).into()) + unused_assets.ensure_contains(&(asset_location, asset_amount_extra).into()) ); // Drop trader @@ -186,12 +186,12 @@ fn test_asset_xcm_trader_with_refund() { // We are going to buy 4e9 weight let bought = Weight::from_parts(4_000_000_000u64, 0); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); // lets calculate amount needed let amount_bought = WeightToFee::weight_to_fee(&bought); - let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + let asset: Asset = (asset_location.clone(), amount_bought).into(); // Make sure buy_weight does not return an error assert_ok!(trader.buy_weight(bought, asset.clone().into(), &ctx)); @@ -209,7 +209,7 @@ fn test_asset_xcm_trader_with_refund() { assert_eq!( trader.refund_weight(bought - weight_used, &ctx), - Some((asset_multilocation, amount_refunded).into()) + Some((asset_location, amount_refunded).into()) ); // Drop trader @@ -258,7 +258,7 @@ fn test_asset_xcm_trader_refund_not_possible_since_amount_less_than_ed() { // We are going to buy small amount let bought = Weight::from_parts(500_000_000u64, 0); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); let amount_bought = WeightToFee::weight_to_fee(&bought); @@ -267,7 +267,7 @@ fn test_asset_xcm_trader_refund_not_possible_since_amount_less_than_ed() { "we are testing what happens when the amount does not exceed ED" ); - let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + let asset: Asset = (asset_location, amount_bought).into(); // Buy weight should return an error assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); @@ -310,7 +310,7 @@ fn test_that_buying_ed_refund_does_not_refund() { // We are gonna buy ED let bought = Weight::from_parts(ExistentialDeposit::get().try_into().unwrap(), 0); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); let amount_bought = WeightToFee::weight_to_fee(&bought); @@ -321,11 +321,11 @@ fn test_that_buying_ed_refund_does_not_refund() { // We know we will have to buy at least ED, so lets make sure first it will // fail with a payment of less than ED - let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + let asset: Asset = (asset_location.clone(), amount_bought).into(); assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); // Now lets buy ED at least - let asset: MultiAsset = (asset_multilocation, ExistentialDeposit::get()).into(); + let asset: Asset = (asset_location, ExistentialDeposit::get()).into(); // Buy weight should work assert_ok!(trader.buy_weight(bought, asset.into(), &ctx)); @@ -386,9 +386,9 @@ fn test_asset_xcm_trader_not_possible_for_non_sufficient_assets() { // lets calculate amount needed let asset_amount_needed = WeightToFee::weight_to_fee(&bought); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); - let asset: MultiAsset = (asset_multilocation, asset_amount_needed).into(); + let asset: Asset = (asset_location, asset_amount_needed).into(); // Make sure again buy_weight does return an error assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); @@ -418,19 +418,19 @@ fn test_assets_balances_api_works() { .build() .execute_with(|| { let local_asset_id = 1; - let foreign_asset_id_multilocation = - MultiLocation { parents: 1, interior: X2(Parachain(1234), GeneralIndex(12345)) }; + let foreign_asset_id_location = + Location::new(1, [Parachain(1234), GeneralIndex(12345)]); // check before assert_eq!(Assets::balance(local_asset_id, AccountId::from(ALICE)), 0); assert_eq!( - ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)), + ForeignAssets::balance(foreign_asset_id_location.clone(), AccountId::from(ALICE)), 0 ); assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 0); assert!(Runtime::query_account_balances(AccountId::from(ALICE)) .unwrap() - .try_as::() + .try_as::() .unwrap() .is_none()); @@ -461,7 +461,7 @@ fn test_assets_balances_api_works() { let foreign_asset_minimum_asset_balance = 3333333_u128; assert_ok!(ForeignAssets::force_create( RuntimeHelper::root_origin(), - foreign_asset_id_multilocation, + foreign_asset_id_location.clone(), AccountId::from(SOME_ASSET_ADMIN).into(), false, foreign_asset_minimum_asset_balance @@ -470,7 +470,7 @@ fn test_assets_balances_api_works() { // We first mint enough asset for the account to exist for assets assert_ok!(ForeignAssets::mint( RuntimeHelper::origin_of(AccountId::from(SOME_ASSET_ADMIN)), - foreign_asset_id_multilocation, + foreign_asset_id_location.clone(), AccountId::from(ALICE).into(), 6 * foreign_asset_minimum_asset_balance )); @@ -481,12 +481,12 @@ fn test_assets_balances_api_works() { minimum_asset_balance ); assert_eq!( - ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)), + ForeignAssets::balance(foreign_asset_id_location.clone(), AccountId::from(ALICE)), 6 * minimum_asset_balance ); assert_eq!(Balances::free_balance(AccountId::from(ALICE)), some_currency); - let result: MultiAssets = Runtime::query_account_balances(AccountId::from(ALICE)) + let result: XcmAssets = Runtime::query_account_balances(AccountId::from(ALICE)) .unwrap() .try_into() .unwrap(); @@ -507,7 +507,7 @@ fn test_assets_balances_api_works() { .into()))); // check foreign asset assert!(result.inner().iter().any(|asset| asset.eq(&( - Identity::convert_back(&foreign_asset_id_multilocation).unwrap(), + Identity::convert_back(&foreign_asset_id_location).unwrap(), 6 * foreign_asset_minimum_asset_balance ) .into()))); @@ -595,11 +595,11 @@ asset_test_utils::include_asset_transactor_transfer_with_pallet_assets_instance_ Runtime, XcmConfig, ForeignAssetsInstance, - MultiLocation, + Location, JustTry, collator_session_keys(), ExistentialDeposit::get(), - MultiLocation { parents: 1, interior: X2(Parachain(1313), GeneralIndex(12345)) }, + Location::new(1, [Parachain(1313), GeneralIndex(12345)]), Box::new(|| { assert!(Assets::asset_ids().collect::>().is_empty()); }), @@ -614,7 +614,7 @@ asset_test_utils::include_create_and_manage_foreign_assets_for_local_consensus_p WeightToFee, ForeignCreatorsSovereignAccountOf, ForeignAssetsInstance, - MultiLocation, + Location, JustTry, collator_session_keys(), ExistentialDeposit::get(), @@ -721,12 +721,12 @@ mod asset_hub_rococo_tests { AccountId::from([73; 32]), AccountId::from(BLOCK_AUTHOR_ACCOUNT), // receiving WOCs - (MultiLocation { parents: 2, interior: X1(GlobalConsensus(Wococo)) }, 1000000000000, 1_000_000_000), + (Location::new(2, [GlobalConsensus(Wococo)]), 1000000000000, 1_000_000_000), bridging_to_asset_hub_wococo, ( - X1(PalletInstance(bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WOCOCO_MESSAGES_PALLET_INDEX)), + [PalletInstance(bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WOCOCO_MESSAGES_PALLET_INDEX)].into(), GlobalConsensus(Wococo), - X1(Parachain(1000)) + [Parachain(1000)].into() ) ) } @@ -746,12 +746,12 @@ mod asset_hub_rococo_tests { AccountId::from([73; 32]), AccountId::from(BLOCK_AUTHOR_ACCOUNT), // receiving WNDs - (MultiLocation { parents: 2, interior: X1(GlobalConsensus(Westend)) }, 1000000000000, 1_000_000_000), + (Location::new(2, [GlobalConsensus(Westend)]), 1000000000000, 1_000_000_000), bridging_to_asset_hub_westend, ( - X1(PalletInstance(bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WESTEND_MESSAGES_PALLET_INDEX)), + [PalletInstance(bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WESTEND_MESSAGES_PALLET_INDEX)].into(), GlobalConsensus(Westend), - X1(Parachain(1000)) + [Parachain(1000)].into() ) ) } @@ -1017,12 +1017,12 @@ mod asset_hub_wococo_tests { AccountId::from([73; 32]), AccountId::from(BLOCK_AUTHOR_ACCOUNT), // receiving ROCs - (MultiLocation { parents: 2, interior: X1(GlobalConsensus(Rococo)) }, 1000000000000, 1_000_000_000), + (Location::new(2, [GlobalConsensus(Rococo)]), 1000000000000, 1_000_000_000), with_wococo_flavor_bridging_to_asset_hub_rococo, ( - X1(PalletInstance(bp_bridge_hub_wococo::WITH_BRIDGE_WOCOCO_TO_ROCOCO_MESSAGES_PALLET_INDEX)), + [PalletInstance(bp_bridge_hub_wococo::WITH_BRIDGE_WOCOCO_TO_ROCOCO_MESSAGES_PALLET_INDEX)].into(), GlobalConsensus(Rococo), - X1(Parachain(1000)) + [Parachain(1000)].into() ) ) } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs index d88aa2607e2d..5ec523bbe4be 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -27,11 +27,9 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); mod weights; pub mod xcm_config; -use crate::xcm_config::{ - LocalAndForeignAssetsMultiLocationMatcher, TrustBackedAssetsPalletLocation, -}; +use crate::xcm_config::{LocalAndForeignAssetsLocationMatcher, TrustBackedAssetsPalletLocation}; use assets_common::{ - local_and_foreign_assets::{LocalAndForeignAssets, MultiLocationConverter}, + local_and_foreign_assets::{LocalAndForeignAssets, LocationConverter}, AssetIdForTrustBackedAssetsConvert, }; use codec::{Decode, Encode, MaxEncodedLen}; @@ -77,7 +75,7 @@ use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; -use xcm::opaque::v3::MultiLocation; +use xcm::latest::prelude::Location; use xcm_config::{ ForeignAssetsConvertedConcreteId, PoolAssetsConvertedConcreteId, TrustBackedAssetsConvertedConcreteId, WestendLocation, XcmOriginToTransactDispatchOrigin, @@ -87,7 +85,7 @@ use xcm_config::{ pub use sp_runtime::BuildStorage; use assets_common::{ - foreign_creators::ForeignCreators, matching::FromSiblingParachain, MultiLocationForAssetId, + foreign_creators::ForeignCreators, matching::FromSiblingParachain, LocationForAssetId, }; use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; use xcm::latest::prelude::*; @@ -311,7 +309,7 @@ impl pallet_asset_conversion::Config for Runtime { type HigherPrecisionBalance = sp_core::U256; type Currency = Balances; type AssetBalance = Balance; - type AssetId = MultiLocation; + type AssetId = Location; type Assets = LocalAndForeignAssets< Assets, AssetIdForTrustBackedAssetsConvert, @@ -326,14 +324,14 @@ impl pallet_asset_conversion::Config for Runtime { type PalletId = AssetConversionPalletId; type AllowMultiAssetPools = AllowMultiAssetPools; type MaxSwapPathLength = ConstU32<4>; - type MultiAssetId = Box; + type MultiAssetId = Box; type MultiAssetIdConverter = - MultiLocationConverter; + LocationConverter; type MintMinLiquidity = ConstU128<100>; type WeightInfo = weights::pallet_asset_conversion::WeightInfo; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = - crate::xcm_config::BenchmarkMultiLocationConverter>; + crate::xcm_config::BenchmarkLocationConverter>; } parameter_types! { @@ -354,8 +352,8 @@ pub type ForeignAssetsInstance = pallet_assets::Instance2; impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; - type AssetId = MultiLocationForAssetId; - type AssetIdParameter = MultiLocationForAssetId; + type AssetId = LocationForAssetId; + type AssetIdParameter = LocationForAssetId; type Currency = Balances; type CreateOrigin = ForeignCreators< (FromSiblingParachain>,), @@ -636,7 +634,7 @@ impl cumulus_pallet_aura_ext::Config for Runtime {} parameter_types! { /// The asset ID for the asset that we use to pay for message delivery fees. - pub FeeAssetId: AssetId = Concrete(xcm_config::WestendLocation::get()); + pub FeeAssetId: AssetId = AssetId(xcm_config::WestendLocation::get()); /// The base fee for the message delivery fees. pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); } @@ -1162,18 +1160,18 @@ impl_runtime_apis! { Block, Balance, u128, - Box, + Box, > for Runtime { - fn quote_price_exact_tokens_for_tokens(asset1: Box, asset2: Box, amount: u128, include_fee: bool) -> Option { + fn quote_price_exact_tokens_for_tokens(asset1: Box, asset2: Box, amount: u128, include_fee: bool) -> Option { AssetConversion::quote_price_exact_tokens_for_tokens(asset1, asset2, amount, include_fee) } - fn quote_price_tokens_for_exact_tokens(asset1: Box, asset2: Box, amount: u128, include_fee: bool) -> Option { + fn quote_price_tokens_for_exact_tokens(asset1: Box, asset2: Box, amount: u128, include_fee: bool) -> Option { AssetConversion::quote_price_tokens_for_exact_tokens(asset1, asset2, amount, include_fee) } - fn get_reserves(asset1: Box, asset2: Box) -> Option<(Balance, Balance)> { + fn get_reserves(asset1: Box, asset2: Box) -> Option<(Balance, Balance)> { AssetConversion::get_reserves(&asset1, &asset2).ok() } } @@ -1227,7 +1225,7 @@ impl_runtime_apis! { AccountId, > for Runtime { - fn query_account_balances(account: AccountId) -> Result { + fn query_account_balances(account: AccountId) -> Result { use assets_common::fungible_conversion::{convert, convert_balance}; Ok([ // collect pallet_balance @@ -1346,31 +1344,31 @@ impl_runtime_apis! { use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsiscsBenchmark; impl pallet_xcm::benchmarking::Config for Runtime { - fn reachable_dest() -> Option { + fn reachable_dest() -> Option { Some(Parent.into()) } - fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { // Relay/native token can be teleported between AH and Relay. Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Parent.into()) + id: AssetId(Parent.into()) }, Parent.into(), )) } - fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { // AH can reserve transfer native token to some random parachain. let random_para_id = 43211234; ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( random_para_id.into() ); Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Parent.into()) + id: AssetId(Parent.into()) }, ParentThen(Parachain(random_para_id).into()).into(), )) @@ -1388,7 +1386,7 @@ impl_runtime_apis! { xcm_config::bridging::SiblingBridgeHubParaId::get().into() ); } - fn ensure_bridged_target_destination() -> MultiLocation { + fn ensure_bridged_target_destination() -> Location { ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( xcm_config::bridging::SiblingBridgeHubParaId::get().into() ); @@ -1401,7 +1399,7 @@ impl_runtime_apis! { use pallet_xcm_benchmarks::asset_instance_from; parameter_types! { - pub ExistentialDepositMultiAsset: Option = Some(( + pub ExistentialDepositAsset: Option = Some(( WestendLocation::get(), ExistentialDeposit::get() ).into()); @@ -1412,33 +1410,33 @@ impl_runtime_apis! { type AccountIdConverter = xcm_config::LocationToAccountId; type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< xcm_config::XcmConfig, - ExistentialDepositMultiAsset, + ExistentialDepositAsset, xcm_config::PriceForParentDelivery, >; - fn valid_destination() -> Result { + fn valid_destination() -> Result { Ok(WestendLocation::get()) } - fn worst_case_holding(depositable_count: u32) -> MultiAssets { + fn worst_case_holding(depositable_count: u32) -> Assets { // A mix of fungible, non-fungible, and concrete assets. let holding_non_fungibles = MaxAssetsIntoHolding::get() / 2 - depositable_count; let holding_fungibles = holding_non_fungibles - 1; let fungibles_amount: u128 = 100; let mut assets = (0..holding_fungibles) .map(|i| { - MultiAsset { - id: Concrete(GeneralIndex(i as u128).into()), + Asset { + id: AssetId(GeneralIndex(i as u128).into()), fun: Fungible(fungibles_amount * i as u128), } }) - .chain(core::iter::once(MultiAsset { id: Concrete(Here.into()), fun: Fungible(u128::MAX) })) - .chain((0..holding_non_fungibles).map(|i| MultiAsset { - id: Concrete(GeneralIndex(i as u128).into()), + .chain(core::iter::once(Asset { id: AssetId(Here.into()), fun: Fungible(u128::MAX) })) + .chain((0..holding_non_fungibles).map(|i| Asset { + id: AssetId(GeneralIndex(i as u128).into()), fun: NonFungible(asset_instance_from(i)), })) .collect::>(); - assets.push(MultiAsset { - id: Concrete(WestendLocation::get()), + assets.push(Asset { + id: AssetId(WestendLocation::get()), fun: Fungible(1_000_000 * UNITS), }); assets.into() @@ -1446,16 +1444,16 @@ impl_runtime_apis! { } parameter_types! { - pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + pub const TrustedTeleporter: Option<(Location, Asset)> = Some(( WestendLocation::get(), - MultiAsset { fun: Fungible(UNITS), id: Concrete(WestendLocation::get()) }, + Asset { fun: Fungible(UNITS), id: AssetId(WestendLocation::get()) }, )); pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None; // AssetHubWestend trusts AssetHubRococo as reserve for ROCs - pub TrustedReserve: Option<(MultiLocation, MultiAsset)> = Some( + pub TrustedReserve: Option<(Location, Asset)> = Some( ( xcm_config::bridging::to_rococo::AssetHubRococo::get(), - MultiAsset::from((xcm_config::bridging::to_rococo::RocLocation::get(), 1000000000000 as u128)) + Asset::from((xcm_config::bridging::to_rococo::RocLocation::get(), 1000000000000 as u128)) ) ); } @@ -1467,9 +1465,9 @@ impl_runtime_apis! { type TrustedTeleporter = TrustedTeleporter; type TrustedReserve = TrustedReserve; - fn get_multi_asset() -> MultiAsset { - MultiAsset { - id: Concrete(WestendLocation::get()), + fn get_asset() -> Asset { + Asset { + id: AssetId(WestendLocation::get()), fun: Fungible(UNITS), } } @@ -1483,42 +1481,42 @@ impl_runtime_apis! { (0u64, Response::Version(Default::default())) } - fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> { Err(BenchmarkError::Skip) } - fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + fn universal_alias() -> Result<(Location, Junction), BenchmarkError> { match xcm_config::bridging::BridgingBenchmarksHelper::prepare_universal_alias() { Some(alias) => Ok(alias), None => Err(BenchmarkError::Skip) } } - fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> { + fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> { Ok((WestendLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) } - fn subscribe_origin() -> Result { + fn subscribe_origin() -> Result { Ok(WestendLocation::get()) } - fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { + fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> { let origin = WestendLocation::get(); - let assets: MultiAssets = (Concrete(WestendLocation::get()), 1_000 * UNITS).into(); - let ticket = MultiLocation { parents: 0, interior: Here }; + let assets: Assets = (AssetId(WestendLocation::get()), 1_000 * UNITS).into(); + let ticket = Location { parents: 0, interior: Here }; Ok((origin, ticket, assets)) } - fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { + fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> { Err(BenchmarkError::Skip) } fn export_message_origin_and_destination( - ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { + ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> { Err(BenchmarkError::Skip) } - fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { + fn alias_origin() -> Result<(Location, Location), BenchmarkError> { Err(BenchmarkError::Skip) } } @@ -1585,15 +1583,11 @@ pub mod migrations { use sp_runtime::{traits::StaticLookup, Saturating}; /// Temporary migration because of bug with native asset, it can be removed once applied on - /// `AssetHubWestend`. Migrates pools with `MultiLocation { parents: 0, interior: Here }` to - /// `MultiLocation { parents: 1, interior: Here }` + /// `AssetHubWestend`. Migrates pools with `Location { parents: 0, interior: Here }` to + /// `Location { parents: 1, interior: Here }` pub struct NativeAssetParents0ToParents1Migration(sp_std::marker::PhantomData); - impl< - T: pallet_asset_conversion::Config< - MultiAssetId = Box, - AssetId = MultiLocation, - >, - > OnRuntimeUpgrade for NativeAssetParents0ToParents1Migration + impl, AssetId = Location>> + OnRuntimeUpgrade for NativeAssetParents0ToParents1Migration where ::PoolAssetId: Into, AccountIdOf: Into<[u8; 32]>, @@ -1604,7 +1598,7 @@ pub mod migrations { sp_runtime::AccountId32: From<::AccountId>, { fn on_runtime_upgrade() -> Weight { - let invalid_native_asset = MultiLocation { parents: 0, interior: Here }; + let invalid_native_asset = Location { parents: 0, interior: Here }; let valid_native_asset = WestendLocation::get(); let mut reads: u64 = 1; @@ -1625,7 +1619,7 @@ pub mod migrations { // fix new account let new_pool_id = pallet_asset_conversion::Pallet::::get_pool_id( - Box::new(valid_native_asset), + Box::new(valid_native_asset.clone()), old_pool_id.1.clone(), ); let new_pool_account = @@ -1665,10 +1659,10 @@ pub mod migrations { // move LocalOrForeignAssets let _ = T::Assets::transfer( - *old_pool_id.1.as_ref(), + *old_pool_id.1.clone(), &old_pool_account, &new_pool_account, - T::Assets::balance(*old_pool_id.1.as_ref(), &old_pool_account), + T::Assets::balance(*old_pool_id.1.clone(), &old_pool_account), Preservation::Expendable, ); reads.saturating_accrue(1); diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs index bcd51167f97e..8c77774da2dd 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs @@ -23,14 +23,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; -trait WeighMultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight; +trait WeighAssets { + fn weigh_assets(&self, weight: Weight) -> Weight; } const MAX_ASSETS: u64 = 100; -impl WeighMultiAssets for MultiAssetFilter { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for AssetFilter { + fn weigh_assets(&self, weight: Weight) -> Weight { match self { Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64), Self::Wild(asset) => match asset { @@ -49,40 +49,36 @@ impl WeighMultiAssets for MultiAssetFilter { } } -impl WeighMultiAssets for MultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for Assets { + fn weigh_assets(&self, weight: Weight) -> Weight { weight.saturating_mul(self.inner().iter().count() as u64) } } pub struct AssetHubWestendXcmWeight(core::marker::PhantomData); impl XcmWeightInfo for AssetHubWestendXcmWeight { - fn withdraw_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::withdraw_asset()) + fn withdraw_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::withdraw_asset()) } - fn reserve_asset_deposited(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::reserve_asset_deposited()) + fn reserve_asset_deposited(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::reserve_asset_deposited()) } - fn receive_teleported_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::receive_teleported_asset()) + fn receive_teleported_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::receive_teleported_asset()) } fn query_response( _query_id: &u64, _response: &Response, _max_weight: &Weight, - _querier: &Option, + _querier: &Option, ) -> Weight { XcmGeneric::::query_response() } - fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_asset()) + fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::transfer_asset()) } - fn transfer_reserve_asset( - assets: &MultiAssets, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_reserve_asset()) + fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } fn transact( _origin_type: &OriginKind, @@ -110,44 +106,36 @@ impl XcmWeightInfo for AssetHubWestendXcmWeight { fn clear_origin() -> Weight { XcmGeneric::::clear_origin() } - fn descend_origin(_who: &InteriorMultiLocation) -> Weight { + fn descend_origin(_who: &InteriorLocation) -> Weight { XcmGeneric::::descend_origin() } fn report_error(_query_response_info: &QueryResponseInfo) -> Weight { XcmGeneric::::report_error() } - fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_asset()) + fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::deposit_asset()) } - fn deposit_reserve_asset( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_reserve_asset()) + fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::deposit_reserve_asset()) } - fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight { + fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight { Weight::MAX } fn initiate_reserve_withdraw( - assets: &MultiAssetFilter, - _reserve: &MultiLocation, + assets: &AssetFilter, + _reserve: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) + assets.weigh_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) } - fn initiate_teleport( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_teleport()) + fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } - fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight { + fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } - fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight { + fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } fn refund_surplus() -> Weight { @@ -162,7 +150,7 @@ impl XcmWeightInfo for AssetHubWestendXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } - fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight { + fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } fn trap(_code: &u64) -> Weight { @@ -174,13 +162,13 @@ impl XcmWeightInfo for AssetHubWestendXcmWeight { fn unsubscribe_version() -> Weight { XcmGeneric::::unsubscribe_version() } - fn burn_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + fn burn_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::burn_asset()) } - fn expect_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + fn expect_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::expect_asset()) } - fn expect_origin(_origin: &Option) -> Weight { + fn expect_origin(_origin: &Option) -> Weight { XcmGeneric::::expect_origin() } fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { @@ -213,16 +201,16 @@ impl XcmWeightInfo for AssetHubWestendXcmWeight { fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight { Weight::MAX } - fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn lock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn unlock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn note_unlockable(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn request_unlock(_: &Asset, _: &Location) -> Weight { Weight::MAX } fn set_fees_mode(_: &bool) -> Weight { @@ -234,11 +222,11 @@ impl XcmWeightInfo for AssetHubWestendXcmWeight { fn clear_topic() -> Weight { XcmGeneric::::clear_topic() } - fn alias_origin(_: &MultiLocation) -> Weight { + fn alias_origin(_: &Location) -> Weight { // XCM Executor does not currently support alias origin operations Weight::MAX } - fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { + fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs index 17312c0f46ef..4ac91a71a55a 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs @@ -20,11 +20,11 @@ use super::{ TransactionByteFee, TrustBackedAssetsInstance, WeightToFee, XcmpQueue, }; use assets_common::{ - local_and_foreign_assets::MatchesLocalAndForeignAssetsMultiLocation, + local_and_foreign_assets::MatchesLocalAndForeignAssetsLocation, matching::{FromSiblingParachain, IsForeignConcreteAsset}, }; use frame_support::{ - match_types, parameter_types, + parameter_types, traits::{ConstU32, Contains, Equals, Everything, Nothing, PalletInfoAccess}, }; use frame_system::EnsureRoot; @@ -60,24 +60,24 @@ use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; use {cumulus_primitives_core::ParaId, sp_core::Get}; parameter_types! { - pub const WestendLocation: MultiLocation = MultiLocation::parent(); + pub const WestendLocation: Location = Location::parent(); pub const RelayNetwork: Option = Some(NetworkId::Westend); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = - X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocation: InteriorLocation = + [GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into(); pub UniversalLocationNetworkId: NetworkId = UniversalLocation::get().global_consensus().unwrap(); - pub TrustBackedAssetsPalletLocation: MultiLocation = + pub TrustBackedAssetsPalletLocation: Location = PalletInstance(::index() as u8).into(); - pub ForeignAssetsPalletLocation: MultiLocation = + pub ForeignAssetsPalletLocation: Location = PalletInstance(::index() as u8).into(); - pub PoolAssetsPalletLocation: MultiLocation = + pub PoolAssetsPalletLocation: Location = PalletInstance(::index() as u8).into(); pub CheckingAccount: AccountId = PolkadotXcm::check_account(); pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating(); - pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into(); + pub RelayTreasuryLocation: Location = (Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into(); } -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( @@ -101,7 +101,7 @@ pub type CurrencyTransactor = CurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -119,7 +119,7 @@ pub type FungiblesTransactor = FungiblesAdapter< Assets, // Use this currency when it is a fungible asset matching the given location or name: TrustBackedAssetsConvertedConcreteId, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -136,8 +136,8 @@ pub type ForeignAssetsConvertedConcreteId = assets_common::ForeignAssetsConverte // Ignore `TrustBackedAssets` explicitly StartsWith, // Ignore asset which starts explicitly with our `GlobalConsensus(NetworkId)`, means: - // - foreign assets from our consensus should be: `MultiLocation {parents: 1, - // X*(Parachain(xyz), ..)} + // - foreign assets from our consensus should be: `Location {parents: 1, X*(Parachain(xyz), + // ..)} // - foreign assets outside our consensus with the same `GlobalConsensus(NetworkId)` wont // be accepted here StartsWithExplicitGlobalConsensus, @@ -151,7 +151,7 @@ pub type ForeignFungiblesTransactor = FungiblesAdapter< ForeignAssets, // Use this currency when it is a fungible asset matching the given location or name: ForeignAssetsConvertedConcreteId, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -171,7 +171,7 @@ pub type PoolFungiblesTransactor = FungiblesAdapter< PoolAssets, // Use this currency when it is a fungible asset matching the given location or name: PoolAssetsConvertedConcreteId, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -186,21 +186,21 @@ pub type PoolFungiblesTransactor = FungiblesAdapter< pub type AssetTransactors = (CurrencyTransactor, FungiblesTransactor, ForeignFungiblesTransactor, PoolFungiblesTransactor); -/// Simple `MultiLocation` matcher for Local and Foreign asset `MultiLocation`. -pub struct LocalAndForeignAssetsMultiLocationMatcher; -impl MatchesLocalAndForeignAssetsMultiLocation for LocalAndForeignAssetsMultiLocationMatcher { - fn is_local(location: &MultiLocation) -> bool { - use assets_common::fungible_conversion::MatchesMultiLocation; +/// Simple `Location` matcher for Local and Foreign asset `Location`. +pub struct LocalAndForeignAssetsLocationMatcher; +impl MatchesLocalAndForeignAssetsLocation for LocalAndForeignAssetsLocationMatcher { + fn is_local(location: &Location) -> bool { + use assets_common::fungible_conversion::MatchesLocation; TrustBackedAssetsConvertedConcreteId::contains(location) } - fn is_foreign(location: &MultiLocation) -> bool { - use assets_common::fungible_conversion::MatchesMultiLocation; + fn is_foreign(location: &Location) -> bool { + use assets_common::fungible_conversion::MatchesLocation; ForeignAssetsConvertedConcreteId::contains(location) } } -impl Contains for LocalAndForeignAssetsMultiLocationMatcher { - fn contains(location: &MultiLocation) -> bool { +impl Contains for LocalAndForeignAssetsLocationMatcher { + fn contains(location: &Location) -> bool { Self::is_local(location) || Self::is_foreign(location) } } @@ -235,11 +235,11 @@ parameter_types! { pub XcmAssetFeesReceiver: Option = Authorship::author(); } -match_types! { - pub type ParentOrParentsPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { .. }) } - }; +pub struct ParentOrParentsPlurality; +impl Contains for ParentOrParentsPlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [Plurality { .. }])) + } } /// A call filter for the XCM Transact instruction. This is a temporary measure until we properly @@ -509,6 +509,18 @@ pub type AssetFeeAsExistentialDepositMultiplierFeeCharger = AssetFeeAsExistentia TrustBackedAssetsInstance, >; +pub struct SystemParachains; +impl Contains for SystemParachains { + fn contains(location: &Location) -> bool { + use system_parachain::{ASSET_HUB_ID, COLLECTIVES_ID, BRIDGE_HUB_ID}; + + matches!( + location.unpack(), + (1, [Parachain(ASSET_HUB_ID | COLLECTIVES_ID | BRIDGE_HUB_ID)]) + ) + } +} + /// Multiplier used for dedicated `TakeFirstAssetTrader` with `ForeignAssets` instance. pub type ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger = AssetFeeAsExistentialDepositMultiplier< @@ -518,18 +530,6 @@ pub type ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger = ForeignAssetsInstance, >; -match_types! { - pub type SystemParachains: impl Contains = { - MultiLocation { - parents: 1, - interior: X1(Parachain( - system_parachain::ASSET_HUB_ID | - system_parachain::COLLECTIVES_ID | - system_parachain::BRIDGE_HUB_ID - )), - } - }; -} /// Locations that will not be charged fees in the executor, /// either execution or delivery. @@ -680,36 +680,36 @@ pub type ForeignCreatorsSovereignAccountOf = ( /// Simple conversion of `u32` into an `AssetId` for use in benchmarking. pub struct XcmBenchmarkHelper; #[cfg(feature = "runtime-benchmarks")] -impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { - fn create_asset_id_parameter(id: u32) -> MultiLocation { - MultiLocation { parents: 1, interior: X1(Parachain(id)) } +impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { + fn create_asset_id_parameter(id: u32) -> Location { + Location { parents: 1, interior: [Parachain(id)].into() } } } #[cfg(feature = "runtime-benchmarks")] -pub struct BenchmarkMultiLocationConverter { +pub struct BenchmarkLocationConverter { _phantom: sp_std::marker::PhantomData, } #[cfg(feature = "runtime-benchmarks")] -impl - pallet_asset_conversion::BenchmarkHelper> - for BenchmarkMultiLocationConverter +impl pallet_asset_conversion::BenchmarkHelper> + for BenchmarkLocationConverter where SelfParaId: Get, { - fn asset_id(asset_id: u32) -> MultiLocation { - MultiLocation { + fn asset_id(asset_id: u32) -> Location { + Location { parents: 1, - interior: X3( + interior: [ Parachain(SelfParaId::get().into()), PalletInstance(::index() as u8), GeneralIndex(asset_id.into()), - ), + ] + .into(), } } - fn multiasset_id(asset_id: u32) -> sp_std::boxed::Box { + fn multiasset_id(asset_id: u32) -> sp_std::boxed::Box { sp_std::boxed::Box::new(Self::asset_id(asset_id)) } } @@ -741,7 +741,7 @@ pub mod bridging { pub storage XcmBridgeHubRouterByteFee: Balance = TransactionByteFee::get(); pub SiblingBridgeHubParaId: u32 = bp_bridge_hub_westend::BRIDGE_HUB_WESTEND_PARACHAIN_ID; - pub SiblingBridgeHub: MultiLocation = MultiLocation::new(1, X1(Parachain(SiblingBridgeHubParaId::get()))); + pub SiblingBridgeHub: Location = Location::new(1, [Parachain(SiblingBridgeHubParaId::get())]); /// Router expects payment with this `AssetId`. /// (`AssetId` has to be aligned with `BridgeTable`) pub XcmBridgeHubRouterFeeAssetId: AssetId = WestendLocation::get().into(); @@ -758,25 +758,25 @@ pub mod bridging { use super::*; parameter_types! { - pub SiblingBridgeHubWithBridgeHubRococoInstance: MultiLocation = MultiLocation::new( + pub SiblingBridgeHubWithBridgeHubRococoInstance: Location = Location::new( 1, - X2( + [ Parachain(SiblingBridgeHubParaId::get()), PalletInstance(bp_bridge_hub_westend::WITH_BRIDGE_WESTEND_TO_ROCOCO_MESSAGES_PALLET_INDEX) - ) + ] ); pub const RococoNetwork: NetworkId = NetworkId::Rococo; - pub AssetHubRococo: MultiLocation = MultiLocation::new(2, X2(GlobalConsensus(RococoNetwork::get()), Parachain(bp_asset_hub_rococo::ASSET_HUB_ROCOCO_PARACHAIN_ID))); - pub RocLocation: MultiLocation = MultiLocation::new(2, X1(GlobalConsensus(RococoNetwork::get()))); + pub AssetHubRococo: Location = Location::new(2, [GlobalConsensus(RococoNetwork::get()), Parachain(bp_asset_hub_rococo::ASSET_HUB_ROCOCO_PARACHAIN_ID)]); + pub RocLocation: Location = Location::new(2, [GlobalConsensus(RococoNetwork::get())]); - pub RocFromAssetHubRococo: (MultiAssetFilter, MultiLocation) = ( - Wild(AllOf { fun: WildFungible, id: Concrete(RocLocation::get()) }), + pub RocFromAssetHubRococo: (AssetFilter, Location) = ( + Wild(AllOf { fun: WildFungible, id: AssetId(RocLocation::get()) }), AssetHubRococo::get() ); /// Set up exporters configuration. - /// `Option` represents static "base fee" which is used for total delivery fee calculation. + /// `Option` represents static "base fee" which is used for total delivery fee calculation. pub BridgeTable: sp_std::vec::Vec = sp_std::vec![ NetworkExportTableItem::new( RococoNetwork::get(), @@ -793,15 +793,15 @@ pub mod bridging { ]; /// Universal aliases - pub UniversalAliases: BTreeSet<(MultiLocation, Junction)> = BTreeSet::from_iter( + pub UniversalAliases: BTreeSet<(Location, Junction)> = BTreeSet::from_iter( sp_std::vec![ (SiblingBridgeHubWithBridgeHubRococoInstance::get(), GlobalConsensus(RococoNetwork::get())) ] ); } - impl Contains<(MultiLocation, Junction)> for UniversalAliases { - fn contains(alias: &(MultiLocation, Junction)) -> bool { + impl Contains<(Location, Junction)> for UniversalAliases { + fn contains(alias: &(Location, Junction)) -> bool { UniversalAliases::get().contains(alias) } } @@ -836,7 +836,7 @@ pub mod bridging { #[cfg(feature = "runtime-benchmarks")] impl BridgingBenchmarksHelper { - pub fn prepare_universal_alias() -> Option<(MultiLocation, Junction)> { + pub fn prepare_universal_alias() -> Option<(Location, Junction)> { let alias = to_rococo::UniversalAliases::get().into_iter().find_map(|(location, junction)| { match to_rococo::SiblingBridgeHubWithBridgeHubRococoInstance::get() diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs index 7922b04e8077..c643b06e3128 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs @@ -43,8 +43,12 @@ use parachains_common::{ }; use sp_runtime::traits::MaybeEquivalence; use std::convert::Into; -use xcm::latest::prelude::*; -use xcm_executor::traits::{Identity, JustTry, WeightTrader}; +use xcm::{ + latest::prelude::{Assets as XcmAssets, *}, +}; +use xcm_executor::{ + traits::{Identity, JustTry, WeightTrader}, +}; const ALICE: [u8; 32] = [1u8; 32]; const SOME_ASSET_ADMIN: [u8; 32] = [5u8; 32]; @@ -96,8 +100,8 @@ fn test_asset_xcm_trader() { minimum_asset_balance )); - // get asset id as multilocation - let asset_multilocation = + // get asset id as location + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&local_asset_id).unwrap(); // Set Alice as block author, who will receive fees @@ -116,8 +120,8 @@ fn test_asset_xcm_trader() { // Lets pay with: asset_amount_needed + asset_amount_extra let asset_amount_extra = 100_u128; - let asset: MultiAsset = - (asset_multilocation, asset_amount_needed + asset_amount_extra).into(); + let asset: Asset = + (asset_location.clone(), asset_amount_needed + asset_amount_extra).into(); let mut trader = ::Trader::new(); let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; @@ -126,7 +130,7 @@ fn test_asset_xcm_trader() { let unused_assets = trader.buy_weight(bought, asset.into(), &ctx).expect("Expected Ok"); // Check whether a correct amount of unused assets is returned assert_ok!( - unused_assets.ensure_contains(&(asset_multilocation, asset_amount_extra).into()) + unused_assets.ensure_contains(&(asset_location, asset_amount_extra).into()) ); // Drop trader @@ -183,12 +187,12 @@ fn test_asset_xcm_trader_with_refund() { // We are going to buy 4e9 weight let bought = Weight::from_parts(4_000_000_000u64, 0); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); // lets calculate amount needed let amount_bought = WeightToFee::weight_to_fee(&bought); - let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + let asset: Asset = (asset_location.clone(), amount_bought).into(); // Make sure buy_weight does not return an error assert_ok!(trader.buy_weight(bought, asset.clone().into(), &ctx)); @@ -206,7 +210,7 @@ fn test_asset_xcm_trader_with_refund() { assert_eq!( trader.refund_weight(bought - weight_used, &ctx), - Some((asset_multilocation, amount_refunded).into()) + Some((asset_location, amount_refunded).into()) ); // Drop trader @@ -255,7 +259,7 @@ fn test_asset_xcm_trader_refund_not_possible_since_amount_less_than_ed() { // We are going to buy small amount let bought = Weight::from_parts(500_000_000u64, 0); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); let amount_bought = WeightToFee::weight_to_fee(&bought); @@ -264,7 +268,7 @@ fn test_asset_xcm_trader_refund_not_possible_since_amount_less_than_ed() { "we are testing what happens when the amount does not exceed ED" ); - let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + let asset: Asset = (asset_location, amount_bought).into(); // Buy weight should return an error assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); @@ -306,7 +310,7 @@ fn test_that_buying_ed_refund_does_not_refund() { let bought = Weight::from_parts(500_000_000u64, 0); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); let amount_bought = WeightToFee::weight_to_fee(&bought); @@ -317,11 +321,11 @@ fn test_that_buying_ed_refund_does_not_refund() { // We know we will have to buy at least ED, so lets make sure first it will // fail with a payment of less than ED - let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + let asset: Asset = (asset_location.clone(), amount_bought).into(); assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); // Now lets buy ED at least - let asset: MultiAsset = (asset_multilocation, ExistentialDeposit::get()).into(); + let asset: Asset = (asset_location, ExistentialDeposit::get()).into(); // Buy weight should work assert_ok!(trader.buy_weight(bought, asset.into(), &ctx)); @@ -382,9 +386,9 @@ fn test_asset_xcm_trader_not_possible_for_non_sufficient_assets() { // lets calculate amount needed let asset_amount_needed = WeightToFee::weight_to_fee(&bought); - let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); - let asset: MultiAsset = (asset_multilocation, asset_amount_needed).into(); + let asset: Asset = (asset_location, asset_amount_needed).into(); // Make sure again buy_weight does return an error assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); @@ -414,19 +418,22 @@ fn test_assets_balances_api_works() { .build() .execute_with(|| { let local_asset_id = 1; - let foreign_asset_id_multilocation = - MultiLocation { parents: 1, interior: X2(Parachain(1234), GeneralIndex(12345)) }; + let foreign_asset_id_location = + Location { parents: 1, interior: [Parachain(1234), GeneralIndex(12345)].into() }; // check before assert_eq!(Assets::balance(local_asset_id, AccountId::from(ALICE)), 0); assert_eq!( - ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)), + ForeignAssets::balance( + foreign_asset_id_location.clone(), + AccountId::from(ALICE) + ), 0 ); assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 0); assert!(Runtime::query_account_balances(AccountId::from(ALICE)) .unwrap() - .try_as::() + .try_as::() .unwrap() .is_none()); @@ -457,7 +464,7 @@ fn test_assets_balances_api_works() { let foreign_asset_minimum_asset_balance = 3333333_u128; assert_ok!(ForeignAssets::force_create( RuntimeHelper::root_origin(), - foreign_asset_id_multilocation, + foreign_asset_id_location.clone(), AccountId::from(SOME_ASSET_ADMIN).into(), false, foreign_asset_minimum_asset_balance @@ -466,7 +473,7 @@ fn test_assets_balances_api_works() { // We first mint enough asset for the account to exist for assets assert_ok!(ForeignAssets::mint( RuntimeHelper::origin_of(AccountId::from(SOME_ASSET_ADMIN)), - foreign_asset_id_multilocation, + foreign_asset_id_location.clone(), AccountId::from(ALICE).into(), 6 * foreign_asset_minimum_asset_balance )); @@ -477,12 +484,15 @@ fn test_assets_balances_api_works() { minimum_asset_balance ); assert_eq!( - ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)), + ForeignAssets::balance( + foreign_asset_id_location.clone(), + AccountId::from(ALICE) + ), 6 * minimum_asset_balance ); assert_eq!(Balances::free_balance(AccountId::from(ALICE)), some_currency); - let result: MultiAssets = Runtime::query_account_balances(AccountId::from(ALICE)) + let result: XcmAssets = Runtime::query_account_balances(AccountId::from(ALICE)) .unwrap() .try_into() .unwrap(); @@ -503,7 +513,7 @@ fn test_assets_balances_api_works() { .into()))); // check foreign asset assert!(result.inner().iter().any(|asset| asset.eq(&( - Identity::convert_back(&foreign_asset_id_multilocation).unwrap(), + Identity::convert_back(&foreign_asset_id_location).unwrap(), 6 * foreign_asset_minimum_asset_balance ) .into()))); @@ -591,11 +601,11 @@ asset_test_utils::include_asset_transactor_transfer_with_pallet_assets_instance_ Runtime, XcmConfig, ForeignAssetsInstance, - MultiLocation, + Location, JustTry, collator_session_keys(), ExistentialDeposit::get(), - MultiLocation { parents: 1, interior: X2(Parachain(1313), GeneralIndex(12345)) }, + Location { parents: 1, interior: [Parachain(1313), GeneralIndex(12345)].into() }, Box::new(|| { assert!(Assets::asset_ids().collect::>().is_empty()); }), @@ -610,7 +620,7 @@ asset_test_utils::include_create_and_manage_foreign_assets_for_local_consensus_p WeightToFee, ForeignCreatorsSovereignAccountOf, ForeignAssetsInstance, - MultiLocation, + Location, JustTry, collator_session_keys(), ExistentialDeposit::get(), @@ -689,12 +699,12 @@ fn receive_reserve_asset_deposited_roc_from_asset_hub_rococo_works() { AccountId::from([73; 32]), AccountId::from(BLOCK_AUTHOR_ACCOUNT), // receiving ROCs - (MultiLocation { parents: 2, interior: X1(GlobalConsensus(Rococo)) }, 1000000000000, 1_000_000_000), + (Location::new(2, [GlobalConsensus(Rococo)]), 1000000000000, 1_000_000_000), bridging_to_asset_hub_rococo, ( - X1(PalletInstance(bp_bridge_hub_westend::WITH_BRIDGE_WESTEND_TO_ROCOCO_MESSAGES_PALLET_INDEX)), + [PalletInstance(bp_bridge_hub_westend::WITH_BRIDGE_WESTEND_TO_ROCOCO_MESSAGES_PALLET_INDEX)].into(), GlobalConsensus(Rococo), - X1(Parachain(1000)) + [Parachain(1000)].into() ) ) } diff --git a/cumulus/parachains/runtimes/assets/common/src/foreign_creators.rs b/cumulus/parachains/runtimes/assets/common/src/foreign_creators.rs index 1ed7bd0538c2..934cbd631e3e 100644 --- a/cumulus/parachains/runtimes/assets/common/src/foreign_creators.rs +++ b/cumulus/parachains/runtimes/assets/common/src/foreign_creators.rs @@ -17,7 +17,7 @@ use frame_support::traits::{ ContainsPair, EnsureOrigin, EnsureOriginWithArg, Everything, OriginTrait, }; use pallet_xcm::{EnsureXcm, Origin as XcmOrigin}; -use xcm::latest::MultiLocation; +use xcm::latest::Location; use xcm_executor::traits::ConvertLocation; /// `EnsureOriginWithArg` impl for `CreateOrigin` that allows only XCM origins that are locations @@ -26,12 +26,11 @@ pub struct ForeignCreators( sp_std::marker::PhantomData<(IsForeign, AccountOf, AccountId)>, ); impl< - IsForeign: ContainsPair, + IsForeign: ContainsPair, AccountOf: ConvertLocation, AccountId: Clone, RuntimeOrigin: From + OriginTrait + Clone, - > EnsureOriginWithArg - for ForeignCreators + > EnsureOriginWithArg for ForeignCreators where RuntimeOrigin::PalletsOrigin: From + TryInto, @@ -40,7 +39,7 @@ where fn try_origin( origin: RuntimeOrigin, - asset_location: &MultiLocation, + asset_location: &Location, ) -> sp_std::result::Result { let origin_location = EnsureXcm::::try_origin(origin.clone())?; if !IsForeign::contains(asset_location, &origin_location) { @@ -50,7 +49,7 @@ where } #[cfg(feature = "runtime-benchmarks")] - fn try_successful_origin(a: &MultiLocation) -> Result { - Ok(pallet_xcm::Origin::Xcm(*a).into()) + fn try_successful_origin(a: &Location) -> Result { + Ok(pallet_xcm::Origin::Xcm(a.clone()).into()) } } diff --git a/cumulus/parachains/runtimes/assets/common/src/fungible_conversion.rs b/cumulus/parachains/runtimes/assets/common/src/fungible_conversion.rs index 80f8a971d217..e21203485a76 100644 --- a/cumulus/parachains/runtimes/assets/common/src/fungible_conversion.rs +++ b/cumulus/parachains/runtimes/assets/common/src/fungible_conversion.rs @@ -19,52 +19,48 @@ use crate::runtime_api::FungiblesAccessError; use frame_support::traits::Contains; use sp_runtime::traits::MaybeEquivalence; use sp_std::{borrow::Borrow, vec::Vec}; -use xcm::latest::{MultiAsset, MultiLocation}; +use xcm::latest::{Asset, Location}; use xcm_builder::{ConvertedConcreteId, MatchedConvertedConcreteId}; use xcm_executor::traits::MatchesFungibles; -/// Converting any [`(AssetId, Balance)`] to [`MultiAsset`] -pub trait MultiAssetConverter: +/// Converting any [`(AssetId, Balance)`] to [`Asset`] +pub trait AssetConverter: MatchesFungibles where AssetId: Clone, Balance: Clone, - ConvertAssetId: MaybeEquivalence, + ConvertAssetId: MaybeEquivalence, ConvertBalance: MaybeEquivalence, { - fn convert_ref( - value: impl Borrow<(AssetId, Balance)>, - ) -> Result; + fn convert_ref(value: impl Borrow<(AssetId, Balance)>) -> Result; } -/// Checks for `MultiLocation`. -pub trait MatchesMultiLocation: +/// Checks for `Location`. +pub trait MatchesLocation: MatchesFungibles where AssetId: Clone, Balance: Clone, - MatchAssetId: Contains, - ConvertAssetId: MaybeEquivalence, + MatchAssetId: Contains, + ConvertAssetId: MaybeEquivalence, ConvertBalance: MaybeEquivalence, { - fn contains(location: &MultiLocation) -> bool; + fn contains(location: &Location) -> bool; } impl< AssetId: Clone, Balance: Clone, - ConvertAssetId: MaybeEquivalence, + ConvertAssetId: MaybeEquivalence, ConvertBalance: MaybeEquivalence, - > MultiAssetConverter + > AssetConverter for ConvertedConcreteId { - fn convert_ref( - value: impl Borrow<(AssetId, Balance)>, - ) -> Result { + fn convert_ref(value: impl Borrow<(AssetId, Balance)>) -> Result { let (asset_id, balance) = value.borrow(); match ConvertAssetId::convert_back(asset_id) { - Some(asset_id_as_multilocation) => match ConvertBalance::convert_back(balance) { - Some(amount) => Ok((asset_id_as_multilocation, amount).into()), + Some(asset_id_as_location) => match ConvertBalance::convert_back(balance) { + Some(amount) => Ok((asset_id_as_location, amount).into()), None => Err(FungiblesAccessError::AmountToBalanceConversionFailed), }, None => Err(FungiblesAccessError::AssetIdConversionFailed), @@ -75,19 +71,17 @@ impl< impl< AssetId: Clone, Balance: Clone, - MatchAssetId: Contains, - ConvertAssetId: MaybeEquivalence, + MatchAssetId: Contains, + ConvertAssetId: MaybeEquivalence, ConvertBalance: MaybeEquivalence, - > MultiAssetConverter + > AssetConverter for MatchedConvertedConcreteId { - fn convert_ref( - value: impl Borrow<(AssetId, Balance)>, - ) -> Result { + fn convert_ref(value: impl Borrow<(AssetId, Balance)>) -> Result { let (asset_id, balance) = value.borrow(); match ConvertAssetId::convert_back(asset_id) { - Some(asset_id_as_multilocation) => match ConvertBalance::convert_back(balance) { - Some(amount) => Ok((asset_id_as_multilocation, amount).into()), + Some(asset_id_as_location) => match ConvertBalance::convert_back(balance) { + Some(amount) => Ok((asset_id_as_location, amount).into()), None => Err(FungiblesAccessError::AmountToBalanceConversionFailed), }, None => Err(FungiblesAccessError::AssetIdConversionFailed), @@ -98,13 +92,13 @@ impl< impl< AssetId: Clone, Balance: Clone, - MatchAssetId: Contains, - ConvertAssetId: MaybeEquivalence, + MatchAssetId: Contains, + ConvertAssetId: MaybeEquivalence, ConvertBalance: MaybeEquivalence, - > MatchesMultiLocation + > MatchesLocation for MatchedConvertedConcreteId { - fn contains(location: &MultiLocation) -> bool { + fn contains(location: &Location) -> bool { MatchAssetId::contains(location) } } @@ -113,12 +107,12 @@ impl< impl< AssetId: Clone, Balance: Clone, - MatchAssetId: Contains, - ConvertAssetId: MaybeEquivalence, + MatchAssetId: Contains, + ConvertAssetId: MaybeEquivalence, ConvertBalance: MaybeEquivalence, - > MatchesMultiLocation for Tuple + > MatchesLocation for Tuple { - fn contains(location: &MultiLocation) -> bool { + fn contains(location: &Location) -> bool { for_tuples!( #( match Tuple::contains(location) { o @ true => return o, _ => () } )* ); @@ -127,27 +121,24 @@ impl< } } -/// Helper function to convert collections with [`(AssetId, Balance)`] to [`MultiAsset`] +/// Helper function to convert collections with [`(AssetId, Balance)`] to [`Asset`] pub fn convert<'a, AssetId, Balance, ConvertAssetId, ConvertBalance, Converter>( items: impl Iterator, -) -> Result, FungiblesAccessError> +) -> Result, FungiblesAccessError> where AssetId: Clone + 'a, Balance: Clone + 'a, - ConvertAssetId: MaybeEquivalence, + ConvertAssetId: MaybeEquivalence, ConvertBalance: MaybeEquivalence, - Converter: MultiAssetConverter, + Converter: AssetConverter, { items.map(Converter::convert_ref).collect() } -/// Helper function to convert `Balance` with MultiLocation` to `MultiAsset` -pub fn convert_balance< - T: frame_support::pallet_prelude::Get, - Balance: TryInto, ->( +/// Helper function to convert `Balance` with Location` to `Asset` +pub fn convert_balance, Balance: TryInto>( balance: Balance, -) -> Result { +) -> Result { match balance.try_into() { Ok(balance) => Ok((T::get(), balance).into()), Err(_) => Err(FungiblesAccessError::AmountToBalanceConversionFailed), @@ -162,20 +153,20 @@ mod tests { use xcm::latest::prelude::*; use xcm_executor::traits::{Identity, JustTry}; - type Converter = MatchedConvertedConcreteId; + type Converter = MatchedConvertedConcreteId; #[test] fn converted_concrete_id_fungible_multi_asset_conversion_roundtrip_works() { - let location = MultiLocation::new(0, X1(GlobalConsensus(ByGenesis([0; 32])))); + let location = Location::new(0, [GlobalConsensus(ByGenesis([0; 32]))]); let amount = 123456_u64; - let expected_multi_asset = MultiAsset { - id: Concrete(MultiLocation::new(0, X1(GlobalConsensus(ByGenesis([0; 32]))))), + let expected_multi_asset = Asset { + id: AssetId(Location::new(0, [GlobalConsensus(ByGenesis([0; 32]))])), fun: Fungible(123456_u128), }; assert_eq!( Converter::matches_fungibles(&expected_multi_asset).map_err(|_| ()), - Ok((location, amount)) + Ok((location.clone(), amount)) ); assert_eq!(Converter::convert_ref((location, amount)), Ok(expected_multi_asset)); @@ -184,17 +175,17 @@ mod tests { #[test] fn converted_concrete_id_fungible_multi_asset_conversion_collection_works() { let data = vec![ - (MultiLocation::new(0, X1(GlobalConsensus(ByGenesis([0; 32])))), 123456_u64), - (MultiLocation::new(1, X1(GlobalConsensus(ByGenesis([1; 32])))), 654321_u64), + (Location::new(0, [GlobalConsensus(ByGenesis([0; 32]))]), 123456_u64), + (Location::new(1, [GlobalConsensus(ByGenesis([1; 32]))]), 654321_u64), ]; let expected_data = vec![ - MultiAsset { - id: Concrete(MultiLocation::new(0, X1(GlobalConsensus(ByGenesis([0; 32]))))), + Asset { + id: AssetId(Location::new(0, [GlobalConsensus(ByGenesis([0; 32]))])), fun: Fungible(123456_u128), }, - MultiAsset { - id: Concrete(MultiLocation::new(1, X1(GlobalConsensus(ByGenesis([1; 32]))))), + Asset { + id: AssetId(Location::new(1, [GlobalConsensus(ByGenesis([1; 32]))])), fun: Fungible(654321_u128), }, ]; diff --git a/cumulus/parachains/runtimes/assets/common/src/lib.rs b/cumulus/parachains/runtimes/assets/common/src/lib.rs index f45c3289aab4..a37b11cbdd46 100644 --- a/cumulus/parachains/runtimes/assets/common/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/common/src/lib.rs @@ -21,14 +21,14 @@ pub mod local_and_foreign_assets; pub mod matching; pub mod runtime_api; -use crate::matching::{LocalMultiLocationPattern, ParentLocation}; +use crate::matching::{LocalLocationPattern, ParentLocation}; use frame_support::traits::{Equals, EverythingBut}; use parachains_common::AssetIdForTrustBackedAssets; -use xcm::prelude::MultiLocation; +use xcm::prelude::Location; use xcm_builder::{AsPrefixedGeneralIndex, MatchedConvertedConcreteId, StartsWith}; use xcm_executor::traits::{Identity, JustTry}; -/// `MultiLocation` vs `AssetIdForTrustBackedAssets` converter for `TrustBackedAssets` +/// `Location` vs `AssetIdForTrustBackedAssets` converter for `TrustBackedAssets` pub type AssetIdForTrustBackedAssetsConvert = AsPrefixedGeneralIndex; @@ -42,45 +42,39 @@ pub type TrustBackedAssetsConvertedConcreteId; -/// AssetId used for identifying assets by MultiLocation. -pub type MultiLocationForAssetId = MultiLocation; +/// AssetId used for identifying assets by Location. +pub type LocationForAssetId = Location; -/// [`MatchedConvertedConcreteId`] converter dedicated for storing `AssetId` as `MultiLocation`. -pub type MultiLocationConvertedConcreteId = - MatchedConvertedConcreteId< - MultiLocationForAssetId, - Balance, - MultiLocationFilter, - Identity, - JustTry, - >; +/// [`MatchedConvertedConcreteId`] converter dedicated for storing `AssetId` as `Location`. +pub type LocationConvertedConcreteId = + MatchedConvertedConcreteId; /// [`MatchedConvertedConcreteId`] converter dedicated for storing `ForeignAssets` with `AssetId` as -/// `MultiLocation`. +/// `Location`. /// /// Excludes by default: /// - parent as relay chain -/// - all local MultiLocations +/// - all local Locations /// -/// `AdditionalMultiLocationExclusionFilter` can customize additional excluded MultiLocations -pub type ForeignAssetsConvertedConcreteId = - MultiLocationConvertedConcreteId< +/// `AdditionalLocationExclusionFilter` can customize additional excluded Locations +pub type ForeignAssetsConvertedConcreteId = + LocationConvertedConcreteId< EverythingBut<( // Excludes relay/parent chain currency Equals, // Here we rely on fact that something like this works: - // assert!(MultiLocation::new(1, - // X1(Parachain(100))).starts_with(&MultiLocation::parent())); - // assert!(X1(Parachain(100)).starts_with(&Here)); - StartsWith, + // assert!(Location::new(1, + // [Parachain(100)]).starts_with(&Location::parent())); + // assert!([Parachain(100)].into().starts_with(&Here)); + StartsWith, // Here we can exclude more stuff or leave it as `()` - AdditionalMultiLocationExclusionFilter, + AdditionalLocationExclusionFilter, )>, Balance, >; type AssetIdForPoolAssets = u32; -/// `MultiLocation` vs `AssetIdForPoolAssets` converter for `PoolAssets`. +/// `Location` vs `AssetIdForPoolAssets` converter for `PoolAssets`. pub type AssetIdForPoolAssetsConvert = AsPrefixedGeneralIndex; /// [`MatchedConvertedConcreteId`] converter dedicated for `PoolAssets` @@ -104,11 +98,11 @@ mod tests { #[test] fn asset_id_for_trust_backed_assets_convert_works() { frame_support::parameter_types! { - pub TrustBackedAssetsPalletLocation: MultiLocation = MultiLocation::new(5, X1(PalletInstance(13))); + pub TrustBackedAssetsPalletLocation: Location = Location::new(5, [PalletInstance(13)]); } let local_asset_id = 123456789 as AssetIdForTrustBackedAssets; let expected_reverse_ref = - MultiLocation::new(5, X2(PalletInstance(13), GeneralIndex(local_asset_id.into()))); + Location::new(5, [PalletInstance(13), GeneralIndex(local_asset_id.into())]); assert_eq!( AssetIdForTrustBackedAssetsConvert::::convert_back( @@ -129,7 +123,7 @@ mod tests { #[test] fn trust_backed_assets_match_fungibles_works() { frame_support::parameter_types! { - pub TrustBackedAssetsPalletLocation: MultiLocation = MultiLocation::new(0, X1(PalletInstance(13))); + pub TrustBackedAssetsPalletLocation: Location = Location::new(0, [PalletInstance(13)]); } // setup convert type TrustBackedAssetsConvert = @@ -137,85 +131,86 @@ mod tests { let test_data = vec![ // missing GeneralIndex - (ma_1000(0, X1(PalletInstance(13))), Err(MatchError::AssetIdConversionFailed)), + (ma_1000(0, [PalletInstance(13)].into()), Err(MatchError::AssetIdConversionFailed)), ( - ma_1000(0, X2(PalletInstance(13), GeneralKey { data: [0; 32], length: 32 })), + ma_1000(0, [PalletInstance(13), GeneralKey { data: [0; 32], length: 32 }].into()), Err(MatchError::AssetIdConversionFailed), ), ( - ma_1000(0, X2(PalletInstance(13), Parachain(1000))), + ma_1000(0, [PalletInstance(13), Parachain(1000)].into()), Err(MatchError::AssetIdConversionFailed), ), // OK - (ma_1000(0, X2(PalletInstance(13), GeneralIndex(1234))), Ok((1234, 1000))), + (ma_1000(0, [PalletInstance(13), GeneralIndex(1234)].into()), Ok((1234, 1000))), ( - ma_1000(0, X3(PalletInstance(13), GeneralIndex(1234), GeneralIndex(2222))), + ma_1000(0, [PalletInstance(13), GeneralIndex(1234), GeneralIndex(2222)].into()), Ok((1234, 1000)), ), ( ma_1000( 0, - X4( + [ PalletInstance(13), GeneralIndex(1234), GeneralIndex(2222), GeneralKey { data: [0; 32], length: 32 }, - ), + ] + .into(), ), Ok((1234, 1000)), ), // wrong pallet instance ( - ma_1000(0, X2(PalletInstance(77), GeneralIndex(1234))), + ma_1000(0, [PalletInstance(77), GeneralIndex(1234)].into()), Err(MatchError::AssetNotHandled), ), ( - ma_1000(0, X3(PalletInstance(77), GeneralIndex(1234), GeneralIndex(2222))), + ma_1000(0, [PalletInstance(77), GeneralIndex(1234), GeneralIndex(2222)].into()), Err(MatchError::AssetNotHandled), ), // wrong parent ( - ma_1000(1, X2(PalletInstance(13), GeneralIndex(1234))), + ma_1000(1, [PalletInstance(13), GeneralIndex(1234)].into()), Err(MatchError::AssetNotHandled), ), ( - ma_1000(1, X3(PalletInstance(13), GeneralIndex(1234), GeneralIndex(2222))), + ma_1000(1, [PalletInstance(13), GeneralIndex(1234), GeneralIndex(2222)].into()), Err(MatchError::AssetNotHandled), ), ( - ma_1000(1, X2(PalletInstance(77), GeneralIndex(1234))), + ma_1000(1, [PalletInstance(77), GeneralIndex(1234)].into()), Err(MatchError::AssetNotHandled), ), ( - ma_1000(1, X3(PalletInstance(77), GeneralIndex(1234), GeneralIndex(2222))), + ma_1000(1, [PalletInstance(77), GeneralIndex(1234), GeneralIndex(2222)].into()), Err(MatchError::AssetNotHandled), ), // wrong parent ( - ma_1000(2, X2(PalletInstance(13), GeneralIndex(1234))), + ma_1000(2, [PalletInstance(13), GeneralIndex(1234)].into()), Err(MatchError::AssetNotHandled), ), ( - ma_1000(2, X3(PalletInstance(13), GeneralIndex(1234), GeneralIndex(2222))), + ma_1000(2, [PalletInstance(13), GeneralIndex(1234), GeneralIndex(2222)].into()), Err(MatchError::AssetNotHandled), ), // missing GeneralIndex - (ma_1000(0, X1(PalletInstance(77))), Err(MatchError::AssetNotHandled)), - (ma_1000(1, X1(PalletInstance(13))), Err(MatchError::AssetNotHandled)), - (ma_1000(2, X1(PalletInstance(13))), Err(MatchError::AssetNotHandled)), + (ma_1000(0, [PalletInstance(77)].into()), Err(MatchError::AssetNotHandled)), + (ma_1000(1, [PalletInstance(13)].into()), Err(MatchError::AssetNotHandled)), + (ma_1000(2, [PalletInstance(13)].into()), Err(MatchError::AssetNotHandled)), ]; - for (multi_asset, expected_result) in test_data { + for (asset, expected_result) in test_data { assert_eq!( - >::matches_fungibles(&multi_asset), - expected_result, "multi_asset: {:?}", multi_asset); + >::matches_fungibles(&asset), + expected_result, "asset: {:?}", asset); } } #[test] - fn multi_location_converted_concrete_id_converter_works() { + fn location_converted_concrete_id_converter_works() { frame_support::parameter_types! { - pub Parachain100Pattern: MultiLocation = MultiLocation::new(1, X1(Parachain(100))); + pub Parachain100Pattern: Location = Location::new(1, [Parachain(100)]); pub UniversalLocationNetworkId: NetworkId = NetworkId::ByGenesis([9; 32]); } @@ -231,95 +226,97 @@ mod tests { let test_data = vec![ // excluded as local (ma_1000(0, Here), Err(MatchError::AssetNotHandled)), - (ma_1000(0, X1(Parachain(100))), Err(MatchError::AssetNotHandled)), + (ma_1000(0, [Parachain(100)].into()), Err(MatchError::AssetNotHandled)), ( - ma_1000(0, X2(PalletInstance(13), GeneralIndex(1234))), + ma_1000(0, [PalletInstance(13), GeneralIndex(1234)].into()), Err(MatchError::AssetNotHandled), ), // excluded as parent (ma_1000(1, Here), Err(MatchError::AssetNotHandled)), // excluded as additional filter - Parachain100Pattern - (ma_1000(1, X1(Parachain(100))), Err(MatchError::AssetNotHandled)), - (ma_1000(1, X2(Parachain(100), GeneralIndex(1234))), Err(MatchError::AssetNotHandled)), + (ma_1000(1, [Parachain(100)].into()), Err(MatchError::AssetNotHandled)), ( - ma_1000(1, X3(Parachain(100), PalletInstance(13), GeneralIndex(1234))), + ma_1000(1, [Parachain(100), GeneralIndex(1234)].into()), + Err(MatchError::AssetNotHandled), + ), + ( + ma_1000(1, [Parachain(100), PalletInstance(13), GeneralIndex(1234)].into()), Err(MatchError::AssetNotHandled), ), // excluded as additional filter - StartsWithExplicitGlobalConsensus ( - ma_1000(1, X1(GlobalConsensus(NetworkId::ByGenesis([9; 32])))), + ma_1000(1, [GlobalConsensus(NetworkId::ByGenesis([9; 32]))].into()), Err(MatchError::AssetNotHandled), ), ( - ma_1000(2, X1(GlobalConsensus(NetworkId::ByGenesis([9; 32])))), + ma_1000(2, [GlobalConsensus(NetworkId::ByGenesis([9; 32]))].into()), Err(MatchError::AssetNotHandled), ), ( ma_1000( 2, - X3( + [ GlobalConsensus(NetworkId::ByGenesis([9; 32])), Parachain(200), GeneralIndex(1234), - ), + ] + .into(), ), Err(MatchError::AssetNotHandled), ), // ok - (ma_1000(1, X1(Parachain(200))), Ok((MultiLocation::new(1, X1(Parachain(200))), 1000))), - (ma_1000(2, X1(Parachain(200))), Ok((MultiLocation::new(2, X1(Parachain(200))), 1000))), + (ma_1000(1, [Parachain(200)].into()), Ok((Location::new(1, [Parachain(200)]), 1000))), + (ma_1000(2, [Parachain(200)].into()), Ok((Location::new(2, [Parachain(200)]), 1000))), ( - ma_1000(1, X2(Parachain(200), GeneralIndex(1234))), - Ok((MultiLocation::new(1, X2(Parachain(200), GeneralIndex(1234))), 1000)), + ma_1000(1, [Parachain(200), GeneralIndex(1234)].into()), + Ok((Location::new(1, [Parachain(200), GeneralIndex(1234)]), 1000)), ), ( - ma_1000(2, X2(Parachain(200), GeneralIndex(1234))), - Ok((MultiLocation::new(2, X2(Parachain(200), GeneralIndex(1234))), 1000)), + ma_1000(2, [Parachain(200), GeneralIndex(1234)].into()), + Ok((Location::new(2, [Parachain(200), GeneralIndex(1234)]), 1000)), ), ( - ma_1000(2, X1(GlobalConsensus(NetworkId::ByGenesis([7; 32])))), - Ok(( - MultiLocation::new(2, X1(GlobalConsensus(NetworkId::ByGenesis([7; 32])))), - 1000, - )), + ma_1000(2, [GlobalConsensus(NetworkId::ByGenesis([7; 32]))].into()), + Ok((Location::new(2, [GlobalConsensus(NetworkId::ByGenesis([7; 32]))]), 1000)), ), ( ma_1000( 2, - X3( + [ GlobalConsensus(NetworkId::ByGenesis([7; 32])), Parachain(200), GeneralIndex(1234), - ), + ] + .into(), ), Ok(( - MultiLocation::new( + Location::new( 2, - X3( + [ GlobalConsensus(NetworkId::ByGenesis([7; 32])), Parachain(200), GeneralIndex(1234), - ), + ], ), 1000, )), ), ]; - for (multi_asset, expected_result) in test_data { + for (asset, expected_result) in test_data { assert_eq!( - >::matches_fungibles( - &multi_asset + >::matches_fungibles( + &asset ), expected_result, - "multi_asset: {:?}", - multi_asset + "asset: {:?}", + asset ); } } - // Create MultiAsset - fn ma_1000(parents: u8, interior: Junctions) -> MultiAsset { - (MultiLocation::new(parents, interior), 1000).into() + // Create Asset + fn ma_1000(parents: u8, interior: Junctions) -> Asset { + (Location::new(parents, interior), 1000).into() } } diff --git a/cumulus/parachains/runtimes/assets/common/src/local_and_foreign_assets.rs b/cumulus/parachains/runtimes/assets/common/src/local_and_foreign_assets.rs index 9f429016f530..54dbe0a807c6 100644 --- a/cumulus/parachains/runtimes/assets/common/src/local_and_foreign_assets.rs +++ b/cumulus/parachains/runtimes/assets/common/src/local_and_foreign_assets.rs @@ -24,35 +24,34 @@ use pallet_asset_conversion::{MultiAssetIdConversionResult, MultiAssetIdConverte use parachains_common::AccountId; use sp_runtime::{traits::MaybeEquivalence, DispatchError, DispatchResult}; use sp_std::{boxed::Box, marker::PhantomData}; -use xcm::latest::MultiLocation; +use xcm::latest::Location; -pub struct MultiLocationConverter, MultiLocationMatcher> { - _phantom: PhantomData<(NativeAssetLocation, MultiLocationMatcher)>, +pub struct LocationConverter, LocationMatcher> { + _phantom: PhantomData<(NativeAssetLocation, LocationMatcher)>, } -impl - MultiAssetIdConverter, MultiLocation> - for MultiLocationConverter +impl MultiAssetIdConverter, Location> + for LocationConverter where - NativeAssetLocation: Get, - MultiLocationMatcher: Contains, + NativeAssetLocation: Get, + LocationMatcher: Contains, { - fn get_native() -> Box { + fn get_native() -> Box { Box::new(NativeAssetLocation::get()) } - fn is_native(asset_id: &Box) -> bool { + fn is_native(asset_id: &Box) -> bool { *asset_id == Self::get_native() } fn try_convert( - asset_id: &Box, - ) -> MultiAssetIdConversionResult, MultiLocation> { + asset_id: &Box, + ) -> MultiAssetIdConversionResult, Location> { if Self::is_native(&asset_id) { return MultiAssetIdConversionResult::Native } - if MultiLocationMatcher::contains(&asset_id) { + if LocationMatcher::contains(&asset_id) { MultiAssetIdConversionResult::Converted(*asset_id.clone()) } else { MultiAssetIdConversionResult::Unsupported(asset_id.clone()) @@ -60,9 +59,9 @@ where } } -pub trait MatchesLocalAndForeignAssetsMultiLocation { - fn is_local(location: &MultiLocation) -> bool; - fn is_foreign(location: &MultiLocation) -> bool; +pub trait MatchesLocalAndForeignAssetsLocation { + fn is_local(location: &Location) -> bool; + fn is_foreign(location: &Location) -> bool; } pub struct LocalAndForeignAssets { @@ -76,8 +75,8 @@ where + Unbalanced + Balanced + PalletInfoAccess, - LocalAssetIdConverter: MaybeEquivalence, - ForeignAssets: Inspect + LocalAssetIdConverter: MaybeEquivalence, + ForeignAssets: Inspect + Unbalanced + Balanced, { @@ -148,10 +147,10 @@ impl Inspect for LocalAndForeignAssets where Assets: Inspect, - LocalAssetIdConverter: MaybeEquivalence, - ForeignAssets: Inspect, + LocalAssetIdConverter: MaybeEquivalence, + ForeignAssets: Inspect, { - type AssetId = MultiLocation; + type AssetId = Location; type Balance = u128; /// The total amount of issuance in the system. @@ -256,14 +255,14 @@ where + Inspect + Balanced + PalletInfoAccess, - LocalAssetIdConverter: MaybeEquivalence, + LocalAssetIdConverter: MaybeEquivalence, ForeignAssets: Mutate - + Inspect + + Inspect + Balanced, { /// Transfer funds from one account into another. fn transfer( - asset: MultiLocation, + asset: Location, source: &AccountId, dest: &AccountId, amount: Self::Balance, @@ -281,8 +280,8 @@ impl Create for LocalAndForeignAssets where Assets: Create + Inspect, - LocalAssetIdConverter: MaybeEquivalence, - ForeignAssets: Create + Inspect, + LocalAssetIdConverter: MaybeEquivalence, + ForeignAssets: Create + Inspect, { /// Create a new fungible asset. fn create( @@ -299,18 +298,18 @@ where } } -impl AccountTouch +impl AccountTouch for LocalAndForeignAssets where Assets: AccountTouch, - LocalAssetIdConverter: MaybeEquivalence, - ForeignAssets: AccountTouch, + LocalAssetIdConverter: MaybeEquivalence, + ForeignAssets: AccountTouch, { type Balance = u128; fn deposit_required( - asset_id: MultiLocation, - ) -> >::Balance { + asset_id: Location, + ) -> >::Balance { if let Some(asset_id) = LocalAssetIdConverter::convert(&asset_id) { Assets::deposit_required(asset_id) } else { @@ -319,7 +318,7 @@ where } fn touch( - asset_id: MultiLocation, + asset_id: Location, who: AccountId, depositor: AccountId, ) -> Result<(), DispatchError> { @@ -332,15 +331,15 @@ where } /// Implements [`ContainsPair`] trait for a pair of asset and account IDs. -impl ContainsPair +impl ContainsPair for LocalAndForeignAssets where Assets: PalletInfoAccess + ContainsPair, - LocalAssetIdConverter: MaybeEquivalence, - ForeignAssets: ContainsPair, + LocalAssetIdConverter: MaybeEquivalence, + ForeignAssets: ContainsPair, { /// Check if an account with the given asset ID and account address exists. - fn contains(asset_id: &MultiLocation, who: &AccountId) -> bool { + fn contains(asset_id: &Location, who: &AccountId) -> bool { if let Some(asset_id) = LocalAssetIdConverter::convert(asset_id) { Assets::contains(&asset_id, &who) } else { @@ -354,9 +353,8 @@ impl Balanced where Assets: Balanced + Inspect + PalletInfoAccess, - LocalAssetIdConverter: MaybeEquivalence, - ForeignAssets: - Balanced + Inspect, + LocalAssetIdConverter: MaybeEquivalence, + ForeignAssets: Balanced + Inspect, { type OnDropDebt = DebtDropIndirection; type OnDropCredit = CreditDropIndirection; @@ -366,15 +364,14 @@ pub struct DebtDropIndirection { _phantom: PhantomData>, } -impl HandleImbalanceDrop +impl HandleImbalanceDrop for DebtDropIndirection where Assets: Balanced + Inspect, - LocalAssetIdConverter: MaybeEquivalence, - ForeignAssets: - Balanced + Inspect, + LocalAssetIdConverter: MaybeEquivalence, + ForeignAssets: Balanced + Inspect, { - fn handle(asset: MultiLocation, amount: u128) { + fn handle(asset: Location, amount: u128) { if let Some(asset_id) = LocalAssetIdConverter::convert(&asset) { Assets::OnDropDebt::handle(asset_id, amount); } else { @@ -387,15 +384,14 @@ pub struct CreditDropIndirection { _phantom: PhantomData>, } -impl HandleImbalanceDrop +impl HandleImbalanceDrop for CreditDropIndirection where Assets: Balanced + Inspect, - LocalAssetIdConverter: MaybeEquivalence, - ForeignAssets: - Balanced + Inspect, + LocalAssetIdConverter: MaybeEquivalence, + ForeignAssets: Balanced + Inspect, { - fn handle(asset: MultiLocation, amount: u128) { + fn handle(asset: Location, amount: u128) { if let Some(asset_id) = LocalAssetIdConverter::convert(&asset) { Assets::OnDropCredit::handle(asset_id, amount); } else { @@ -407,7 +403,7 @@ where #[cfg(test)] mod tests { use crate::{ - local_and_foreign_assets::MultiLocationConverter, AssetIdForPoolAssetsConvert, + local_and_foreign_assets::LocationConverter, AssetIdForPoolAssetsConvert, AssetIdForTrustBackedAssetsConvert, }; use frame_support::traits::EverythingBut; @@ -417,17 +413,15 @@ mod tests { use xcm_builder::StartsWith; #[test] - fn test_multi_location_converter_works() { + fn test_location_converter_works() { frame_support::parameter_types! { - pub const WestendLocation: MultiLocation = MultiLocation::parent(); - pub TrustBackedAssetsPalletLocation: MultiLocation = PalletInstance(50_u8).into(); - pub PoolAssetsPalletLocation: MultiLocation = PalletInstance(55_u8).into(); + pub const WestendLocation: Location = Location::parent(); + pub TrustBackedAssetsPalletLocation: Location = PalletInstance(50_u8).into(); + pub PoolAssetsPalletLocation: Location = PalletInstance(55_u8).into(); } - type C = MultiLocationConverter< - WestendLocation, - EverythingBut>, - >; + type C = + LocationConverter>>; let native_asset = WestendLocation::get(); let local_asset = @@ -437,33 +431,33 @@ mod tests { .unwrap(); let pool_asset = AssetIdForPoolAssetsConvert::::convert_back(&456).unwrap(); - let foreign_asset1 = MultiLocation { parents: 1, interior: X1(Parachain(2222)) }; - let foreign_asset2 = MultiLocation { + let foreign_asset1 = Location { parents: 1, interior: [Parachain(2222)].into() }; + let foreign_asset2 = Location { parents: 2, - interior: X2(GlobalConsensus(ByGenesis([1; 32])), Parachain(2222)), + interior: [GlobalConsensus(ByGenesis([1; 32])), Parachain(2222)].into(), }; - assert!(C::is_native(&Box::new(native_asset))); - assert!(!C::is_native(&Box::new(local_asset))); - assert!(!C::is_native(&Box::new(pool_asset))); - assert!(!C::is_native(&Box::new(foreign_asset1))); - assert!(!C::is_native(&Box::new(foreign_asset2))); + assert!(C::is_native(&Box::new(native_asset.clone()))); + assert!(!C::is_native(&Box::new(local_asset.clone()))); + assert!(!C::is_native(&Box::new(pool_asset.clone()))); + assert!(!C::is_native(&Box::new(foreign_asset1.clone()))); + assert!(!C::is_native(&Box::new(foreign_asset2.clone()))); assert_eq!(C::try_convert(&Box::new(native_asset)), MultiAssetIdConversionResult::Native); assert_eq!( - C::try_convert(&Box::new(local_asset)), + C::try_convert(&Box::new(local_asset.clone())), MultiAssetIdConversionResult::Converted(local_asset) ); assert_eq!( - C::try_convert(&Box::new(pool_asset)), + C::try_convert(&Box::new(pool_asset.clone())), MultiAssetIdConversionResult::Unsupported(Box::new(pool_asset)) ); assert_eq!( - C::try_convert(&Box::new(foreign_asset1)), + C::try_convert(&Box::new(foreign_asset1.clone())), MultiAssetIdConversionResult::Converted(foreign_asset1) ); assert_eq!( - C::try_convert(&Box::new(foreign_asset2)), + C::try_convert(&Box::new(foreign_asset2.clone())), MultiAssetIdConversionResult::Converted(foreign_asset2) ); } diff --git a/cumulus/parachains/runtimes/assets/common/src/matching.rs b/cumulus/parachains/runtimes/assets/common/src/matching.rs index 914972812521..9a66acc9baf0 100644 --- a/cumulus/parachains/runtimes/assets/common/src/matching.rs +++ b/cumulus/parachains/runtimes/assets/common/src/matching.rs @@ -14,36 +14,54 @@ // limitations under the License. use cumulus_primitives_core::ParaId; -use frame_support::{pallet_prelude::Get, traits::ContainsPair}; -use xcm::{ - latest::prelude::{MultiAsset, MultiLocation}, - prelude::*, -}; +use frame_support::{pallet_prelude::Get, traits::{ContainsPair, Contains}}; +use xcm::prelude::*; + +pub struct StartsWith(sp_std::marker::PhantomData); +impl> Contains for StartsWith { + fn contains(t: &Location) -> bool { + t.starts_with(&LocationValue::get()) + } +} + +pub struct Equals(sp_std::marker::PhantomData); +impl> Contains for Equals { + fn contains(t: &Location) -> bool { + t == &LocationValue::get() + } +} + +pub struct StartsWithExplicitGlobalConsensus(sp_std::marker::PhantomData); +impl> Contains for StartsWithExplicitGlobalConsensus { + fn contains(t: &Location) -> bool { + matches!(t.interior.global_consensus(), Ok(requested_network) if requested_network.eq(&Network::get())) + } +} use xcm_builder::ensure_is_remote; frame_support::parameter_types! { - pub LocalMultiLocationPattern: MultiLocation = MultiLocation::new(0, Here); - pub ParentLocation: MultiLocation = MultiLocation::parent(); + pub LocalLocationPattern: Location = Location::new(0, Here); + pub ParentLocation: Location = Location::parent(); } /// Accepts an asset if it is from the origin. pub struct IsForeignConcreteAsset(sp_std::marker::PhantomData); -impl> ContainsPair +impl> ContainsPair for IsForeignConcreteAsset { - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool { + fn contains(asset: &Asset, origin: &Location) -> bool { log::trace!(target: "xcm::contains", "IsForeignConcreteAsset asset: {:?}, origin: {:?}", asset, origin); - matches!(asset.id, Concrete(ref id) if IsForeign::contains(id, origin)) + matches!(asset.id, AssetId(ref id) if IsForeign::contains(id, origin)) } } -/// Checks if `a` is from sibling location `b`. Checks that `MultiLocation-a` starts with -/// `MultiLocation-b`, and that the `ParaId` of `b` is not equal to `a`. +/// Checks if `a` is from sibling location `b`. Checks that `Location-a` starts with +/// `Location-b`, and that the `ParaId` of `b` is not equal to `a`. pub struct FromSiblingParachain(sp_std::marker::PhantomData); -impl> ContainsPair +impl> ContainsPair for FromSiblingParachain { - fn contains(&a: &MultiLocation, b: &MultiLocation) -> bool { + fn contains(a: &Location, b: &Location) -> bool { // `a` needs to be from `b` at least if !a.starts_with(b) { return false @@ -51,26 +69,26 @@ impl> ContainsPair // here we check if sibling match a { - MultiLocation { parents: 1, interior } => + Location { parents: 1, interior } => matches!(interior.first(), Some(Parachain(sibling_para_id)) if sibling_para_id.ne(&u32::from(SelfParaId::get()))), _ => false, } } } -/// Adapter verifies if it is allowed to receive `MultiAsset` from `MultiLocation`. +/// Adapter verifies if it is allowed to receive `Asset` from `Location`. /// -/// Note: `MultiLocation` has to be from a different global consensus. +/// Note: `Location` has to be from a different global consensus. pub struct IsTrustedBridgedReserveLocationForConcreteAsset( sp_std::marker::PhantomData<(UniversalLocation, Reserves)>, ); impl< - UniversalLocation: Get, - Reserves: ContainsPair, - > ContainsPair + UniversalLocation: Get, + Reserves: ContainsPair, + > ContainsPair for IsTrustedBridgedReserveLocationForConcreteAsset { - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool { + fn contains(asset: &Asset, origin: &Location) -> bool { let universal_source = UniversalLocation::get(); log::trace!( target: "xcm::contains", @@ -79,7 +97,7 @@ impl< ); // check remote origin - let _ = match ensure_is_remote(universal_source, *origin) { + let _ = match ensure_is_remote(universal_source.clone(), origin.clone()) { Ok(devolved) => devolved, Err(_) => { log::trace!( diff --git a/cumulus/parachains/runtimes/assets/common/src/runtime_api.rs b/cumulus/parachains/runtimes/assets/common/src/runtime_api.rs index 0a166a048193..19977cbedab0 100644 --- a/cumulus/parachains/runtimes/assets/common/src/runtime_api.rs +++ b/cumulus/parachains/runtimes/assets/common/src/runtime_api.rs @@ -18,12 +18,12 @@ use codec::{Codec, Decode, Encode}; use sp_runtime::RuntimeDebug; #[cfg(feature = "std")] -use {sp_std::vec::Vec, xcm::latest::MultiAsset}; +use {sp_std::vec::Vec, xcm::latest::Asset}; /// The possible errors that can happen querying the storage of assets. #[derive(Eq, PartialEq, Encode, Decode, RuntimeDebug, scale_info::TypeInfo)] pub enum FungiblesAccessError { - /// `MultiLocation` to `AssetId`/`ClassId` conversion failed. + /// `Location` to `AssetId`/`ClassId` conversion failed. AssetIdConversionFailed, /// `u128` amount to currency `Balance` conversion failed. AmountToBalanceConversionFailed, @@ -36,11 +36,11 @@ sp_api::decl_runtime_apis! { where AccountId: Codec, { - /// Returns the list of all [`MultiAsset`] that an `AccountId` has. + /// Returns the list of all [`Asset`] that an `AccountId` has. #[changed_in(2)] - fn query_account_balances(account: AccountId) -> Result, FungiblesAccessError>; + fn query_account_balances(account: AccountId) -> Result, FungiblesAccessError>; - /// Returns the list of all [`MultiAsset`] that an `AccountId` has. - fn query_account_balances(account: AccountId) -> Result; + /// Returns the list of all [`Asset`] that an `AccountId` has. + fn query_account_balances(account: AccountId) -> Result; } } diff --git a/cumulus/parachains/runtimes/assets/test-utils/src/lib.rs b/cumulus/parachains/runtimes/assets/test-utils/src/lib.rs index 872ad06ddd5b..877d61780ce7 100644 --- a/cumulus/parachains/runtimes/assets/test-utils/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/test-utils/src/lib.rs @@ -28,7 +28,7 @@ use xcm::latest::prelude::*; use xcm_builder::{CreateMatcher, MatchXcm}; /// Given a message, a sender, and a destination, it returns the delivery fees -fn get_fungible_delivery_fees(destination: MultiLocation, message: Xcm<()>) -> u128 { +fn get_fungible_delivery_fees(destination: Location, message: Xcm<()>) -> u128 { let Ok((_, delivery_fees)) = validate_send::(destination, message) else { unreachable!("message can be sent; qed") }; @@ -46,8 +46,8 @@ fn get_fungible_delivery_fees(destination: MultiLocation, message: X /// chain as part of a reserve-asset-transfer. pub(crate) fn assert_matches_reserve_asset_deposited_instructions( xcm: &mut Xcm, - expected_reserve_assets_deposited: &MultiAssets, - expected_beneficiary: &MultiLocation, + expected_reserve_assets_deposited: &Assets, + expected_beneficiary: &Location, ) { let _ = xcm .0 diff --git a/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs b/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs index f1cc76350a00..5c990af09363 100644 --- a/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs +++ b/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs @@ -37,7 +37,7 @@ use sp_runtime::{ traits::{MaybeEquivalence, StaticLookup, Zero}, DispatchError, Saturating, }; -use xcm::{latest::prelude::*, VersionedMultiAssets}; +use xcm::{latest::prelude::*, VersionedAssets}; use xcm_executor::{traits::ConvertLocation, XcmExecutor}; type RuntimeHelper = @@ -110,7 +110,7 @@ pub fn teleports_for_native_asset_works< 0.into() ); - let native_asset_id = MultiLocation::parent(); + let native_asset_id = Location::parent(); let buy_execution_fee_amount_eta = WeightToFee::weight_to_fee(&Weight::from_parts(90_000_000_000, 1024)); let native_asset_amount_unit = existential_deposit; @@ -119,38 +119,40 @@ pub fn teleports_for_native_asset_works< // 1. process received teleported assets from relaychain let xcm = Xcm(vec![ - ReceiveTeleportedAsset(MultiAssets::from(vec![MultiAsset { - id: Concrete(native_asset_id), + ReceiveTeleportedAsset(Assets::from(vec![Asset { + id: AssetId(native_asset_id.clone()), fun: Fungible(native_asset_amount_received.into()), }])), ClearOrigin, BuyExecution { - fees: MultiAsset { - id: Concrete(native_asset_id), + fees: Asset { + id: AssetId(native_asset_id.clone()), fun: Fungible(buy_execution_fee_amount_eta), }, weight_limit: Limited(Weight::from_parts(3035310000, 65536)), }, DepositAsset { assets: Wild(AllCounted(1)), - beneficiary: MultiLocation { + beneficiary: Location { parents: 0, - interior: X1(AccountId32 { + interior: [AccountId32 { network: None, id: target_account.clone().into(), - }), + }] + .into(), }, }, ExpectTransactStatus(MaybeErrorCode::Success), ]); - let hash = xcm.using_encoded(sp_io::hashing::blake2_256); + let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256); - let outcome = XcmExecutor::::execute_xcm( + let outcome = XcmExecutor::::prepare_and_execute( Parent, xcm, - hash, + &mut hash, RuntimeHelper::::xcm_max_weight(XcmReceivedFrom::Parent), + Weight::zero(), ); assert_eq!(outcome.ensure_complete(), Ok(())); @@ -163,14 +165,14 @@ pub fn teleports_for_native_asset_works< // 2. try to teleport asset back to the relaychain { - let dest = MultiLocation::parent(); - let mut dest_beneficiary = MultiLocation::parent() + let dest = Location::parent(); + let mut dest_beneficiary = Location::parent() .appended_with(AccountId32 { network: None, id: sp_runtime::AccountId32::new([3; 32]).into(), }) .unwrap(); - dest_beneficiary.reanchor(&dest, XcmConfig::UniversalLocation::get()).unwrap(); + dest_beneficiary.reanchor(&dest, &XcmConfig::UniversalLocation::get()).unwrap(); let target_account_balance_before_teleport = >::free_balance(&target_account); @@ -183,11 +185,11 @@ pub fn teleports_for_native_asset_works< // Mint funds into account to ensure it has enough balance to pay delivery fees let delivery_fees = xcm_helpers::transfer_assets_delivery_fees::( - (native_asset_id, native_asset_to_teleport_away.into()).into(), + (native_asset_id.clone(), native_asset_to_teleport_away.into()).into(), 0, Unlimited, - dest_beneficiary, - dest, + dest_beneficiary.clone(), + dest.clone(), ); >::mint_into( &target_account, @@ -199,7 +201,7 @@ pub fn teleports_for_native_asset_works< RuntimeHelper::::origin_of(target_account.clone()), dest, dest_beneficiary, - (native_asset_id, native_asset_to_teleport_away.into()), + (native_asset_id.clone(), native_asset_to_teleport_away.into()), None, included_head.clone(), &alice, @@ -228,14 +230,14 @@ pub fn teleports_for_native_asset_works< // trust `IsTeleporter` for `(relay-native-asset, para(2345))` pair { let other_para_id = 2345; - let dest = MultiLocation::new(1, X1(Parachain(other_para_id))); - let mut dest_beneficiary = MultiLocation::new(1, X1(Parachain(other_para_id))) + let dest = Location::new(1, [Parachain(other_para_id)]); + let mut dest_beneficiary = Location::new(1, [Parachain(other_para_id)]) .appended_with(AccountId32 { network: None, id: sp_runtime::AccountId32::new([3; 32]).into(), }) .unwrap(); - dest_beneficiary.reanchor(&dest, XcmConfig::UniversalLocation::get()).unwrap(); + dest_beneficiary.reanchor(&dest, &XcmConfig::UniversalLocation::get()).unwrap(); let target_account_balance_before_teleport = >::free_balance(&target_account); @@ -245,6 +247,7 @@ pub fn teleports_for_native_asset_works< native_asset_to_teleport_away < target_account_balance_before_teleport - existential_deposit ); + assert_eq!( RuntimeHelper::::do_teleport_assets::( RuntimeHelper::::origin_of(target_account.clone()), @@ -356,9 +359,9 @@ pub fn teleports_for_foreign_assets_works< ::Balance: From + Into, SovereignAccountOf: ConvertLocation>, >::AssetId: - From + Into, + From + Into, >::AssetIdParameter: - From + Into, + From + Into, >::Balance: From + Into, ::AccountId: @@ -370,23 +373,21 @@ pub fn teleports_for_foreign_assets_works< { // foreign parachain with the same consensus currency as asset let foreign_para_id = 2222; - let foreign_asset_id_multilocation = MultiLocation { + let foreign_asset_id_location = Location { parents: 1, - interior: X2(Parachain(foreign_para_id), GeneralIndex(1234567)), + interior: [Parachain(foreign_para_id), GeneralIndex(1234567)].into(), }; // foreign creator, which can be sibling parachain to match ForeignCreators - let foreign_creator = MultiLocation { parents: 1, interior: X1(Parachain(foreign_para_id)) }; + let foreign_creator = Location { parents: 1, interior: [Parachain(foreign_para_id)].into() }; let foreign_creator_as_account_id = SovereignAccountOf::convert_location(&foreign_creator).expect(""); // we want to buy execution with local relay chain currency let buy_execution_fee_amount = WeightToFee::weight_to_fee(&Weight::from_parts(90_000_000_000, 0)); - let buy_execution_fee = MultiAsset { - id: Concrete(MultiLocation::parent()), - fun: Fungible(buy_execution_fee_amount), - }; + let buy_execution_fee = + Asset { id: AssetId(Location::parent()), fun: Fungible(buy_execution_fee_amount) }; let teleported_foreign_asset_amount = 10_000_000_000_000; let runtime_para_id = 1000; @@ -425,14 +426,14 @@ pub fn teleports_for_foreign_assets_works< ); assert_eq!( >::balance( - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), &target_account ), 0.into() ); assert_eq!( >::balance( - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), &CheckingAccount::get() ), 0.into() @@ -441,14 +442,14 @@ pub fn teleports_for_foreign_assets_works< assert_total::< pallet_assets::Pallet, AccountIdOf, - >(foreign_asset_id_multilocation, 0, 0); + >(foreign_asset_id_location.clone(), 0, 0); // create foreign asset (0 total issuance) let asset_minimum_asset_balance = 3333333_u128; assert_ok!( >::force_create( RuntimeHelper::::root_origin(), - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), asset_owner.into(), false, asset_minimum_asset_balance.into() @@ -457,7 +458,7 @@ pub fn teleports_for_foreign_assets_works< assert_total::< pallet_assets::Pallet, AccountIdOf, - >(foreign_asset_id_multilocation, 0, 0); + >(foreign_asset_id_location.clone(), 0, 0); assert!(teleported_foreign_asset_amount > asset_minimum_asset_balance); // 1. process received teleported assets from sibling parachain (foreign_para_id) @@ -465,39 +466,41 @@ pub fn teleports_for_foreign_assets_works< // BuyExecution with relaychain native token WithdrawAsset(buy_execution_fee.clone().into()), BuyExecution { - fees: MultiAsset { - id: Concrete(MultiLocation::parent()), + fees: Asset { + id: AssetId(Location::parent()), fun: Fungible(buy_execution_fee_amount), }, weight_limit: Limited(Weight::from_parts(403531000, 65536)), }, // Process teleported asset - ReceiveTeleportedAsset(MultiAssets::from(vec![MultiAsset { - id: Concrete(foreign_asset_id_multilocation), + ReceiveTeleportedAsset(Assets::from(vec![Asset { + id: AssetId(foreign_asset_id_location.clone()), fun: Fungible(teleported_foreign_asset_amount), }])), DepositAsset { assets: Wild(AllOf { - id: Concrete(foreign_asset_id_multilocation), + id: AssetId(foreign_asset_id_location.clone()), fun: WildFungibility::Fungible, }), - beneficiary: MultiLocation { + beneficiary: Location { parents: 0, - interior: X1(AccountId32 { + interior: [AccountId32 { network: None, id: target_account.clone().into(), - }), + }] + .into(), }, }, ExpectTransactStatus(MaybeErrorCode::Success), ]); - let hash = xcm.using_encoded(sp_io::hashing::blake2_256); + let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256); - let outcome = XcmExecutor::::execute_xcm( + let outcome = XcmExecutor::::prepare_and_execute( foreign_creator, xcm, - hash, + &mut hash, RuntimeHelper::::xcm_max_weight(XcmReceivedFrom::Sibling), + Weight::zero(), ); assert_eq!(outcome.ensure_complete(), Ok(())); @@ -508,7 +511,7 @@ pub fn teleports_for_foreign_assets_works< ); assert_eq!( >::balance( - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), &target_account ), teleported_foreign_asset_amount.into() @@ -520,7 +523,7 @@ pub fn teleports_for_foreign_assets_works< ); assert_eq!( >::balance( - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), &CheckingAccount::get() ), 0.into() @@ -530,25 +533,25 @@ pub fn teleports_for_foreign_assets_works< pallet_assets::Pallet, AccountIdOf, >( - foreign_asset_id_multilocation, + foreign_asset_id_location.clone(), teleported_foreign_asset_amount, teleported_foreign_asset_amount, ); // 2. try to teleport asset back to source parachain (foreign_para_id) { - let dest = MultiLocation::new(1, X1(Parachain(foreign_para_id))); - let mut dest_beneficiary = MultiLocation::new(1, X1(Parachain(foreign_para_id))) + let dest = Location::new(1, [Parachain(foreign_para_id)]); + let mut dest_beneficiary = Location::new(1, [Parachain(foreign_para_id)]) .appended_with(AccountId32 { network: None, id: sp_runtime::AccountId32::new([3; 32]).into(), }) .unwrap(); - dest_beneficiary.reanchor(&dest, XcmConfig::UniversalLocation::get()).unwrap(); + dest_beneficiary.reanchor(&dest, &XcmConfig::UniversalLocation::get()).unwrap(); let target_account_balance_before_teleport = >::balance( - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), &target_account, ); let asset_to_teleport_away = asset_minimum_asset_balance * 3; @@ -562,11 +565,11 @@ pub fn teleports_for_foreign_assets_works< // Make sure the target account has enough native asset to pay for delivery fees let delivery_fees = xcm_helpers::transfer_assets_delivery_fees::( - (foreign_asset_id_multilocation, asset_to_teleport_away).into(), + (foreign_asset_id_location.clone(), asset_to_teleport_away).into(), 0, Unlimited, - dest_beneficiary, - dest, + dest_beneficiary.clone(), + dest.clone(), ); >::mint_into( &target_account, @@ -578,7 +581,7 @@ pub fn teleports_for_foreign_assets_works< RuntimeHelper::::origin_of(target_account.clone()), dest, dest_beneficiary, - (foreign_asset_id_multilocation, asset_to_teleport_away), + (foreign_asset_id_location.clone(), asset_to_teleport_away), Some((runtime_para_id, foreign_para_id)), included_head, &alice, @@ -587,14 +590,14 @@ pub fn teleports_for_foreign_assets_works< // check balances assert_eq!( >::balance( - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), &target_account ), (target_account_balance_before_teleport - asset_to_teleport_away.into()) ); assert_eq!( >::balance( - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), &CheckingAccount::get() ), 0.into() @@ -604,7 +607,7 @@ pub fn teleports_for_foreign_assets_works< pallet_assets::Pallet, AccountIdOf, >( - foreign_asset_id_multilocation, + foreign_asset_id_location, teleported_foreign_asset_amount - asset_to_teleport_away, teleported_foreign_asset_amount - asset_to_teleport_away, ); @@ -717,17 +720,19 @@ pub fn asset_transactor_transfer_with_local_consensus_currency_works BOB let _ = RuntimeHelper::::do_transfer( - MultiLocation { + Location { parents: 0, - interior: X1(AccountId32 { network: None, id: source_account.clone().into() }), + interior: [AccountId32 { network: None, id: source_account.clone().into() }] + .into(), }, - MultiLocation { + Location { parents: 0, - interior: X1(AccountId32 { network: None, id: target_account.clone().into() }), + interior: [AccountId32 { network: None, id: target_account.clone().into() }] + .into(), }, // local_consensus_currency_asset, e.g.: relaychain token (KSM, DOT, ...) ( - MultiLocation { parents: 1, interior: Here }, + Location { parents: 1, interior: Here }, (BalanceOf::::from(1_u128) * unit).into(), ), ) @@ -779,7 +784,7 @@ macro_rules! include_asset_transactor_transfer_with_local_consensus_currency_wor } ); -///Test-case makes sure that `Runtime`'s `xcm::AssetTransactor` can handle native relay chain +/// Test-case makes sure that `Runtime`'s `xcm::AssetTransactor` can handle native relay chain /// currency pub fn asset_transactor_transfer_with_pallet_assets_instance_works< Runtime, @@ -820,8 +825,8 @@ pub fn asset_transactor_transfer_with_pallet_assets_instance_works< <::Lookup as StaticLookup>::Source: From<::AccountId>, AssetsPalletInstance: 'static, - AssetId: Clone + Copy, - AssetIdConverter: MaybeEquivalence, + AssetId: Clone, + AssetIdConverter: MaybeEquivalence, { ExtBuilder::::default() .with_collators(collator_session_keys.collators()) @@ -836,10 +841,10 @@ pub fn asset_transactor_transfer_with_pallet_assets_instance_works< .execute_with(|| { // create some asset class let asset_minimum_asset_balance = 3333333_u128; - let asset_id_as_multilocation = AssetIdConverter::convert_back(&asset_id).unwrap(); + let asset_id_as_location = AssetIdConverter::convert_back(&asset_id).unwrap(); assert_ok!(>::force_create( RuntimeHelper::::root_origin(), - asset_id.into(), + asset_id.clone().into(), asset_owner.clone().into(), false, asset_minimum_asset_balance.into() @@ -848,7 +853,7 @@ pub fn asset_transactor_transfer_with_pallet_assets_instance_works< // We first mint enough asset for the account to exist for assets assert_ok!(>::mint( RuntimeHelper::::origin_of(asset_owner.clone()), - asset_id.into(), + asset_id.clone().into(), alice_account.clone().into(), (6 * asset_minimum_asset_balance).into() )); @@ -856,28 +861,28 @@ pub fn asset_transactor_transfer_with_pallet_assets_instance_works< // check Assets before assert_eq!( >::balance( - asset_id.into(), + asset_id.clone().into(), &alice_account ), (6 * asset_minimum_asset_balance).into() ); assert_eq!( >::balance( - asset_id.into(), + asset_id.clone().into(), &bob_account ), 0.into() ); assert_eq!( >::balance( - asset_id.into(), + asset_id.clone().into(), &charlie_account ), 0.into() ); assert_eq!( >::balance( - asset_id.into(), + asset_id.clone().into(), &asset_owner ), 0.into() @@ -904,21 +909,20 @@ pub fn asset_transactor_transfer_with_pallet_assets_instance_works< // ExistentialDeposit) assert_noop!( RuntimeHelper::::do_transfer( - MultiLocation { + Location { parents: 0, - interior: X1(AccountId32 { - network: None, - id: alice_account.clone().into() - }), + interior: [AccountId32 { network: None, id: alice_account.clone().into() }] + .into(), }, - MultiLocation { + Location { parents: 0, - interior: X1(AccountId32 { + interior: [AccountId32 { network: None, id: charlie_account.clone().into() - }), + }] + .into(), }, - (asset_id_as_multilocation, asset_minimum_asset_balance), + (asset_id_as_location.clone(), asset_minimum_asset_balance), ), XcmError::FailedToTransactAsset(Into::<&str>::into( sp_runtime::TokenError::CannotCreate @@ -928,18 +932,17 @@ pub fn asset_transactor_transfer_with_pallet_assets_instance_works< // transfer_asset (deposit/withdraw) ALICE -> BOB (ok - has ExistentialDeposit) assert!(matches!( RuntimeHelper::::do_transfer( - MultiLocation { + Location { parents: 0, - interior: X1(AccountId32 { - network: None, - id: alice_account.clone().into() - }), + interior: [AccountId32 { network: None, id: alice_account.clone().into() }] + .into(), }, - MultiLocation { + Location { parents: 0, - interior: X1(AccountId32 { network: None, id: bob_account.clone().into() }), + interior: [AccountId32 { network: None, id: bob_account.clone().into() }] + .into(), }, - (asset_id_as_multilocation, asset_minimum_asset_balance), + (asset_id_as_location, asset_minimum_asset_balance), ), Ok(_) )); @@ -947,21 +950,21 @@ pub fn asset_transactor_transfer_with_pallet_assets_instance_works< // check Assets after assert_eq!( >::balance( - asset_id.into(), + asset_id.clone().into(), &alice_account ), (5 * asset_minimum_asset_balance).into() ); assert_eq!( >::balance( - asset_id.into(), + asset_id.clone().into(), &bob_account ), asset_minimum_asset_balance.into() ); assert_eq!( >::balance( - asset_id.into(), + asset_id.clone().into(), &charlie_account ), 0.into() @@ -1093,26 +1096,24 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor <::Lookup as StaticLookup>::Source: From<::AccountId>, ForeignAssetsPalletInstance: 'static, - AssetId: Clone + Copy, - AssetIdConverter: MaybeEquivalence, + AssetId: Clone, + AssetIdConverter: MaybeEquivalence, { - // foreign parachain with the same consensus currency as asset - let foreign_asset_id_multilocation = - MultiLocation { parents: 1, interior: X2(Parachain(2222), GeneralIndex(1234567)) }; - let asset_id = AssetIdConverter::convert(&foreign_asset_id_multilocation).unwrap(); + // foreign parachain with the same consenus currency as asset + let foreign_asset_id_location = + Location::new(1, [Parachain(2222), GeneralIndex(1234567)]); + let asset_id = AssetIdConverter::convert(&foreign_asset_id_location).unwrap(); // foreign creator, which can be sibling parachain to match ForeignCreators - let foreign_creator = MultiLocation { parents: 1, interior: X1(Parachain(2222)) }; + let foreign_creator = Location { parents: 1, interior: [Parachain(2222)].into() }; let foreign_creator_as_account_id = SovereignAccountOf::convert_location(&foreign_creator).expect(""); // we want to buy execution with local relay chain currency let buy_execution_fee_amount = WeightToFee::weight_to_fee(&Weight::from_parts(90_000_000_000, 0)); - let buy_execution_fee = MultiAsset { - id: Concrete(MultiLocation::parent()), - fun: Fungible(buy_execution_fee_amount), - }; + let buy_execution_fee = + Asset { id: AssetId(Location::parent()), fun: Fungible(buy_execution_fee_amount) }; const ASSET_NAME: &str = "My super coin"; const ASSET_SYMBOL: &str = "MY_S_COIN"; @@ -1152,7 +1153,7 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor Runtime, ForeignAssetsPalletInstance, >::create { - id: asset_id.into(), + id: asset_id.clone().into(), // admin as sovereign_account admin: foreign_creator_as_account_id.clone().into(), min_balance: 1.into(), @@ -1162,7 +1163,7 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor Runtime, ForeignAssetsPalletInstance, >::set_metadata { - id: asset_id.into(), + id: asset_id.clone().into(), name: Vec::from(ASSET_NAME), symbol: Vec::from(ASSET_SYMBOL), decimals: 12, @@ -1172,7 +1173,7 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor Runtime, ForeignAssetsPalletInstance, >::set_team { - id: asset_id.into(), + id: asset_id.clone().into(), issuer: foreign_creator_as_account_id.clone().into(), admin: foreign_creator_as_account_id.clone().into(), freezer: bob_account.clone().into(), @@ -1202,14 +1203,15 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor ]); // messages with different consensus should go through the local bridge-hub - let hash = xcm.using_encoded(sp_io::hashing::blake2_256); + let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256); // execute xcm as XcmpQueue would do - let outcome = XcmExecutor::::execute_xcm( - foreign_creator, + let outcome = XcmExecutor::::prepare_and_execute( + foreign_creator.clone(), xcm, - hash, + &mut hash, RuntimeHelper::::xcm_max_weight(XcmReceivedFrom::Sibling), + Weight::zero(), ); assert_eq!(outcome.ensure_complete(), Ok(())); @@ -1230,25 +1232,25 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor use frame_support::traits::fungibles::roles::Inspect as InspectRoles; assert_eq!( >::owner( - asset_id.into() + asset_id.clone().into() ), Some(foreign_creator_as_account_id.clone()) ); assert_eq!( >::admin( - asset_id.into() + asset_id.clone().into() ), Some(foreign_creator_as_account_id.clone()) ); assert_eq!( >::issuer( - asset_id.into() + asset_id.clone().into() ), Some(foreign_creator_as_account_id.clone()) ); assert_eq!( >::freezer( - asset_id.into() + asset_id.clone().into() ), Some(bob_account.clone()) ); @@ -1262,13 +1264,13 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor assert_metadata::< pallet_assets::Pallet, AccountIdOf, - >(asset_id, ASSET_NAME, ASSET_SYMBOL, 12); + >(asset_id.clone(), ASSET_NAME, ASSET_SYMBOL, 12); // check if changed freezer, can freeze assert_noop!( >::freeze( RuntimeHelper::::origin_of(bob_account), - asset_id.into(), + asset_id.clone().into(), alice_account.clone().into() ), pallet_assets::Error::::NoAccount @@ -1284,9 +1286,9 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor // lets try create asset for different parachain(3333) (foreign_creator(2222) can create // just his assets) - let foreign_asset_id_multilocation = - MultiLocation { parents: 1, interior: X2(Parachain(3333), GeneralIndex(1234567)) }; - let asset_id = AssetIdConverter::convert(&foreign_asset_id_multilocation).unwrap(); + let foreign_asset_id_location = + Location { parents: 1, interior: [Parachain(3333), GeneralIndex(1234567)].into() }; + let asset_id = AssetIdConverter::convert(&foreign_asset_id_location).unwrap(); // prepare data for xcm::Transact(create) let foreign_asset_create = runtime_call_encode(pallet_assets::Call::< @@ -1310,14 +1312,15 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor ]); // messages with different consensus should go through the local bridge-hub - let hash = xcm.using_encoded(sp_io::hashing::blake2_256); + let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256); // execute xcm as XcmpQueue would do - let outcome = XcmExecutor::::execute_xcm( + let outcome = XcmExecutor::::prepare_and_execute( foreign_creator, xcm, - hash, + &mut hash, RuntimeHelper::::xcm_max_weight(XcmReceivedFrom::Sibling), + Weight::zero(), ); assert_eq!(outcome.ensure_complete(), Ok(())); @@ -1441,15 +1444,15 @@ pub fn reserve_transfer_native_asset_to_non_teleport_para_works< // reserve-transfer native asset with local reserve to remote parachain (2345) let other_para_id = 2345; - let native_asset = MultiLocation::parent(); - let dest = MultiLocation::new(1, X1(Parachain(other_para_id))); - let mut dest_beneficiary = MultiLocation::new(1, X1(Parachain(other_para_id))) + let native_asset = Location::parent(); + let dest = Location::new(1, [Parachain(other_para_id)]); + let mut dest_beneficiary = Location::new(1, [Parachain(other_para_id)]) .appended_with(AccountId32 { network: None, id: sp_runtime::AccountId32::new([3; 32]).into(), }) .unwrap(); - dest_beneficiary.reanchor(&dest, XcmConfig::UniversalLocation::get()).unwrap(); + dest_beneficiary.reanchor(&dest, &XcmConfig::UniversalLocation::get()).unwrap(); let reserve_account = LocationToAccountId::convert_location(&dest) .expect("Sovereign account for reserves"); @@ -1495,17 +1498,17 @@ pub fn reserve_transfer_native_asset_to_non_teleport_para_works< ); // local native asset (pallet_balances) - let asset_to_transfer = MultiAsset { + let asset_to_transfer = Asset { fun: Fungible(balance_to_transfer.into()), - id: Concrete(native_asset), + id: AssetId(native_asset), }; // pallet_xcm call reserve transfer assert_ok!(>::limited_reserve_transfer_assets( RuntimeHelper::::origin_of(alice_account.clone()), - Box::new(dest.into_versioned()), - Box::new(dest_beneficiary.into_versioned()), - Box::new(VersionedMultiAssets::from(MultiAssets::from(asset_to_transfer))), + Box::new(dest.clone().into_versioned()), + Box::new(dest_beneficiary.clone().into_versioned()), + Box::new(VersionedAssets::from(Assets::from(asset_to_transfer))), 0, weight_limit, )); @@ -1535,9 +1538,12 @@ pub fn reserve_transfer_native_asset_to_non_teleport_para_works< ) .unwrap(); + let v4_xcm: Xcm<()> = xcm_sent.clone().try_into().unwrap(); + dbg!(&v4_xcm); + let delivery_fees = get_fungible_delivery_fees::< ::XcmSender, - >(dest, Xcm::try_from(xcm_sent.clone()).unwrap()); + >(dest.clone(), Xcm::try_from(xcm_sent.clone()).unwrap()); assert_eq!( xcm_sent_message_hash, @@ -1547,8 +1553,8 @@ pub fn reserve_transfer_native_asset_to_non_teleport_para_works< // check sent XCM Program to other parachain println!("reserve_transfer_native_asset_works sent xcm: {:?}", xcm_sent); - let reserve_assets_deposited = MultiAssets::from(vec![MultiAsset { - id: Concrete(MultiLocation { parents: 1, interior: Here }), + let reserve_assets_deposited = Assets::from(vec![Asset { + id: AssetId(Location { parents: 1, interior: Here }), fun: Fungible(1000000000000), }]); diff --git a/cumulus/parachains/runtimes/assets/test-utils/src/test_cases_over_bridge.rs b/cumulus/parachains/runtimes/assets/test-utils/src/test_cases_over_bridge.rs index 851fcd5c7d68..ffba6e51e5ba 100644 --- a/cumulus/parachains/runtimes/assets/test-utils/src/test_cases_over_bridge.rs +++ b/cumulus/parachains/runtimes/assets/test-utils/src/test_cases_over_bridge.rs @@ -30,15 +30,15 @@ use parachains_runtimes_test_utils::{ ValidatorIdOf, XcmReceivedFrom, }; use sp_runtime::{traits::StaticLookup, Saturating}; -use xcm::{latest::prelude::*, VersionedMultiAssets}; +use xcm::{latest::prelude::*, VersionedAssets}; use xcm_builder::{CreateMatcher, MatchXcm}; use xcm_executor::{traits::ConvertLocation, XcmExecutor}; pub struct TestBridgingConfig { pub bridged_network: NetworkId, pub local_bridge_hub_para_id: u32, - pub local_bridge_hub_location: MultiLocation, - pub bridged_target_location: MultiLocation, + pub local_bridge_hub_location: Location, + pub bridged_target_location: Location, } /// Test-case makes sure that `Runtime` can initiate **reserve transfer assets** over bridge. @@ -116,7 +116,7 @@ pub fn limited_reserve_transfer_assets_for_native_asset_works< LocationToAccountId::convert_location(&target_location_from_different_consensus) .expect("Sovereign account for reserves"); let balance_to_transfer = 1_000_000_000_000_u128; - let native_asset = MultiLocation::parent(); + let native_asset = Location::parent(); // open HRMP to bridge hub mock_open_hrmp_channel::( @@ -162,35 +162,32 @@ pub fn limited_reserve_transfer_assets_for_native_asset_works< .unwrap_or(0.into()); // local native asset (pallet_balances) - let asset_to_transfer = MultiAsset { + let asset_to_transfer = Asset { fun: Fungible(balance_to_transfer.into()), - id: Concrete(native_asset), + id: native_asset.into(), }; // destination is (some) account relative to the destination different consensus - let target_destination_account = MultiLocation { - parents: 0, - interior: X1(AccountId32 { - network: Some(bridged_network), - id: sp_runtime::AccountId32::new([3; 32]).into(), - }), - }; + let target_destination_account = Location::new(0, [AccountId32 { + network: Some(bridged_network), + id: sp_runtime::AccountId32::new([3; 32]).into(), + }]); - let assets_to_transfer = MultiAssets::from(asset_to_transfer); + let assets_to_transfer = Assets::from(asset_to_transfer); let mut expected_assets = assets_to_transfer.clone(); let context = XcmConfig::UniversalLocation::get(); expected_assets - .reanchor(&target_location_from_different_consensus, context) + .reanchor(&target_location_from_different_consensus, &context) .unwrap(); - let expected_beneficiary = target_destination_account; + let expected_beneficiary = target_destination_account.clone(); // do pallet_xcm call reserve transfer assert_ok!(>::limited_reserve_transfer_assets( RuntimeHelper::::origin_of(alice_account.clone()), - Box::new(target_location_from_different_consensus.into_versioned()), + Box::new(target_location_from_different_consensus.clone().into_versioned()), Box::new(target_destination_account.into_versioned()), - Box::new(VersionedMultiAssets::from(assets_to_transfer)), + Box::new(VersionedAssets::from(assets_to_transfer)), 0, weight_limit, )); @@ -265,13 +262,14 @@ pub fn limited_reserve_transfer_assets_for_native_asset_works< let (_, target_location_junctions_without_global_consensus) = target_location_from_different_consensus .interior + .clone() .split_global() .expect("split works"); assert_eq!(destination, &target_location_junctions_without_global_consensus); // Call `SendXcm::validate` to get delivery fees. delivery_fees = get_fungible_delivery_fees::< ::XcmSender, - >(target_location_from_different_consensus, inner_xcm.clone()); + >(target_location_from_different_consensus.clone(), inner_xcm.clone()); assert_matches_reserve_asset_deposited_instructions( inner_xcm, &expected_assets, @@ -321,10 +319,10 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works< target_account: AccountIdOf, block_author_account: AccountIdOf, ( - foreign_asset_id_multilocation, + foreign_asset_id_location, transfered_foreign_asset_id_amount, foreign_asset_id_minimum_balance, - ): (MultiLocation, u128, u128), + ): (Location, u128, u128), prepare_configuration: fn() -> TestBridgingConfig, (bridge_instance, universal_origin, descend_origin): (Junctions, Junction, Junctions), /* bridge adds origin manipulation on the way */ ) where @@ -345,9 +343,9 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works< XcmConfig: xcm_executor::Config, LocationToAccountId: ConvertLocation>, >::AssetId: - From + Into, + From + Into, >::AssetIdParameter: - From + Into, + From + Into, >::Balance: From + Into + From, ::AccountId: Into<<::RuntimeOrigin as OriginTrait>::AccountId> @@ -380,7 +378,7 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works< // sovereign account as foreign asset owner (can be whoever for this scenario, doesnt // matter) let sovereign_account_as_owner_of_foreign_asset = - LocationToAccountId::convert_location(&MultiLocation::parent()).unwrap(); + LocationToAccountId::convert_location(&Location::parent()).unwrap(); // staking pot account for collecting local native fees from `BuyExecution` let staking_pot = >::account_id(); @@ -393,7 +391,7 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works< assert_ok!( >::force_create( RuntimeHelper::::root_origin(), - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), sovereign_account_as_owner_of_foreign_asset.clone().into(), true, // is_sufficient=true foreign_asset_id_minimum_balance.into() @@ -417,34 +415,31 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works< // ForeignAssets balances before assert_eq!( >::balance( - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), &target_account ), 0.into() ); assert_eq!( >::balance( - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), &block_author_account ), 0.into() ); assert_eq!( >::balance( - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), &staking_pot ), 0.into() ); - let expected_assets = MultiAssets::from(vec![MultiAsset { - id: Concrete(foreign_asset_id_multilocation), + let expected_assets = Assets::from(vec![Asset { + id: AssetId(foreign_asset_id_location.clone()), fun: Fungible(transfered_foreign_asset_id_amount), }]); - let expected_beneficiary = MultiLocation { - parents: 0, - interior: X1(AccountId32 { network: None, id: target_account.clone().into() }), - }; + let expected_beneficiary = Location::new(0, [AccountId32 { network: None, id: target_account.clone().into() }]); // Call received XCM execution let xcm = Xcm(vec![ @@ -454,13 +449,13 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works< ReserveAssetDeposited(expected_assets.clone()), ClearOrigin, BuyExecution { - fees: MultiAsset { - id: Concrete(foreign_asset_id_multilocation), + fees: Asset { + id: foreign_asset_id_location.clone().into(), fun: Fungible(transfered_foreign_asset_id_amount), }, weight_limit: Unlimited, }, - DepositAsset { assets: Wild(AllCounted(1)), beneficiary: expected_beneficiary }, + DepositAsset { assets: Wild(AllCounted(1)), beneficiary: expected_beneficiary.clone() }, SetTopic([ 220, 188, 144, 32, 213, 83, 111, 175, 44, 210, 111, 19, 90, 165, 191, 112, 140, 247, 192, 124, 42, 17, 153, 141, 114, 34, 189, 20, 83, 69, 237, 173, @@ -472,13 +467,16 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works< &expected_beneficiary, ); - let hash = xcm.using_encoded(sp_io::hashing::blake2_256); + let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256); // execute xcm as XcmpQueue would do - let outcome = XcmExecutor::::execute_xcm( + let outcome = XcmExecutor::::prepare_and_execute( local_bridge_hub_location, xcm, - hash, + &mut hash, + RuntimeHelper::::xcm_max_weight( + XcmReceivedFrom::Sibling, + ), RuntimeHelper::::xcm_max_weight( XcmReceivedFrom::Sibling, ), @@ -488,7 +486,7 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works< // author actual balance after (received fees from Trader for ForeignAssets) let author_received_fees = >::balance( - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), &block_author_account, ); @@ -509,21 +507,21 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works< // ForeignAssets balances after assert_eq!( >::balance( - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), &target_account ), (transfered_foreign_asset_id_amount - author_received_fees.into()).into() ); assert_eq!( >::balance( - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.clone().into(), &block_author_account ), author_received_fees ); assert_eq!( >::balance( - foreign_asset_id_multilocation.into(), + foreign_asset_id_location.into(), &staking_pot ), 0.into() @@ -579,13 +577,14 @@ pub fn report_bridge_status_from_xcm_bridge_router_works< // Call received XCM execution let xcm = if is_congested { congested_message() } else { uncongested_message() }; - let hash = xcm.using_encoded(sp_io::hashing::blake2_256); + let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256); // execute xcm as XcmpQueue would do - let outcome = XcmExecutor::::execute_xcm( + let outcome = XcmExecutor::::prepare_and_execute( local_bridge_hub_location, xcm, - hash, + &mut hash, + RuntimeHelper::::xcm_max_weight(XcmReceivedFrom::Sibling), RuntimeHelper::::xcm_max_weight(XcmReceivedFrom::Sibling), ); assert_eq!(outcome.ensure_complete(), Ok(())); diff --git a/cumulus/parachains/runtimes/assets/test-utils/src/xcm_helpers.rs b/cumulus/parachains/runtimes/assets/test-utils/src/xcm_helpers.rs index 0aebe38fef53..489a83c6726e 100644 --- a/cumulus/parachains/runtimes/assets/test-utils/src/xcm_helpers.rs +++ b/cumulus/parachains/runtimes/assets/test-utils/src/xcm_helpers.rs @@ -23,11 +23,11 @@ use xcm::latest::prelude::*; /// Because it returns only a `u128`, it assumes delivery fees are only paid /// in one asset and that asset is known. pub fn transfer_assets_delivery_fees( - assets: MultiAssets, + assets: Assets, fee_asset_item: u32, weight_limit: WeightLimit, - beneficiary: MultiLocation, - destination: MultiLocation, + beneficiary: Location, + destination: Location, ) -> u128 { let message = teleport_assets_dummy_message(assets, fee_asset_item, weight_limit, beneficiary); get_fungible_delivery_fees::(destination, message) @@ -35,7 +35,7 @@ pub fn transfer_assets_delivery_fees( /// Returns the delivery fees amount for a query response as a result of the execution /// of a `ExpectError` instruction with no error. -pub fn query_response_delivery_fees(querier: MultiLocation) -> u128 { +pub fn query_response_delivery_fees(querier: Location) -> u128 { // Message to calculate delivery fees, it's encoded size is what's important. // This message reports that there was no error, if an error is reported, the encoded size would // be different. @@ -45,7 +45,7 @@ pub fn query_response_delivery_fees(querier: MultiLocation) -> u128 query_id: 0, // Dummy query id response: Response::ExecutionResult(None), max_weight: Weight::zero(), - querier: Some(querier), + querier: Some(querier.clone()), }, SetTopic([0u8; 32]), // Dummy topic ]); @@ -55,9 +55,9 @@ pub fn query_response_delivery_fees(querier: MultiLocation) -> u128 /// Returns the delivery fees amount for the execution of `PayOverXcm` pub fn pay_over_xcm_delivery_fees( interior: Junctions, - destination: MultiLocation, - beneficiary: MultiLocation, - asset: MultiAsset, + destination: Location, + beneficiary: Location, + asset: Asset, ) -> u128 { // This is a dummy message. // The encoded size is all that matters for delivery fees. @@ -66,7 +66,7 @@ pub fn pay_over_xcm_delivery_fees( UnpaidExecution { weight_limit: Unlimited, check_origin: None }, SetAppendix(Xcm(vec![ SetFeesMode { jit_withdraw: true }, - ReportError(QueryResponseInfo { destination, query_id: 0, max_weight: Weight::zero() }), + ReportError(QueryResponseInfo { destination: destination.clone(), query_id: 0, max_weight: Weight::zero() }), ])), TransferAsset { beneficiary, assets: vec![asset].into() }, ]); @@ -78,10 +78,10 @@ pub fn pay_over_xcm_delivery_fees( /// However, it should have the same encoded size, which is what matters for delivery fees. /// Also has same encoded size as the one created by the reserve transfer assets extrinsic. fn teleport_assets_dummy_message( - assets: MultiAssets, + assets: Assets, fee_asset_item: u32, weight_limit: WeightLimit, - beneficiary: MultiLocation, + beneficiary: Location, ) -> Xcm<()> { Xcm(vec![ ReceiveTeleportedAsset(assets.clone()), // Same encoded size as `ReserveAssetDeposited` @@ -93,7 +93,7 @@ fn teleport_assets_dummy_message( } /// Given a message, a sender, and a destination, it returns the delivery fees -fn get_fungible_delivery_fees(destination: MultiLocation, message: Xcm<()>) -> u128 { +fn get_fungible_delivery_fees(destination: Location, message: Xcm<()>) -> u128 { let Ok((_, delivery_fees)) = validate_send::(destination, message) else { unreachable!("message can be sent; qed") }; diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/lib.rs index b37507000842..9822364a7aea 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/lib.rs @@ -708,22 +708,22 @@ impl_runtime_apis! { use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsiscsBenchmark; impl pallet_xcm::benchmarking::Config for Runtime { - fn reachable_dest() -> Option { + fn reachable_dest() -> Option { Some(Parent.into()) } - fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { // Relay/native token can be teleported between BH and Relay. Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Parent.into()) + id: AssetId(Parent.into()) }, Parent.into(), )) } - fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { // Reserve transfers are disabled on BH. None } @@ -733,7 +733,7 @@ impl_runtime_apis! { use xcm_config::KsmRelayLocation; parameter_types! { - pub ExistentialDepositMultiAsset: Option = Some(( + pub ExistentialDepositAsset: Option = Some(( xcm_config::KsmRelayLocation::get(), ExistentialDeposit::get() ).into()); @@ -743,18 +743,18 @@ impl_runtime_apis! { type XcmConfig = xcm_config::XcmConfig; type AccountIdConverter = xcm_config::LocationToAccountId; type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< - xcm_config::XcmConfig, - ExistentialDepositMultiAsset, + xcm_config::XcmConfig, + ExistentialDepositAsset, xcm_config::PriceForParentDelivery, >; - fn valid_destination() -> Result { + fn valid_destination() -> Result { Ok(KsmRelayLocation::get()) } - fn worst_case_holding(_depositable_count: u32) -> MultiAssets { + fn worst_case_holding(_depositable_count: u32) -> Assets { // just concrete assets according to relay chain. - let assets: Vec = vec![ - MultiAsset { - id: Concrete(KsmRelayLocation::get()), + let assets: Vec = vec![ + Asset { + id: AssetId(KsmRelayLocation::get()), fun: Fungible(1_000_000 * UNITS), } ]; @@ -763,12 +763,12 @@ impl_runtime_apis! { } parameter_types! { - pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + pub const TrustedTeleporter: Option<(Location, Asset)> = Some(( KsmRelayLocation::get(), - MultiAsset { fun: Fungible(UNITS), id: Concrete(KsmRelayLocation::get()) }, + Asset { fun: Fungible(UNITS), id: AssetId(KsmRelayLocation::get()) }, )); pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None; - pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None; + pub const TrustedReserve: Option<(Location, Asset)> = None; } impl pallet_xcm_benchmarks::fungible::Config for Runtime { @@ -778,9 +778,9 @@ impl_runtime_apis! { type TrustedTeleporter = TrustedTeleporter; type TrustedReserve = TrustedReserve; - fn get_multi_asset() -> MultiAsset { - MultiAsset { - id: Concrete(KsmRelayLocation::get()), + fn get_asset() -> Asset { + Asset { + id: AssetId(KsmRelayLocation::get()), fun: Fungible(UNITS), } } @@ -794,39 +794,39 @@ impl_runtime_apis! { (0u64, Response::Version(Default::default())) } - fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> { Err(BenchmarkError::Skip) } - fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + fn universal_alias() -> Result<(Location, Junction), BenchmarkError> { Err(BenchmarkError::Skip) } - fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> { + fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> { Ok((KsmRelayLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) } - fn subscribe_origin() -> Result { + fn subscribe_origin() -> Result { Ok(KsmRelayLocation::get()) } - fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { + fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> { let origin = KsmRelayLocation::get(); - let assets: MultiAssets = (Concrete(KsmRelayLocation::get()), 1_000 * UNITS).into(); - let ticket = MultiLocation { parents: 0, interior: Here }; + let assets: Assets = (AssetId(KsmRelayLocation::get()), 1_000 * UNITS).into(); + let ticket = Location { parents: 0, interior: Here }; Ok((origin, ticket, assets)) } - fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { + fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> { Err(BenchmarkError::Skip) } fn export_message_origin_and_destination( - ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { + ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> { Err(BenchmarkError::Skip) } - fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { + fn alias_origin() -> Result<(Location, Location), BenchmarkError> { Err(BenchmarkError::Skip) } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/mod.rs index 71732961d3de..6bfd21d48b48 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/mod.rs @@ -23,14 +23,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; -trait WeighMultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight; +trait WeighAssets { + fn weigh_assets(&self, weight: Weight) -> Weight; } const MAX_ASSETS: u64 = 100; -impl WeighMultiAssets for MultiAssetFilter { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for AssetFilter { + fn weigh_assets(&self, weight: Weight) -> Weight { match self { Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64), Self::Wild(asset) => match asset { @@ -49,40 +49,36 @@ impl WeighMultiAssets for MultiAssetFilter { } } -impl WeighMultiAssets for MultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for Assets { + fn weigh_assets(&self, weight: Weight) -> Weight { weight.saturating_mul(self.inner().iter().count() as u64) } } pub struct BridgeHubKusamaXcmWeight(core::marker::PhantomData); impl XcmWeightInfo for BridgeHubKusamaXcmWeight { - fn withdraw_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::withdraw_asset()) + fn withdraw_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::withdraw_asset()) } - fn reserve_asset_deposited(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::reserve_asset_deposited()) + fn reserve_asset_deposited(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::reserve_asset_deposited()) } - fn receive_teleported_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::receive_teleported_asset()) + fn receive_teleported_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::receive_teleported_asset()) } fn query_response( _query_id: &u64, _response: &Response, _max_weight: &Weight, - _querier: &Option, + _querier: &Option, ) -> Weight { XcmGeneric::::query_response() } - fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_asset()) + fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::transfer_asset()) } - fn transfer_reserve_asset( - assets: &MultiAssets, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_reserve_asset()) + fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } fn transact( _origin_type: &OriginKind, @@ -110,44 +106,36 @@ impl XcmWeightInfo for BridgeHubKusamaXcmWeight { fn clear_origin() -> Weight { XcmGeneric::::clear_origin() } - fn descend_origin(_who: &InteriorMultiLocation) -> Weight { + fn descend_origin(_who: &InteriorLocation) -> Weight { XcmGeneric::::descend_origin() } fn report_error(_query_response_info: &QueryResponseInfo) -> Weight { XcmGeneric::::report_error() } - fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_asset()) + fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::deposit_asset()) } - fn deposit_reserve_asset( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_reserve_asset()) + fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::deposit_reserve_asset()) } - fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight { + fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight { Weight::MAX } fn initiate_reserve_withdraw( - assets: &MultiAssetFilter, - _reserve: &MultiLocation, + assets: &AssetFilter, + _reserve: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) + assets.weigh_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) } - fn initiate_teleport( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_teleport()) + fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } - fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight { + fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } - fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight { + fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } fn refund_surplus() -> Weight { @@ -162,7 +150,7 @@ impl XcmWeightInfo for BridgeHubKusamaXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } - fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight { + fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } fn trap(_code: &u64) -> Weight { @@ -174,13 +162,13 @@ impl XcmWeightInfo for BridgeHubKusamaXcmWeight { fn unsubscribe_version() -> Weight { XcmGeneric::::unsubscribe_version() } - fn burn_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + fn burn_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::burn_asset()) } - fn expect_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + fn expect_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::expect_asset()) } - fn expect_origin(_origin: &Option) -> Weight { + fn expect_origin(_origin: &Option) -> Weight { XcmGeneric::::expect_origin() } fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { @@ -213,16 +201,16 @@ impl XcmWeightInfo for BridgeHubKusamaXcmWeight { fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight { Weight::MAX } - fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn lock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn unlock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn note_unlockable(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn request_unlock(_: &Asset, _: &Location) -> Weight { Weight::MAX } fn set_fees_mode(_: &bool) -> Weight { @@ -234,11 +222,11 @@ impl XcmWeightInfo for BridgeHubKusamaXcmWeight { fn clear_topic() -> Weight { XcmGeneric::::clear_topic() } - fn alias_origin(_: &MultiLocation) -> Weight { + fn alias_origin(_: &Location) -> Weight { // XCM Executor does not currently support alias origin operations Weight::MAX } - fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { + fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/xcm_config.rs index b3703eee8301..3da40a0a449e 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/xcm_config.rs @@ -20,7 +20,7 @@ use super::{ CENTS, }; use frame_support::{ - match_types, parameter_types, + parameter_types, traits::{ConstU32, Contains, Everything, Nothing}, }; use frame_system::EnsureRoot; @@ -40,18 +40,18 @@ use xcm_builder::{ use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; parameter_types! { - pub const KsmRelayLocation: MultiLocation = MultiLocation::parent(); + pub const KsmRelayLocation: Location = Location::parent(); pub const RelayNetwork: Option = Some(NetworkId::Kusama); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = - X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocation: InteriorLocation = + [GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into(); pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 64; - pub const GovernanceLocation: MultiLocation = MultiLocation::parent(); - pub const FellowshipLocation: MultiLocation = MultiLocation::parent(); + pub const GovernanceLocation: Location = Location::parent(); + pub const FellowshipLocation: Location = Location::parent(); } -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( @@ -69,7 +69,7 @@ pub type CurrencyTransactor = CurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: + // Do a simple punn to convert an AccountId32 Location into a native chain account ID: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -101,16 +101,20 @@ pub type XcmOriginToTransactDispatchOrigin = ( XcmPassthrough, ); -match_types! { - pub type ParentOrParentsPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { .. }) } - }; - pub type ParentOrSiblings: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(_) } - }; +pub struct ParentOrParentsPlurality; +impl Contains for ParentOrParentsPlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [Plurality { .. }])) + } } + +pub struct ParentOrSiblings; +impl Contains for ParentOrSiblings { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [_])) + } +} + /// A call filter for the XCM Transact instruction. This is a temporary measure until we properly /// account for proof size weights. /// @@ -218,13 +222,13 @@ impl xcm_executor::Config for XcmConfig { type Aliasers = Nothing; } -/// Converts a local signed origin into an XCM multilocation. +/// Converts a local signed origin into an XCM location. /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; parameter_types! { /// The asset ID for the asset that we use to pay for message delivery fees. - pub FeeAssetId: AssetId = Concrete(KsmRelayLocation::get()); + pub FeeAssetId: AssetId = AssetId(KsmRelayLocation::get()); /// The base fee for the message delivery fees. pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/lib.rs index 841bb4ee8611..f4b05acc4503 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/lib.rs @@ -709,22 +709,22 @@ impl_runtime_apis! { use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsiscsBenchmark; impl pallet_xcm::benchmarking::Config for Runtime { - fn reachable_dest() -> Option { + fn reachable_dest() -> Option { Some(Parent.into()) } - fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { // Relay/native token can be teleported between BH and Relay. Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Parent.into()) + id: AssetId(Parent.into()) }, Parent.into(), )) } - fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { // Reserve transfers are disabled on BH. None } @@ -734,7 +734,7 @@ impl_runtime_apis! { use xcm_config::DotRelayLocation; parameter_types! { - pub ExistentialDepositMultiAsset: Option = Some(( + pub ExistentialDepositAsset: Option = Some(( xcm_config::DotRelayLocation::get(), ExistentialDeposit::get() ).into()); @@ -744,18 +744,18 @@ impl_runtime_apis! { type XcmConfig = xcm_config::XcmConfig; type AccountIdConverter = xcm_config::LocationToAccountId; type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< - xcm_config::XcmConfig, - ExistentialDepositMultiAsset, + xcm_config::XcmConfig, + ExistentialDepositAsset, xcm_config::PriceForParentDelivery, >; - fn valid_destination() -> Result { + fn valid_destination() -> Result { Ok(DotRelayLocation::get()) } - fn worst_case_holding(_depositable_count: u32) -> MultiAssets { + fn worst_case_holding(_depositable_count: u32) -> Assets { // just concrete assets according to relay chain. - let assets: Vec = vec![ - MultiAsset { - id: Concrete(DotRelayLocation::get()), + let assets: Vec = vec![ + Asset { + id: AssetId(DotRelayLocation::get()), fun: Fungible(1_000_000 * UNITS), } ]; @@ -764,12 +764,12 @@ impl_runtime_apis! { } parameter_types! { - pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + pub const TrustedTeleporter: Option<(Location, Asset)> = Some(( DotRelayLocation::get(), - MultiAsset { fun: Fungible(UNITS), id: Concrete(DotRelayLocation::get()) }, + Asset { fun: Fungible(UNITS), id: AssetId(DotRelayLocation::get()) }, )); pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None; - pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None; + pub const TrustedReserve: Option<(Location, Asset)> = None; } impl pallet_xcm_benchmarks::fungible::Config for Runtime { @@ -779,9 +779,9 @@ impl_runtime_apis! { type TrustedTeleporter = TrustedTeleporter; type TrustedReserve = TrustedReserve; - fn get_multi_asset() -> MultiAsset { - MultiAsset { - id: Concrete(DotRelayLocation::get()), + fn get_asset() -> Asset { + Asset { + id: AssetId(DotRelayLocation::get()), fun: Fungible(UNITS), } } @@ -795,39 +795,39 @@ impl_runtime_apis! { (0u64, Response::Version(Default::default())) } - fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> { Err(BenchmarkError::Skip) } - fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + fn universal_alias() -> Result<(Location, Junction), BenchmarkError> { Err(BenchmarkError::Skip) } - fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> { + fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> { Ok((DotRelayLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) } - fn subscribe_origin() -> Result { + fn subscribe_origin() -> Result { Ok(DotRelayLocation::get()) } - fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { + fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> { let origin = DotRelayLocation::get(); - let assets: MultiAssets = (Concrete(DotRelayLocation::get()), 1_000 * UNITS).into(); - let ticket = MultiLocation { parents: 0, interior: Here }; + let assets: Assets = (AssetId(DotRelayLocation::get()), 1_000 * UNITS).into(); + let ticket = Location { parents: 0, interior: Here }; Ok((origin, ticket, assets)) } - fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { + fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> { Err(BenchmarkError::Skip) } fn export_message_origin_and_destination( - ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { + ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> { Err(BenchmarkError::Skip) } - fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { + fn alias_origin() -> Result<(Location, Location), BenchmarkError> { Err(BenchmarkError::Skip) } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/mod.rs index 33a48f368122..45f48992755b 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/mod.rs @@ -23,14 +23,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; -trait WeighMultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight; +trait WeighAssets { + fn weigh_assets(&self, weight: Weight) -> Weight; } const MAX_ASSETS: u64 = 100; -impl WeighMultiAssets for MultiAssetFilter { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for AssetFilter { + fn weigh_assets(&self, weight: Weight) -> Weight { match self { Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64), Self::Wild(asset) => match asset { @@ -49,40 +49,36 @@ impl WeighMultiAssets for MultiAssetFilter { } } -impl WeighMultiAssets for MultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for Assets { + fn weigh_assets(&self, weight: Weight) -> Weight { weight.saturating_mul(self.inner().iter().count() as u64) } } pub struct BridgeHubPolkadotXcmWeight(core::marker::PhantomData); impl XcmWeightInfo for BridgeHubPolkadotXcmWeight { - fn withdraw_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::withdraw_asset()) + fn withdraw_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::withdraw_asset()) } - fn reserve_asset_deposited(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::reserve_asset_deposited()) + fn reserve_asset_deposited(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::reserve_asset_deposited()) } - fn receive_teleported_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::receive_teleported_asset()) + fn receive_teleported_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::receive_teleported_asset()) } fn query_response( _query_id: &u64, _response: &Response, _max_weight: &Weight, - _querier: &Option, + _querier: &Option, ) -> Weight { XcmGeneric::::query_response() } - fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_asset()) + fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::transfer_asset()) } - fn transfer_reserve_asset( - assets: &MultiAssets, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_reserve_asset()) + fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } fn transact( _origin_type: &OriginKind, @@ -110,44 +106,40 @@ impl XcmWeightInfo for BridgeHubPolkadotXcmWeight { fn clear_origin() -> Weight { XcmGeneric::::clear_origin() } - fn descend_origin(_who: &InteriorMultiLocation) -> Weight { + fn descend_origin(_who: &InteriorLocation) -> Weight { XcmGeneric::::descend_origin() } fn report_error(_query_response_info: &QueryResponseInfo) -> Weight { XcmGeneric::::report_error() } - fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_asset()) + fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::deposit_asset()) } - fn deposit_reserve_asset( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_reserve_asset()) + fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::deposit_reserve_asset()) } - fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight { + fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight { Weight::MAX } fn initiate_reserve_withdraw( - assets: &MultiAssetFilter, - _reserve: &MultiLocation, + assets: &AssetFilter, + _reserve: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) + assets.weigh_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) } fn initiate_teleport( - assets: &MultiAssetFilter, - _dest: &MultiLocation, + assets: &AssetFilter, + _dest: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_teleport()) + assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } - fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight { + fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } - fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight { + fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } fn refund_surplus() -> Weight { @@ -162,7 +154,7 @@ impl XcmWeightInfo for BridgeHubPolkadotXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } - fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight { + fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } fn trap(_code: &u64) -> Weight { @@ -174,13 +166,13 @@ impl XcmWeightInfo for BridgeHubPolkadotXcmWeight { fn unsubscribe_version() -> Weight { XcmGeneric::::unsubscribe_version() } - fn burn_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + fn burn_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::burn_asset()) } - fn expect_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + fn expect_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::expect_asset()) } - fn expect_origin(_origin: &Option) -> Weight { + fn expect_origin(_origin: &Option) -> Weight { XcmGeneric::::expect_origin() } fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { @@ -213,16 +205,16 @@ impl XcmWeightInfo for BridgeHubPolkadotXcmWeight { fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight { Weight::MAX } - fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn lock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn unlock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn note_unlockable(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn request_unlock(_: &Asset, _: &Location) -> Weight { Weight::MAX } fn set_fees_mode(_: &bool) -> Weight { @@ -234,11 +226,11 @@ impl XcmWeightInfo for BridgeHubPolkadotXcmWeight { fn clear_topic() -> Weight { XcmGeneric::::clear_topic() } - fn alias_origin(_: &MultiLocation) -> Weight { + fn alias_origin(_: &Location) -> Weight { // XCM Executor does not currently support alias origin operations Weight::MAX } - fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { + fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/xcm_config.rs index 61eee1c4c5a7..b7add10f0717 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/xcm_config.rs @@ -20,7 +20,7 @@ use super::{ CENTS, }; use frame_support::{ - match_types, parameter_types, + parameter_types, traits::{ConstU32, Contains, Everything, Nothing}, }; use frame_system::EnsureRoot; @@ -40,18 +40,18 @@ use xcm_builder::{ use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; parameter_types! { - pub const DotRelayLocation: MultiLocation = MultiLocation::parent(); + pub const DotRelayLocation: Location = Location::parent(); pub const RelayNetwork: Option = Some(NetworkId::Polkadot); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = - X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocation: InteriorLocation = + [GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into(); pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 64; - pub FellowshipLocation: MultiLocation = MultiLocation::new(1, Parachain(1001)); - pub const GovernanceLocation: MultiLocation = MultiLocation::parent(); + pub FellowshipLocation: Location = Location::new(1, Parachain(1001)); + pub const GovernanceLocation: Location = Location::parent(); } -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( @@ -69,7 +69,7 @@ pub type CurrencyTransactor = CurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: + // Do a simple punn to convert an AccountId32 Location into a native chain account ID: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -101,19 +101,27 @@ pub type XcmOriginToTransactDispatchOrigin = ( XcmPassthrough, ); -match_types! { - pub type ParentOrParentsPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { .. }) } - }; - pub type ParentOrSiblings: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(_) } - }; - pub type FellowsPlurality: impl Contains = { - MultiLocation { parents: 1, interior: X2(Parachain(1001), Plurality { id: BodyId::Technical, ..}) } - }; +pub struct ParentOrParentsPlurality; +impl Contains for ParentOrParentsPlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [Plurality { .. }])) + } +} + +pub struct ParentOrSiblings; +impl Contains for ParentOrSiblings { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [_])) + } } + +pub struct FellowsPlurality; +impl Contains for FellowsPlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, [Parachain(1001), Plurality { id: BodyId::Technical, .. }])) + } +} + /// A call filter for the XCM Transact instruction. This is a temporary measure until we properly /// account for proof size weights. /// @@ -222,13 +230,13 @@ impl xcm_executor::Config for XcmConfig { type Aliasers = Nothing; } -/// Converts a local signed origin into an XCM multilocation. +/// Converts a local signed origin into an XCM location. /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; parameter_types! { /// The asset ID for the asset that we use to pay for message delivery fees. - pub FeeAssetId: AssetId = Concrete(DotRelayLocation::get()); + pub FeeAssetId: AssetId = AssetId(DotRelayLocation::get()); /// The base fee for the message delivery fees. pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_rococo_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_rococo_config.rs index 35497c840684..d1d04a9e8cd9 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_rococo_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_rococo_config.rs @@ -43,7 +43,7 @@ use frame_support::{parameter_types, traits::PalletInfoAccess}; use sp_runtime::RuntimeDebug; use xcm::{ latest::prelude::*, - prelude::{InteriorMultiLocation, NetworkId}, + prelude::{InteriorLocation, NetworkId}, }; use xcm_builder::{BridgeBlobDispatcher, HaulBlobExporter}; @@ -53,8 +53,8 @@ parameter_types! { pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = bp_bridge_hub_wococo::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; pub const BridgeHubRococoChainId: bp_runtime::ChainId = bp_runtime::BRIDGE_HUB_ROCOCO_CHAIN_ID; - pub BridgeHubWococoUniversalLocation: InteriorMultiLocation = X2(GlobalConsensus(Wococo), Parachain(ParachainInfo::parachain_id().into())); - pub BridgeWococoToRococoMessagesPalletInstance: InteriorMultiLocation = X1(PalletInstance(::index() as u8)); + pub BridgeHubWococoUniversalLocation: InteriorLocation = [GlobalConsensus(Wococo), Parachain(ParachainInfo::parachain_id().into())].into(); + pub BridgeWococoToRococoMessagesPalletInstance: InteriorLocation = [PalletInstance(::index() as u8)].into(); pub RococoGlobalConsensusNetwork: NetworkId = NetworkId::Rococo; pub ActiveOutboundLanesToBridgeHubRococo: &'static [bp_messages::LaneId] = &[XCM_LANE_FOR_ASSET_HUB_WOCOCO_TO_ASSET_HUB_ROCOCO]; pub const AssetHubWococoToAssetHubRococoMessagesLane: bp_messages::LaneId = XCM_LANE_FOR_ASSET_HUB_WOCOCO_TO_ASSET_HUB_ROCOCO; @@ -65,7 +65,7 @@ parameter_types! { pub AssetHubRococoParaId: cumulus_primitives_core::ParaId = bp_asset_hub_rococo::ASSET_HUB_ROCOCO_PARACHAIN_ID.into(); pub FromAssetHubWococoToAssetHubRococoRoute: SenderAndLane = SenderAndLane::new( - ParentThen(X1(Parachain(AssetHubWococoParaId::get().into()))).into(), + ParentThen([Parachain(AssetHubWococoParaId::get().into())].into()).into(), XCM_LANE_FOR_ASSET_HUB_WOCOCO_TO_ASSET_HUB_ROCOCO, ); @@ -309,9 +309,9 @@ mod tests { assert_eq!( BridgeWococoToRococoMessagesPalletInstance::get(), - X1(PalletInstance( + Junctions::from([PalletInstance( bp_bridge_hub_wococo::WITH_BRIDGE_WOCOCO_TO_ROCOCO_MESSAGES_PALLET_INDEX - )) + )]) ); } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs index 36dcab09dea7..38ee27ec5feb 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs @@ -44,7 +44,7 @@ use frame_support::{parameter_types, traits::PalletInfoAccess}; use sp_runtime::RuntimeDebug; use xcm::{ latest::prelude::*, - prelude::{InteriorMultiLocation, NetworkId}, + prelude::{InteriorLocation, NetworkId}, }; use xcm_builder::{BridgeBlobDispatcher, HaulBlobExporter}; @@ -54,8 +54,8 @@ parameter_types! { pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = bp_bridge_hub_rococo::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; pub const BridgeHubWestendChainId: bp_runtime::ChainId = bp_runtime::BRIDGE_HUB_WESTEND_CHAIN_ID; - pub BridgeRococoToWestendMessagesPalletInstance: InteriorMultiLocation = X1(PalletInstance(::index() as u8)); - pub BridgeHubRococoUniversalLocation: InteriorMultiLocation = X2(GlobalConsensus(Rococo), Parachain(ParachainInfo::parachain_id().into())); + pub BridgeRococoToWestendMessagesPalletInstance: InteriorLocation = [PalletInstance(::index() as u8)].into(); + pub BridgeHubRococoUniversalLocation: InteriorLocation = [GlobalConsensus(Rococo), Parachain(ParachainInfo::parachain_id().into())].into(); pub WestendGlobalConsensusNetwork: NetworkId = NetworkId::Westend; pub ActiveOutboundLanesToBridgeHubWestend: &'static [bp_messages::LaneId] = &[XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND]; pub const AssetHubRococoToAssetHubWestendMessagesLane: bp_messages::LaneId = XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND; @@ -66,7 +66,7 @@ parameter_types! { pub AssetHubWestendParaId: cumulus_primitives_core::ParaId = bp_asset_hub_westend::ASSET_HUB_WESTEND_PARACHAIN_ID.into(); pub FromAssetHubRococoToAssetHubWestendRoute: SenderAndLane = SenderAndLane::new( - ParentThen(X1(Parachain(AssetHubRococoParaId::get().into()))).into(), + ParentThen([Parachain(AssetHubRococoParaId::get().into())].into()).into(), XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND, ); @@ -312,11 +312,13 @@ mod tests { PriorityBoostPerMessage, >(FEE_BOOST_PER_MESSAGE); + let expected: InteriorLocation = [PalletInstance( + bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WESTEND_MESSAGES_PALLET_INDEX + )].into(); + assert_eq!( BridgeRococoToWestendMessagesPalletInstance::get(), - X1(PalletInstance( - bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WESTEND_MESSAGES_PALLET_INDEX - )) + expected, ); } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_wococo_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_wococo_config.rs index 7780b02632cb..e73ad4a715e3 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_wococo_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_wococo_config.rs @@ -44,7 +44,7 @@ use frame_support::{parameter_types, traits::PalletInfoAccess}; use sp_runtime::RuntimeDebug; use xcm::{ latest::prelude::*, - prelude::{InteriorMultiLocation, NetworkId}, + prelude::{InteriorLocation, NetworkId}, }; use xcm_builder::{BridgeBlobDispatcher, HaulBlobExporter}; @@ -54,8 +54,8 @@ parameter_types! { pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = bp_bridge_hub_rococo::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; pub const BridgeHubWococoChainId: bp_runtime::ChainId = bp_runtime::BRIDGE_HUB_WOCOCO_CHAIN_ID; - pub BridgeRococoToWococoMessagesPalletInstance: InteriorMultiLocation = X1(PalletInstance(::index() as u8)); - pub BridgeHubRococoUniversalLocation: InteriorMultiLocation = X2(GlobalConsensus(Rococo), Parachain(ParachainInfo::parachain_id().into())); + pub BridgeRococoToWococoMessagesPalletInstance: InteriorLocation = [PalletInstance(::index() as u8)].into(); + pub BridgeHubRococoUniversalLocation: InteriorLocation = [GlobalConsensus(Rococo), Parachain(ParachainInfo::parachain_id().into())].into(); pub WococoGlobalConsensusNetwork: NetworkId = NetworkId::Wococo; pub ActiveOutboundLanesToBridgeHubWococo: &'static [bp_messages::LaneId] = &[XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WOCOCO]; pub const AssetHubRococoToAssetHubWococoMessagesLane: bp_messages::LaneId = XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WOCOCO; @@ -66,7 +66,7 @@ parameter_types! { pub AssetHubWococoParaId: cumulus_primitives_core::ParaId = bp_asset_hub_wococo::ASSET_HUB_WOCOCO_PARACHAIN_ID.into(); pub FromAssetHubRococoToAssetHubWococoRoute: SenderAndLane = SenderAndLane::new( - ParentThen(X1(Parachain(AssetHubRococoParaId::get().into()))).into(), + ParentThen([Parachain(AssetHubRococoParaId::get().into())].into()).into(), XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WOCOCO, ); @@ -310,9 +310,9 @@ mod tests { assert_eq!( BridgeRococoToWococoMessagesPalletInstance::get(), - X1(PalletInstance( + Junctions::from([PalletInstance( bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WOCOCO_MESSAGES_PALLET_INDEX - )) + )]) ); } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs index b17d308b8915..fe89241ceebc 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs @@ -388,7 +388,7 @@ impl cumulus_pallet_aura_ext::Config for Runtime {} parameter_types! { /// The asset ID for the asset that we use to pay for message delivery fees. - pub FeeAssetId: AssetId = Concrete(xcm_config::TokenLocation::get()); + pub FeeAssetId: AssetId = AssetId(xcm_config::TokenLocation::get()); /// The base fee for the message delivery fees. pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); } @@ -983,22 +983,22 @@ impl_runtime_apis! { use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsiscsBenchmark; impl pallet_xcm::benchmarking::Config for Runtime { - fn reachable_dest() -> Option { + fn reachable_dest() -> Option { Some(Parent.into()) } - fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { // Relay/native token can be teleported between BH and Relay. Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Parent.into()) + id: AssetId(Parent.into()) }, Parent.into(), )) } - fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { // Reserve transfers are disabled on BH. None } @@ -1008,7 +1008,7 @@ impl_runtime_apis! { use xcm_config::TokenLocation; parameter_types! { - pub ExistentialDepositMultiAsset: Option = Some(( + pub ExistentialDepositAsset: Option = Some(( TokenLocation::get(), ExistentialDeposit::get() ).into()); @@ -1018,18 +1018,18 @@ impl_runtime_apis! { type XcmConfig = xcm_config::XcmConfig; type AccountIdConverter = xcm_config::LocationToAccountId; type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< - xcm_config::XcmConfig, - ExistentialDepositMultiAsset, + xcm_config::XcmConfig, + ExistentialDepositAsset, xcm_config::PriceForParentDelivery, >; - fn valid_destination() -> Result { + fn valid_destination() -> Result { Ok(TokenLocation::get()) } - fn worst_case_holding(_depositable_count: u32) -> MultiAssets { + fn worst_case_holding(_depositable_count: u32) -> Assets { // just concrete assets according to relay chain. - let assets: Vec = vec![ - MultiAsset { - id: Concrete(TokenLocation::get()), + let assets: Vec = vec![ + Asset { + id: AssetId(TokenLocation::get()), fun: Fungible(1_000_000 * UNITS), } ]; @@ -1038,12 +1038,12 @@ impl_runtime_apis! { } parameter_types! { - pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + pub const TrustedTeleporter: Option<(Location, Asset)> = Some(( TokenLocation::get(), - MultiAsset { fun: Fungible(UNITS), id: Concrete(TokenLocation::get()) }, + Asset { fun: Fungible(UNITS), id: AssetId(TokenLocation::get()) }, )); pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None; - pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None; + pub const TrustedReserve: Option<(Location, Asset)> = None; } impl pallet_xcm_benchmarks::fungible::Config for Runtime { @@ -1053,9 +1053,9 @@ impl_runtime_apis! { type TrustedTeleporter = TrustedTeleporter; type TrustedReserve = TrustedReserve; - fn get_multi_asset() -> MultiAsset { - MultiAsset { - id: Concrete(TokenLocation::get()), + fn get_asset() -> Asset { + Asset { + id: AssetId(TokenLocation::get()), fun: Fungible(UNITS), } } @@ -1069,39 +1069,39 @@ impl_runtime_apis! { (0u64, Response::Version(Default::default())) } - fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> { Err(BenchmarkError::Skip) } - fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + fn universal_alias() -> Result<(Location, Junction), BenchmarkError> { Err(BenchmarkError::Skip) } - fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> { + fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> { Ok((TokenLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) } - fn subscribe_origin() -> Result { + fn subscribe_origin() -> Result { Ok(TokenLocation::get()) } - fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { + fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> { let origin = TokenLocation::get(); - let assets: MultiAssets = (Concrete(TokenLocation::get()), 1_000 * UNITS).into(); - let ticket = MultiLocation { parents: 0, interior: Here }; + let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into(); + let ticket = Location { parents: 0, interior: Here }; Ok((origin, ticket, assets)) } - fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { + fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> { Err(BenchmarkError::Skip) } fn export_message_origin_and_destination( - ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { - Ok((TokenLocation::get(), NetworkId::Wococo, X1(Parachain(100)))) + ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> { + Ok((TokenLocation::get(), NetworkId::Wococo, [Parachain(100)].into())) } - fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { + fn alias_origin() -> Result<(Location, Location), BenchmarkError> { Err(BenchmarkError::Skip) } } @@ -1154,7 +1154,7 @@ impl_runtime_apis! { Runtime, bridge_common_config::BridgeGrandpaWococoInstance, bridge_to_wococo_config::WithBridgeHubWococoMessageBridge, - >(params, generate_xcm_builder_bridge_message_sample(X2(GlobalConsensus(Rococo), Parachain(42)))) + >(params, generate_xcm_builder_bridge_message_sample([GlobalConsensus(Rococo), Parachain(42)].into())) } fn prepare_message_delivery_proof( @@ -1197,7 +1197,7 @@ impl_runtime_apis! { Runtime, bridge_common_config::BridgeGrandpaWestendInstance, bridge_to_westend_config::WithBridgeHubWestendMessageBridge, - >(params, generate_xcm_builder_bridge_message_sample(X2(GlobalConsensus(Rococo), Parachain(42)))) + >(params, generate_xcm_builder_bridge_message_sample([GlobalConsensus(Rococo), Parachain(42)].into())) } fn prepare_message_delivery_proof( @@ -1240,7 +1240,7 @@ impl_runtime_apis! { Runtime, bridge_common_config::BridgeGrandpaRococoInstance, bridge_to_rococo_config::WithBridgeHubRococoMessageBridge, - >(params, generate_xcm_builder_bridge_message_sample(X2(GlobalConsensus(Wococo), Parachain(42)))) + >(params, generate_xcm_builder_bridge_message_sample([GlobalConsensus(Wococo), Parachain(42)].into())) } fn prepare_message_delivery_proof( diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/mod.rs index 1c2334a89e25..4f5bae0fe597 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/mod.rs @@ -24,14 +24,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; -trait WeighMultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight; +trait WeighAssets { + fn weigh_assets(&self, weight: Weight) -> Weight; } const MAX_ASSETS: u64 = 100; -impl WeighMultiAssets for MultiAssetFilter { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for AssetFilter { + fn weigh_assets(&self, weight: Weight) -> Weight { match self { Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64), Self::Wild(asset) => match asset { @@ -50,40 +50,36 @@ impl WeighMultiAssets for MultiAssetFilter { } } -impl WeighMultiAssets for MultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for Assets { + fn weigh_assets(&self, weight: Weight) -> Weight { weight.saturating_mul(self.inner().iter().count() as u64) } } pub struct BridgeHubRococoXcmWeight(core::marker::PhantomData); impl XcmWeightInfo for BridgeHubRococoXcmWeight { - fn withdraw_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::withdraw_asset()) + fn withdraw_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::withdraw_asset()) } - fn reserve_asset_deposited(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::reserve_asset_deposited()) + fn reserve_asset_deposited(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::reserve_asset_deposited()) } - fn receive_teleported_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::receive_teleported_asset()) + fn receive_teleported_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::receive_teleported_asset()) } fn query_response( _query_id: &u64, _response: &Response, _max_weight: &Weight, - _querier: &Option, + _querier: &Option, ) -> Weight { XcmGeneric::::query_response() } - fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_asset()) + fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::transfer_asset()) } - fn transfer_reserve_asset( - assets: &MultiAssets, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_reserve_asset()) + fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } fn transact( _origin_type: &OriginKind, @@ -111,44 +107,36 @@ impl XcmWeightInfo for BridgeHubRococoXcmWeight { fn clear_origin() -> Weight { XcmGeneric::::clear_origin() } - fn descend_origin(_who: &InteriorMultiLocation) -> Weight { + fn descend_origin(_who: &InteriorLocation) -> Weight { XcmGeneric::::descend_origin() } fn report_error(_query_response_info: &QueryResponseInfo) -> Weight { XcmGeneric::::report_error() } - fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_asset()) + fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::deposit_asset()) } - fn deposit_reserve_asset( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_reserve_asset()) + fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::deposit_reserve_asset()) } - fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight { + fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight { Weight::MAX } fn initiate_reserve_withdraw( - assets: &MultiAssetFilter, - _reserve: &MultiLocation, + assets: &AssetFilter, + _reserve: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) + assets.weigh_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) } - fn initiate_teleport( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_teleport()) + fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } - fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight { + fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } - fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight { + fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } fn refund_surplus() -> Weight { @@ -163,7 +151,7 @@ impl XcmWeightInfo for BridgeHubRococoXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } - fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight { + fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } fn trap(_code: &u64) -> Weight { @@ -175,13 +163,13 @@ impl XcmWeightInfo for BridgeHubRococoXcmWeight { fn unsubscribe_version() -> Weight { XcmGeneric::::unsubscribe_version() } - fn burn_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + fn burn_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::burn_asset()) } - fn expect_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + fn expect_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::expect_asset()) } - fn expect_origin(_origin: &Option) -> Weight { + fn expect_origin(_origin: &Option) -> Weight { XcmGeneric::::expect_origin() } fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { @@ -215,16 +203,16 @@ impl XcmWeightInfo for BridgeHubRococoXcmWeight { let inner_encoded_len = inner.encode().len() as u32; XcmGeneric::::export_message(inner_encoded_len) } - fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn lock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn unlock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn note_unlockable(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn request_unlock(_: &Asset, _: &Location) -> Weight { Weight::MAX } fn set_fees_mode(_: &bool) -> Weight { @@ -236,11 +224,11 @@ impl XcmWeightInfo for BridgeHubRococoXcmWeight { fn clear_topic() -> Weight { XcmGeneric::::clear_topic() } - fn alias_origin(_: &MultiLocation) -> Weight { + fn alias_origin(_: &Location) -> Weight { // XCM Executor does not currently support alias origin operations Weight::MAX } - fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { + fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs index 1b1e6f8ba71f..0936ede7b01e 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs @@ -27,7 +27,7 @@ use bp_messages::LaneId; use bp_relayers::{PayRewardFromAccount, RewardsAccountOwner, RewardsAccountParams}; use bp_runtime::ChainId; use frame_support::{ - match_types, parameter_types, + parameter_types, traits::{ConstU32, Contains, Equals, Everything, Nothing}, }; use frame_system::EnsureRoot; @@ -61,14 +61,14 @@ use xcm_executor::{ parameter_types! { pub storage Flavor: RuntimeFlavor = RuntimeFlavor::default(); - pub const TokenLocation: MultiLocation = MultiLocation::parent(); + pub const TokenLocation: Location = Location::parent(); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = - X2(GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocation: InteriorLocation = + [GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into(); pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 64; pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating(); - pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into(); + pub RelayTreasuryLocation: Location = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into(); } /// Adapter for resolving `NetworkId` based on `pub storage Flavor: RuntimeFlavor`. @@ -87,7 +87,7 @@ impl Get for RelayNetwork { } } -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( @@ -105,7 +105,7 @@ pub type CurrencyTransactor = CurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: + // Do a simple punn to convert an AccountId32 Location into a native chain account ID: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -137,15 +137,18 @@ pub type XcmOriginToTransactDispatchOrigin = ( XcmPassthrough, ); -match_types! { - pub type ParentOrParentsPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { .. }) } - }; - pub type ParentOrSiblings: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(_) } - }; +pub struct ParentOrParentsPlurality; +impl Contains for ParentOrParentsPlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [Plurality { .. }])) + } +} + +pub struct ParentOrSiblings; +impl Contains for ParentOrSiblings { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [_])) + } } /// A call filter for the XCM Transact instruction. This is a temporary measure until we properly @@ -244,18 +247,15 @@ pub type Barrier = TrailingSetTopicAsId< >, >; -match_types! { - pub type SystemParachains: impl Contains = { - MultiLocation { - parents: 1, - interior: X1(Parachain( - system_parachain::ASSET_HUB_ID | - system_parachain::BRIDGE_HUB_ID | - system_parachain::CONTRACTS_ID | - system_parachain::ENCOINTER_ID - )), - } - }; +pub struct SystemParachains; +impl Contains for SystemParachains { + fn contains(location: &Location) -> bool { + use system_parachain::{ASSET_HUB_ID, BRIDGE_HUB_ID, CONTRACTS_ID, ENCOINTER_ID}; + matches!( + location.unpack(), + (1, [Parachain(ASSET_HUB_ID | BRIDGE_HUB_ID | CONTRACTS_ID | ENCOINTER_ID)]) + ) + } } /// Locations that will not be charged fees in the executor, @@ -336,7 +336,7 @@ impl xcm_executor::Config for XcmConfig { pub type PriceForParentDelivery = ExponentialPrice; -/// Converts a local signed origin into an XCM multilocation. +/// Converts a local signed origin into an XCM location. /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; @@ -413,13 +413,13 @@ impl< > { fn handle_fee( - fee: MultiAssets, + fee: Assets, maybe_context: Option<&XcmContext>, reason: FeeReason, - ) -> MultiAssets { + ) -> Assets { if matches!(reason, FeeReason::Export { network: bridged_network, destination } if bridged_network == DestNetwork::get() && - destination == X1(Parachain(DestParaId::get().into()))) + destination == [Parachain(DestParaId::get().into())]) { // We have 2 relayer rewards accounts: // - the SA of the source parachain on this BH: this pays the relayers for delivering @@ -450,14 +450,14 @@ impl< Fungible(total_fee) => { let source_fee = total_fee / 2; deposit_or_burn_fee::( - MultiAsset { id: asset.id, fun: Fungible(source_fee) }.into(), + Asset { id: asset.id.clone(), fun: Fungible(source_fee) }.into(), maybe_context, source_para_account.clone(), ); let dest_fee = total_fee - source_fee; deposit_or_burn_fee::( - MultiAsset { id: asset.id, fun: Fungible(dest_fee) }.into(), + Asset { id: asset.id, fun: Fungible(dest_fee) }.into(), maybe_context, dest_para_account.clone(), ); @@ -472,7 +472,7 @@ impl< } } - return MultiAssets::new() + return Assets::new() } fee diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs index 39ee2576f5bd..6fb4c45e2c1f 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs @@ -210,7 +210,7 @@ mod bridge_hub_rococo_tests { _ => None, } }), - || ExportMessage { network: Wococo, destination: X1(Parachain(1234)), xcm: Xcm(vec![]) }, + || ExportMessage { network: Wococo, destination: [Parachain(1234)].into(), xcm: Xcm(vec![]) }, XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WOCOCO, Some((TokenLocation::get(), ExistentialDeposit::get()).into()), // value should be >= than value generated by `can_calculate_weight_for_paid_export_message_with_reserve_transfer` @@ -232,7 +232,7 @@ mod bridge_hub_rococo_tests { _ => None, } }), - || ExportMessage { network: Westend, destination: X1(Parachain(1234)), xcm: Xcm(vec![]) }, + || ExportMessage { network: Westend, destination: [Parachain(1234)].into(), xcm: Xcm(vec![]) }, XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND, Some((TokenLocation::get(), ExistentialDeposit::get()).into()), // value should be >= than value generated by `can_calculate_weight_for_paid_export_message_with_reserve_transfer` @@ -577,7 +577,7 @@ mod bridge_hub_wococo_tests { _ => None, } }), - || ExportMessage { network: Rococo, destination: X1(Parachain(4321)), xcm: Xcm(vec![]) }, + || ExportMessage { network: Rococo, destination: [Parachain(4321)].into(), xcm: Xcm(vec![]) }, XCM_LANE_FOR_ASSET_HUB_WOCOCO_TO_ASSET_HUB_ROCOCO, Some((TokenLocation::get(), ExistentialDeposit::get()).into()), // value should be >= than value generated by `can_calculate_weight_for_paid_export_message_with_reserve_transfer` diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs index 70ff43c09e3f..04868a32843b 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs @@ -46,7 +46,7 @@ use frame_support::{ use sp_runtime::RuntimeDebug; use xcm::{ latest::prelude::*, - prelude::{InteriorMultiLocation, NetworkId}, + prelude::{InteriorLocation, NetworkId}, }; use xcm_builder::{BridgeBlobDispatcher, HaulBlobExporter}; @@ -62,8 +62,8 @@ parameter_types! { pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = bp_bridge_hub_westend::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; pub const BridgeHubRococoChainId: bp_runtime::ChainId = bp_runtime::BRIDGE_HUB_ROCOCO_CHAIN_ID; - pub BridgeHubWestendUniversalLocation: InteriorMultiLocation = X2(GlobalConsensus(Westend), Parachain(ParachainInfo::parachain_id().into())); - pub BridgeWestendToRococoMessagesPalletInstance: InteriorMultiLocation = X1(PalletInstance(::index() as u8)); + pub BridgeHubWestendUniversalLocation: InteriorLocation = [GlobalConsensus(Westend), Parachain(ParachainInfo::parachain_id().into())].into(); + pub BridgeWestendToRococoMessagesPalletInstance: InteriorLocation = [PalletInstance(::index() as u8)].into(); pub RococoGlobalConsensusNetwork: NetworkId = NetworkId::Rococo; pub ActiveOutboundLanesToBridgeHubRococo: &'static [bp_messages::LaneId] = &[XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO]; pub const AssetHubWestendToAssetHubRococoMessagesLane: bp_messages::LaneId = XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO; @@ -73,7 +73,7 @@ parameter_types! { pub AssetHubWestendParaId: cumulus_primitives_core::ParaId = bp_asset_hub_westend::ASSET_HUB_WESTEND_PARACHAIN_ID.into(); pub FromAssetHubWestendToAssetHubRococoRoute: SenderAndLane = SenderAndLane::new( - ParentThen(X1(Parachain(AssetHubWestendParaId::get().into()))).into(), + ParentThen([Parachain(AssetHubWestendParaId::get().into())].into()).into(), XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO, ); @@ -339,9 +339,9 @@ mod tests { assert_eq!( BridgeWestendToRococoMessagesPalletInstance::get(), - X1(PalletInstance( + [PalletInstance( bp_bridge_hub_westend::WITH_BRIDGE_WESTEND_TO_ROCOCO_MESSAGES_PALLET_INDEX - )) + )] ); } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs index 9e8fd84e7125..45fcf6e4242e 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs @@ -365,7 +365,7 @@ impl cumulus_pallet_aura_ext::Config for Runtime {} parameter_types! { /// The asset ID for the asset that we use to pay for message delivery fees. - pub FeeAssetId: AssetId = Concrete(xcm_config::WestendLocation::get()); + pub FeeAssetId: AssetId = AssetId(xcm_config::WestendLocation::get()); /// The base fee for the message delivery fees. pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); } @@ -816,22 +816,22 @@ impl_runtime_apis! { use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsiscsBenchmark; impl pallet_xcm::benchmarking::Config for Runtime { - fn reachable_dest() -> Option { + fn reachable_dest() -> Option { Some(Parent.into()) } - fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { // Relay/native token can be teleported between BH and Relay. Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Parent.into()) + id: AssetId(Parent.into()) }, Parent.into(), )) } - fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { // Reserve transfers are disabled on BH. None } @@ -841,7 +841,7 @@ impl_runtime_apis! { use xcm_config::WestendLocation; parameter_types! { - pub ExistentialDepositMultiAsset: Option = Some(( + pub ExistentialDepositAsset: Option = Some(( WestendLocation::get(), ExistentialDeposit::get() ).into()); @@ -852,17 +852,17 @@ impl_runtime_apis! { type AccountIdConverter = xcm_config::LocationToAccountId; type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< xcm_config::XcmConfig, - ExistentialDepositMultiAsset, + ExistentialDepositAsset, xcm_config::PriceForParentDelivery, >; - fn valid_destination() -> Result { + fn valid_destination() -> Result { Ok(WestendLocation::get()) } - fn worst_case_holding(_depositable_count: u32) -> MultiAssets { - // just concrete assets according to relay chain. - let assets: Vec = vec![ - MultiAsset { - id: Concrete(WestendLocation::get()), + fn worst_case_holding(_depositable_count: u32) -> Assets { + // just assets according to relay chain. + let assets: Vec = vec![ + Asset { + id: AssetId(WestendLocation::get()), fun: Fungible(1_000_000 * UNITS), } ]; @@ -871,12 +871,12 @@ impl_runtime_apis! { } parameter_types! { - pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + pub const TrustedTeleporter: Option<(Location, Asset)> = Some(( WestendLocation::get(), - MultiAsset { fun: Fungible(UNITS), id: Concrete(WestendLocation::get()) }, + Asset { fun: Fungible(UNITS), id: AssetId(WestendLocation::get()) }, )); pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None; - pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None; + pub const TrustedReserve: Option<(Location, Asset)> = None; } impl pallet_xcm_benchmarks::fungible::Config for Runtime { @@ -886,9 +886,9 @@ impl_runtime_apis! { type TrustedTeleporter = TrustedTeleporter; type TrustedReserve = TrustedReserve; - fn get_multi_asset() -> MultiAsset { - MultiAsset { - id: Concrete(WestendLocation::get()), + fn get_asset() -> Asset { + Asset { + id: AssetId(WestendLocation::get()), fun: Fungible(UNITS), } } @@ -902,39 +902,39 @@ impl_runtime_apis! { (0u64, Response::Version(Default::default())) } - fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> { Err(BenchmarkError::Skip) } - fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + fn universal_alias() -> Result<(Location, Junction), BenchmarkError> { Err(BenchmarkError::Skip) } - fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> { + fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> { Ok((WestendLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) } - fn subscribe_origin() -> Result { + fn subscribe_origin() -> Result { Ok(WestendLocation::get()) } - fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { + fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> { let origin = WestendLocation::get(); - let assets: MultiAssets = (Concrete(WestendLocation::get()), 1_000 * UNITS).into(); - let ticket = MultiLocation { parents: 0, interior: Here }; + let assets: Assets = (AssetId(WestendLocation::get()), 1_000 * UNITS).into(); + let ticket = Location { parents: 0, interior: Here }; Ok((origin, ticket, assets)) } - fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { + fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> { Err(BenchmarkError::Skip) } fn export_message_origin_and_destination( - ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { - Ok((WestendLocation::get(), NetworkId::Rococo, X1(Parachain(100)))) + ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> { + Ok((WestendLocation::get(), NetworkId::Rococo, [Parachain(100)].into())) } - fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { + fn alias_origin() -> Result<(Location, Location), BenchmarkError> { Err(BenchmarkError::Skip) } } @@ -981,7 +981,7 @@ impl_runtime_apis! { Runtime, bridge_to_rococo_config::BridgeGrandpaRococoInstance, bridge_to_rococo_config::WithBridgeHubRococoMessageBridge, - >(params, generate_xcm_builder_bridge_message_sample(X2(GlobalConsensus(Westend), Parachain(42)))) + >(params, generate_xcm_builder_bridge_message_sample([GlobalConsensus(Westend), Parachain(42)].into())) } fn prepare_message_delivery_proof( diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs index 7269fa84f84a..6ec30903aa9b 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs @@ -25,14 +25,14 @@ use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; -trait WeighMultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight; +trait WeighAssets { + fn weigh_assets(&self, weight: Weight) -> Weight; } const MAX_ASSETS: u64 = 100; -impl WeighMultiAssets for MultiAssetFilter { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for AssetFilter { + fn weigh_assets(&self, weight: Weight) -> Weight { match self { Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64), Self::Wild(asset) => match asset { @@ -51,40 +51,40 @@ impl WeighMultiAssets for MultiAssetFilter { } } -impl WeighMultiAssets for MultiAssets { - fn weigh_multi_assets(&self, weight: Weight) -> Weight { +impl WeighAssets for Assets { + fn weigh_assets(&self, weight: Weight) -> Weight { weight.saturating_mul(self.inner().iter().count() as u64) } } pub struct BridgeHubWestendXcmWeight(core::marker::PhantomData); impl XcmWeightInfo for BridgeHubWestendXcmWeight { - fn withdraw_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::withdraw_asset()) + fn withdraw_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::withdraw_asset()) } - fn reserve_asset_deposited(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::reserve_asset_deposited()) + fn reserve_asset_deposited(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::reserve_asset_deposited()) } - fn receive_teleported_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::receive_teleported_asset()) + fn receive_teleported_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::receive_teleported_asset()) } fn query_response( _query_id: &u64, _response: &Response, _max_weight: &Weight, - _querier: &Option, + _querier: &Option, ) -> Weight { XcmGeneric::::query_response() } - fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_asset()) + fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::transfer_asset()) } fn transfer_reserve_asset( - assets: &MultiAssets, - _dest: &MultiLocation, + assets: &Assets, + _dest: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::transfer_reserve_asset()) + assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } fn transact( _origin_type: &OriginKind, @@ -112,44 +112,44 @@ impl XcmWeightInfo for BridgeHubWestendXcmWeight { fn clear_origin() -> Weight { XcmGeneric::::clear_origin() } - fn descend_origin(_who: &InteriorMultiLocation) -> Weight { + fn descend_origin(_who: &InteriorLocation) -> Weight { XcmGeneric::::descend_origin() } fn report_error(_query_response_info: &QueryResponseInfo) -> Weight { XcmGeneric::::report_error() } - fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_asset()) + fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight { + assets.weigh_assets(XcmFungibleWeight::::deposit_asset()) } fn deposit_reserve_asset( - assets: &MultiAssetFilter, - _dest: &MultiLocation, + assets: &AssetFilter, + _dest: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::deposit_reserve_asset()) + assets.weigh_assets(XcmFungibleWeight::::deposit_reserve_asset()) } - fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight { + fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight { Weight::MAX } fn initiate_reserve_withdraw( - assets: &MultiAssetFilter, - _reserve: &MultiLocation, + assets: &AssetFilter, + _reserve: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) + assets.weigh_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) } fn initiate_teleport( - assets: &MultiAssetFilter, - _dest: &MultiLocation, + assets: &AssetFilter, + _dest: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmFungibleWeight::::initiate_teleport()) + assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } - fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight { + fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } - fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight { + fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } fn refund_surplus() -> Weight { @@ -164,7 +164,7 @@ impl XcmWeightInfo for BridgeHubWestendXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } - fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight { + fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } fn trap(_code: &u64) -> Weight { @@ -176,13 +176,13 @@ impl XcmWeightInfo for BridgeHubWestendXcmWeight { fn unsubscribe_version() -> Weight { XcmGeneric::::unsubscribe_version() } - fn burn_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + fn burn_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::burn_asset()) } - fn expect_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + fn expect_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::expect_asset()) } - fn expect_origin(_origin: &Option) -> Weight { + fn expect_origin(_origin: &Option) -> Weight { XcmGeneric::::expect_origin() } fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { @@ -216,16 +216,16 @@ impl XcmWeightInfo for BridgeHubWestendXcmWeight { let inner_encoded_len = inner.encode().len() as u32; XcmGeneric::::export_message(inner_encoded_len) } - fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn lock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn unlock_asset(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn note_unlockable(_: &Asset, _: &Location) -> Weight { Weight::MAX } - fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn request_unlock(_: &Asset, _: &Location) -> Weight { Weight::MAX } fn set_fees_mode(_: &bool) -> Weight { @@ -237,11 +237,11 @@ impl XcmWeightInfo for BridgeHubWestendXcmWeight { fn clear_topic() -> Weight { XcmGeneric::::clear_topic() } - fn alias_origin(_: &MultiLocation) -> Weight { + fn alias_origin(_: &Location) -> Weight { // XCM Executor does not currently support alias origin operations Weight::MAX } - fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { + fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs index 7084882c41f9..8f46c154bbf0 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs @@ -21,7 +21,7 @@ use super::{ }; use crate::bridge_common_config::{DeliveryRewardInBalance, RequiredStakeForStakeAndSlash}; use frame_support::{ - match_types, parameter_types, + parameter_types, traits::{ConstU32, Contains, Equals, Everything, Nothing}, }; use frame_system::EnsureRoot; @@ -48,18 +48,18 @@ use xcm_builder::{ use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; parameter_types! { - pub const WestendLocation: MultiLocation = MultiLocation::parent(); + pub const WestendLocation: Location = Location::parent(); pub const RelayNetwork: NetworkId = NetworkId::Westend; pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = - X2(GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocation: InteriorLocation = + [GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into(); pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 64; pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating(); - pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into(); + pub RelayTreasuryLocation: Location = (Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into(); } -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( @@ -77,7 +77,7 @@ pub type CurrencyTransactor = CurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: + // Do a simple punn to convert an AccountId32 Location into a native chain account ID: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -109,15 +109,18 @@ pub type XcmOriginToTransactDispatchOrigin = ( XcmPassthrough, ); -match_types! { - pub type ParentOrParentsPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { .. }) } - }; - pub type ParentOrSiblings: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(_) } - }; +pub struct ParentOrParentsPlurality; +impl Contains for ParentOrParentsPlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [Plurality { .. }])) + } +} + +pub struct ParentOrSiblings; +impl Contains for ParentOrSiblings { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [_])) + } } /// A call filter for the XCM Transact instruction. This is a temporary measure until we properly @@ -207,17 +210,16 @@ pub type Barrier = TrailingSetTopicAsId< >, >; -match_types! { - pub type SystemParachains: impl Contains = { - MultiLocation { - parents: 1, - interior: X1(Parachain( - system_parachain::ASSET_HUB_ID | - system_parachain::BRIDGE_HUB_ID | - system_parachain::COLLECTIVES_ID - )), - } - }; +pub struct SystemParachains; +impl Contains for SystemParachains { + fn contains(location: &Location) -> bool { + use system_parachain::{ASSET_HUB_ID, BRIDGE_HUB_ID, COLLECTIVES_ID}; + + matches!( + location.unpack(), + (1, [Parachain(ASSET_HUB_ID | BRIDGE_HUB_ID | COLLECTIVES_ID)]) + ) + } } /// Locations that will not be charged fees in the executor, @@ -271,7 +273,7 @@ impl xcm_executor::Config for XcmConfig { pub type PriceForParentDelivery = ExponentialPrice; -/// Converts a local signed origin into an XCM multilocation. +/// Converts a local signed origin into an XCM location. /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs index 4d477e1413e4..29459cc21527 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs @@ -179,7 +179,7 @@ fn handle_export_message_from_system_parachain_add_to_outbound_queue_works() { _ => None, } }), - || ExportMessage { network: Rococo, destination: X1(Parachain(4321)), xcm: Xcm(vec![]) }, + || ExportMessage { network: Rococo, destination: [Parachain(4321)].into(), xcm: Xcm(vec![]) }, XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO, Some((WestendLocation::get(), ExistentialDeposit::get()).into()), // value should be >= than value generated by `can_calculate_weight_for_paid_export_message_with_reserve_transfer` diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases.rs index b421eea6bcf6..09774687b3c2 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases.rs @@ -146,8 +146,8 @@ pub fn handle_export_message_from_system_parachain_to_outbound_queue_works< >, export_message_instruction: fn() -> Instruction, expected_lane_id: LaneId, - existential_deposit: Option, - maybe_paid_export_message: Option, + existential_deposit: Option, + maybe_paid_export_message: Option, prepare_configuration: impl Fn(), ) where Runtime: frame_system::Config @@ -163,7 +163,7 @@ pub fn handle_export_message_from_system_parachain_to_outbound_queue_works< ValidatorIdOf: From>, { assert_ne!(runtime_para_id, sibling_parachain_id); - let sibling_parachain_location = MultiLocation::new(1, Parachain(sibling_parachain_id)); + let sibling_parachain_location = Location::new(1, Parachain(sibling_parachain_id)); ExtBuilder::::default() .with_collators(collator_session_key.collators()) @@ -202,7 +202,7 @@ pub fn handle_export_message_from_system_parachain_to_outbound_queue_works< .expect("deposited fee"); Xcm(vec![ - WithdrawAsset(MultiAssets::from(vec![fee.clone()])), + WithdrawAsset(Assets::from(vec![fee.clone()])), BuyExecution { fees: fee, weight_limit: Unlimited }, export_message_instruction(), ]) @@ -214,12 +214,13 @@ pub fn handle_export_message_from_system_parachain_to_outbound_queue_works< }; // execute XCM - let hash = xcm.using_encoded(sp_io::hashing::blake2_256); - assert_ok!(XcmExecutor::::execute_xcm( + let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256); + assert_ok!(XcmExecutor::::prepare_and_execute( sibling_parachain_location, xcm, - hash, + &mut hash, RuntimeHelper::::xcm_max_weight(XcmReceivedFrom::Sibling), + Weight::zero(), ) .ensure_complete()); @@ -336,7 +337,7 @@ pub fn message_dispatch_routing_works< // 2. this message is sent from other global consensus with destination of this Runtime sibling parachain (HRMP) let bridging_message = test_data::simulate_message_exporter_on_bridged_chain::( - (RuntimeNetwork::get(), X1(Parachain(sibling_parachain_id))), + (RuntimeNetwork::get(), [Parachain(sibling_parachain_id)].into()), ); // 2.1. WITHOUT opened hrmp channel -> RoutingError @@ -456,8 +457,8 @@ pub fn relayed_incoming_message_works::ClearOrigin; 42]; + let xcm = vec![xcm::latest::Instruction::<()>::ClearOrigin; 42]; let expected_dispatch = xcm::latest::Xcm::<()>({ let mut expected_instructions = xcm.clone(); // dispatch prepends bridge pallet instance expected_instructions.insert( 0, - DescendOrigin(X1(PalletInstance( + DescendOrigin([PalletInstance( as PalletInfoAccess>::index() as u8, - ))), + )].into()), ); expected_instructions }); @@ -707,8 +708,8 @@ pub fn complex_relay_extrinsic_works as PalletInfoAccess>::index() as u8, - ))), + )].into()), ); expected_instructions }); @@ -856,52 +857,43 @@ where { // data here are not relevant for weighing let mut xcm = Xcm(vec![ - WithdrawAsset(MultiAssets::from(vec![MultiAsset { - id: Concrete(MultiLocation { parents: 1, interior: Here }), + WithdrawAsset(Assets::from(vec![Asset { + id: Location::new(1, []).into(), fun: Fungible(34333299), }])), BuyExecution { - fees: MultiAsset { - id: Concrete(MultiLocation { parents: 1, interior: Here }), + fees: Asset { + id: Location::new(1, []).into(), fun: Fungible(34333299), }, weight_limit: Unlimited, }, ExportMessage { network: Polkadot, - destination: X1(Parachain(1000)), + destination: Parachain(1000).into(), xcm: Xcm(vec![ - ReserveAssetDeposited(MultiAssets::from(vec![MultiAsset { - id: Concrete(MultiLocation { - parents: 2, - interior: X1(GlobalConsensus(Kusama)), - }), + ReserveAssetDeposited(Assets::from(vec![Asset { + id: Location::new(2, [GlobalConsensus(Kusama)]).into(), fun: Fungible(1000000000000), }])), ClearOrigin, BuyExecution { - fees: MultiAsset { - id: Concrete(MultiLocation { - parents: 2, - interior: X1(GlobalConsensus(Kusama)), - }), + fees: Asset { + id: Location::new(2, [GlobalConsensus(Kusama)]).into(), fun: Fungible(1000000000000), }, weight_limit: Unlimited, }, DepositAsset { assets: Wild(AllCounted(1)), - beneficiary: MultiLocation { - parents: 0, - interior: X1(xcm::latest::prelude::AccountId32 { - network: None, - id: [ - 212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, - 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, - 109, 162, 125, - ], - }), - }, + beneficiary: Location::new(0, [xcm::latest::prelude::AccountId32 { + network: None, + id: [ + 212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, + 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, + 109, 162, 125, + ], + }]), }, SetTopic([ 116, 82, 194, 132, 171, 114, 217, 165, 23, 37, 161, 177, 165, 179, 247, 114, @@ -912,7 +904,7 @@ where RefundSurplus, DepositAsset { assets: Wild(All), - beneficiary: MultiLocation { parents: 1, interior: X1(Parachain(1000)) }, + beneficiary: Location::new(1, [Parachain(1000)]), }, SetTopic([ 36, 224, 250, 165, 82, 195, 67, 110, 160, 170, 140, 87, 217, 62, 201, 164, 42, 98, 219, @@ -1015,9 +1007,9 @@ where (), >( LaneId::default(), - vec![xcm::v3::Instruction::<()>::ClearOrigin; 1_024].into(), + vec![xcm::v4::Instruction::<()>::ClearOrigin; 1_024].into(), 1, - X2(GlobalConsensus(Polkadot), Parachain(1_000)), + [GlobalConsensus(Polkadot), Parachain(1_000)].into(), 1, 5, 1_000, @@ -1155,10 +1147,10 @@ pub mod test_data { pub fn prepare_inbound_xcm( xcm_message: Xcm, - destination: InteriorMultiLocation, + destination: InteriorLocation, ) -> Vec { - let location = xcm::VersionedInteriorMultiLocation::V3(destination); - let xcm = xcm::VersionedXcm::::V3(xcm_message); + let location = xcm::VersionedInteriorLocation::V4(destination); + let xcm = xcm::VersionedXcm::::V4(xcm_message); // this is the `BridgeMessage` from polkadot xcm builder, but it has no constructor // or public fields, so just tuple // (double encoding, because `.encode()` is called on original Xcm BLOB when it is pushed @@ -1532,8 +1524,8 @@ pub mod test_data { grab_haul_blob!(GrabbingHaulBlob, GRABBED_HAUL_BLOB_PAYLOAD); // lets pretend that some parachain on bridged chain exported the message - let universal_source_on_bridged_chain = - X2(GlobalConsensus(SourceNetwork::get()), Parachain(5678)); + let universal_source_on_bridged_chain: Junctions = + [GlobalConsensus(SourceNetwork::get()), Parachain(5678)].into(); let channel = 1_u32; // simulate XCM message export diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/mod.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/mod.rs index b055ffc8abf1..10fd28fe35c7 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/mod.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/mod.rs @@ -212,7 +212,7 @@ pub type AmbassadorSalaryInstance = pallet_salary::Instance2; parameter_types! { // The interior location on AssetHub for the paying account. This is the Ambassador Salary // pallet instance (which sits at index 74). This sovereign account will need funding. - pub AmbassadorSalaryLocation: InteriorMultiLocation = PalletInstance(74).into(); + pub AmbassadorSalaryLocation: InteriorLocation = PalletInstance(74).into(); } /// [`PayOverXcm`] setup to pay the Ambassador salary on the AssetHub in DOT. diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/mod.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/mod.rs index 2a2757ea5ceb..94e83673ca2c 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/mod.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/mod.rs @@ -40,7 +40,7 @@ use pallet_xcm::{EnsureXcm, IsVoiceOfBody}; use parachains_common::{polkadot::account, HOURS}; use sp_core::{ConstU128, ConstU32}; use sp_runtime::traits::{AccountIdConversion, ConstU16, ConvertToValue, Replace, TakeFirst}; -use xcm_builder::{AliasesIntoAccountId32, PayOverXcm}; +use xcm_builder::{AliasesIntoAccountId32, PayOverXcm, LocatableAssetId}; #[cfg(feature = "runtime-benchmarks")] use crate::impls::benchmarks::{OpenHrmpChannel, PayWithEnsure}; @@ -195,9 +195,15 @@ pub type FellowshipSalaryInstance = pallet_salary::Instance1; use xcm::prelude::*; parameter_types! { + pub AssetHub: Location = (Parent, Parachain(1000)).into(); + pub AssetHubUsdtId: AssetId = (PalletInstance(50), GeneralIndex(1984)).into(); + pub UsdtAsset: LocatableAssetId = LocatableAssetId { + location: AssetHub::get(), + asset_id: AssetHubUsdtId::get(), + }; // The interior location on AssetHub for the paying account. This is the Fellowship Salary // pallet instance (which sits at index 64). This sovereign account will need funding. - pub Interior: InteriorMultiLocation = PalletInstance(64).into(); + pub Interior: InteriorLocation = PalletInstance(64).into(); } const USDT_UNITS: u128 = 1_000_000; diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/lib.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/lib.rs index 206f46140606..450fb6bb4fd3 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/lib.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/lib.rs @@ -432,7 +432,7 @@ impl cumulus_pallet_aura_ext::Config for Runtime {} parameter_types! { /// The asset ID for the asset that we use to pay for message delivery fees. - pub FeeAssetId: AssetId = Concrete(xcm_config::DotLocation::get()); + pub FeeAssetId: AssetId = AssetId(xcm_config::DotLocation::get()); /// The base fee for the message delivery fees. pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); } @@ -971,22 +971,22 @@ impl_runtime_apis! { use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsiscsBenchmark; impl pallet_xcm::benchmarking::Config for Runtime { - fn reachable_dest() -> Option { + fn reachable_dest() -> Option { Some(Parent.into()) } - fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { // Relay/native token can be teleported between Collectives and Relay. Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Parent.into()) + id: AssetId(Parent.into()) }.into(), Parent.into(), )) } - fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { // Reserve transfers are disabled on Collectives. None } diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/xcm_config.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/xcm_config.rs index 71845650bd6c..f72c957abe92 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/xcm_config.rs @@ -19,7 +19,7 @@ use super::{ TransactionByteFee, WeightToFee, XcmpQueue, }; use frame_support::{ - match_types, parameter_types, + parameter_types, traits::{ConstU32, Contains, Everything, Nothing}, weights::Weight, }; @@ -43,16 +43,16 @@ use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; const FELLOWSHIP_ADMIN_INDEX: u32 = 1; parameter_types! { - pub const DotLocation: MultiLocation = MultiLocation::parent(); + pub const DotLocation: Location = Location::parent(); pub const RelayNetwork: Option = Some(NetworkId::Polkadot); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = - X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocation: InteriorLocation = + [GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into(); pub CheckingAccount: AccountId = PolkadotXcm::check_account(); - pub const GovernanceLocation: MultiLocation = MultiLocation::parent(); + pub const GovernanceLocation: Location = Location::parent(); pub const FellowshipAdminBodyId: BodyId = BodyId::Index(FELLOWSHIP_ADMIN_INDEX); - pub AssetHub: MultiLocation = (Parent, Parachain(1000)).into(); - pub AssetHubUsdtId: AssetId = (PalletInstance(50), GeneralIndex(1984)).into(); + pub AssetHub: Location = Location::new(1, [Parachain(1000)]); + pub AssetHubUsdtId: AssetId = [PalletInstance(50), GeneralIndex(1984)].into(); pub UsdtAssetHub: LocatableAssetId = LocatableAssetId { location: AssetHub::get(), asset_id: AssetHubUsdtId::get(), @@ -63,7 +63,7 @@ parameter_types! { }; } -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( @@ -81,7 +81,7 @@ pub type CurrencyTransactor = CurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -125,15 +125,18 @@ parameter_types! { pub const FellowsBodyId: BodyId = BodyId::Technical; } -match_types! { - pub type ParentOrParentsPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { .. }) } - }; - pub type ParentOrSiblings: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(_) } - }; +pub struct ParentOrParentsPlurality; +impl Contains for ParentOrParentsPlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [Plurality { .. }])) + } +} + +pub struct ParentOrSiblings; +impl Contains for ParentOrSiblings { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [_])) + } } /// A call filter for the XCM Transact instruction. This is a temporary measure until we properly @@ -277,7 +280,7 @@ impl xcm_executor::Config for XcmConfig { type Aliasers = Nothing; } -/// Converts a local signed origin into an XCM multilocation. +/// Converts a local signed origin into an XCM location. /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; @@ -293,7 +296,7 @@ pub type XcmRouter = WithUniqueTopic<( XcmpQueue, )>; -/// Type to convert the Fellows origin to a Plurality `MultiLocation` value. +/// Type to convert the Fellows origin to a Plurality `Location` value. pub type FellowsToPlurality = OriginToPluralityVoice; impl pallet_xcm::Config for Runtime { diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs index 2a2f41410337..91e07bd66a32 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs @@ -711,22 +711,22 @@ impl_runtime_apis! { use xcm::latest::prelude::*; use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsiscsBenchmark; impl pallet_xcm::benchmarking::Config for Runtime { - fn reachable_dest() -> Option { + fn reachable_dest() -> Option { Some(Parent.into()) } - fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { // Relay/native token can be teleported between Contracts-System-Para and Relay. Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Parent.into()) + id: AssetId(Parent.into()) }, Parent.into(), )) } - fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { // Reserve transfers are disabled on Contracts-System-Para. None } diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs index faee1c68fe6c..7f4878c3b9da 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs @@ -20,8 +20,8 @@ use super::{ use crate::common::rococo::currency::CENTS; use cumulus_primitives_core::AggregateMessageOrigin; use frame_support::{ - match_types, parameter_types, - traits::{ConstU32, EitherOfDiverse, Equals, Everything, Nothing}, + parameter_types, + traits::{ConstU32, Contains, EitherOfDiverse, Equals, Everything, Nothing}, weights::Weight, }; use frame_system::EnsureRoot; @@ -47,13 +47,13 @@ use xcm_builder::{ use xcm_executor::XcmExecutor; parameter_types! { - pub const RelayLocation: MultiLocation = MultiLocation::parent(); + pub const RelayLocation: Location = Location::parent(); pub const RelayNetwork: Option = None; pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); + pub UniversalLocation: InteriorLocation = Parachain(ParachainInfo::parachain_id().into()).into(); pub const ExecutiveBody: BodyId = BodyId::Executive; pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating(); - pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into(); + pub RelayTreasuryLocation: Location = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into(); } /// We allow root and the Relay Chain council to execute privileged collator selection operations. @@ -62,7 +62,7 @@ pub type CollatorSelectionUpdateOrigin = EitherOfDiverse< EnsureXcm>, >; -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( @@ -80,7 +80,7 @@ pub type CurrencyTransactor = CurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -118,15 +118,18 @@ parameter_types! { pub const MaxInstructions: u32 = 100; } -match_types! { - pub type ParentOrParentsPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { .. }) } - }; - pub type ParentOrSiblings: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(_) } - }; +pub struct ParentOrParentsPlurality; +impl Contains for ParentOrParentsPlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, []) | (1, [Plurality { .. }])) + } +} + +pub struct ParentOrSiblings; +impl Contains for ParentOrSiblings { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, []) | (1, [_])) + } } pub type Barrier = TrailingSetTopicAsId< @@ -158,18 +161,15 @@ pub type Barrier = TrailingSetTopicAsId< >, >; -match_types! { - pub type SystemParachains: impl Contains = { - MultiLocation { - parents: 1, - interior: X1(Parachain( - system_parachain::ASSET_HUB_ID | - system_parachain::BRIDGE_HUB_ID | - system_parachain::CONTRACTS_ID | - system_parachain::ENCOINTER_ID - )), - } - }; +pub struct SystemParachains; +impl Contains for SystemParachains { + fn contains(location: &Location) -> bool { + use system_parachain::{ASSET_HUB_ID, BRIDGE_HUB_ID, CONTRACTS_ID, ENCOINTER_ID}; + matches!( + location.unpack(), + (1, [Parachain(ASSET_HUB_ID | BRIDGE_HUB_ID | CONTRACTS_ID | ENCOINTER_ID)]) + ) + } } /// Locations that will not be charged fees in the executor, @@ -211,7 +211,7 @@ impl xcm_executor::Config for XcmConfig { type Aliasers = Nothing; } -/// Converts a local signed origin into an XCM multilocation. +/// Converts a local signed origin into an XCM location. /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; @@ -265,7 +265,7 @@ impl cumulus_pallet_xcm::Config for Runtime { parameter_types! { /// The asset ID for the asset that we use to pay for message delivery fees. - pub FeeAssetId: AssetId = Concrete(RelayLocation::get()); + pub FeeAssetId: AssetId = AssetId(RelayLocation::get()); /// The base fee for the message delivery fees. pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); } diff --git a/cumulus/parachains/runtimes/glutton/glutton-kusama/src/xcm_config.rs b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/xcm_config.rs index fb7b78b79d2a..b21b0676ac3e 100644 --- a/cumulus/parachains/runtimes/glutton/glutton-kusama/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/xcm_config.rs @@ -18,8 +18,8 @@ use super::{ RuntimeOrigin, }; use frame_support::{ - match_types, parameter_types, - traits::{Everything, Nothing}, + parameter_types, + traits::{Contains, Everything, Nothing}, weights::Weight, }; use xcm::latest::prelude::*; @@ -29,9 +29,9 @@ use xcm_builder::{ }; parameter_types! { - pub const KusamaLocation: MultiLocation = MultiLocation::parent(); + pub const KusamaLocation: Location = Location::parent(); pub const KusamaNetwork: Option = Some(NetworkId::Kusama); - pub UniversalLocation: InteriorMultiLocation = X1(Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocation: InteriorLocation = [Parachain(ParachainInfo::parachain_id().into())].into(); } /// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, @@ -47,8 +47,11 @@ pub type XcmOriginToTransactDispatchOrigin = ( ParentAsSuperuser, ); -match_types! { - pub type JustTheParent: impl Contains = { MultiLocation { parents:1, interior: Here } }; +pub struct JustTheParent; +impl Contains for JustTheParent { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE)) + } } parameter_types! { diff --git a/cumulus/parachains/runtimes/starters/shell/src/xcm_config.rs b/cumulus/parachains/runtimes/starters/shell/src/xcm_config.rs index ff773ca78161..f88056071c82 100644 --- a/cumulus/parachains/runtimes/starters/shell/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/starters/shell/src/xcm_config.rs @@ -18,8 +18,8 @@ use super::{ RuntimeOrigin, }; use frame_support::{ - match_types, parameter_types, - traits::{Everything, Nothing}, + parameter_types, + traits::{Contains, Everything, Nothing}, weights::Weight, }; use xcm::latest::prelude::*; @@ -29,9 +29,9 @@ use xcm_builder::{ }; parameter_types! { - pub const RococoLocation: MultiLocation = MultiLocation::parent(); + pub const RococoLocation: Location = Location::parent(); pub const RococoNetwork: Option = Some(NetworkId::Rococo); - pub UniversalLocation: InteriorMultiLocation = X1(Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocation: InteriorLocation = [Parachain(ParachainInfo::parachain_id().into())].into(); } /// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, @@ -47,8 +47,11 @@ pub type XcmOriginToTransactDispatchOrigin = ( ParentAsSuperuser, ); -match_types! { - pub type JustTheParent: impl Contains = { MultiLocation { parents:1, interior: Here } }; +pub struct JustTheParent; +impl Contains for JustTheParent { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE)) + } } parameter_types! { diff --git a/cumulus/parachains/runtimes/test-utils/src/lib.rs b/cumulus/parachains/runtimes/test-utils/src/lib.rs index e2a6fb45aec3..c334259b2514 100644 --- a/cumulus/parachains/runtimes/test-utils/src/lib.rs +++ b/cumulus/parachains/runtimes/test-utils/src/lib.rs @@ -37,11 +37,11 @@ use sp_consensus_aura::{SlotDuration, AURA_ENGINE_ID}; use sp_core::Encode; use sp_runtime::{traits::Header, BuildStorage, Digest, DigestItem}; use xcm::{ - latest::{MultiAsset, MultiLocation, XcmContext, XcmHash}, + latest::{Asset, Location, XcmContext, XcmHash}, prelude::*, VersionedXcm, MAX_XCM_DECODE_DEPTH, }; -use xcm_executor::{traits::TransactAsset, Assets}; +use xcm_executor::{traits::TransactAsset, AssetsInHolding}; pub mod test_cases; @@ -305,12 +305,12 @@ impl RuntimeHelper { pub fn do_transfer( - from: MultiLocation, - to: MultiLocation, - (asset, amount): (MultiLocation, u128), - ) -> Result { + from: Location, + to: Location, + (asset, amount): (Location, u128), + ) -> Result { ::transfer_asset( - &MultiAsset { id: Concrete(asset), fun: Fungible(amount) }, + &Asset { id: AssetId(asset), fun: Fungible(amount) }, &from, &to, // We aren't able to track the XCM that initiated the fee deposit, so we create a @@ -327,9 +327,9 @@ impl< { pub fn do_teleport_assets( origin: ::RuntimeOrigin, - dest: MultiLocation, - beneficiary: MultiLocation, - (asset, amount): (MultiLocation, u128), + dest: Location, + beneficiary: Location, + (asset, amount): (Location, u128), open_hrmp_channel: Option<(u32, u32)>, included_head: HeaderFor, slot_digest: &[u8], @@ -354,7 +354,7 @@ impl< origin, Box::new(dest.into()), Box::new(beneficiary.into()), - Box::new((Concrete(asset), amount).into()), + Box::new((AssetId(asset), amount).into()), 0, ) } @@ -377,12 +377,13 @@ impl< ]); // execute xcm as parent origin - let hash = xcm.using_encoded(sp_io::hashing::blake2_256); - <::XcmExecutor>::execute_xcm( - MultiLocation::parent(), + let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256); + <::XcmExecutor>::prepare_and_execute( + Location::parent(), xcm, - hash, + &mut hash, Self::xcm_max_weight(XcmReceivedFrom::Parent), + Weight::zero(), ) } } @@ -449,7 +450,7 @@ impl< } pub fn assert_metadata( - asset_id: impl Into + Copy, + asset_id: impl Into + Clone, expected_name: &str, expected_symbol: &str, expected_decimals: u8, @@ -457,20 +458,20 @@ pub fn assert_metadata( Fungibles: frame_support::traits::fungibles::metadata::Inspect + frame_support::traits::fungibles::Inspect, { - assert_eq!(Fungibles::name(asset_id.into()), Vec::from(expected_name),); - assert_eq!(Fungibles::symbol(asset_id.into()), Vec::from(expected_symbol),); + assert_eq!(Fungibles::name(asset_id.clone().into()), Vec::from(expected_name),); + assert_eq!(Fungibles::symbol(asset_id.clone().into()), Vec::from(expected_symbol),); assert_eq!(Fungibles::decimals(asset_id.into()), expected_decimals); } pub fn assert_total( - asset_id: impl Into + Copy, + asset_id: impl Into + Clone, expected_total_issuance: impl Into, expected_active_issuance: impl Into, ) where Fungibles: frame_support::traits::fungibles::metadata::Inspect + frame_support::traits::fungibles::Inspect, { - assert_eq!(Fungibles::total_issuance(asset_id.into()), expected_total_issuance.into()); + assert_eq!(Fungibles::total_issuance(asset_id.clone().into()), expected_total_issuance.into()); assert_eq!(Fungibles::active_issuance(asset_id.into()), expected_active_issuance.into()); } diff --git a/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs b/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs index 74d9a0b071d8..95629e41f0d7 100644 --- a/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs @@ -29,7 +29,7 @@ use super::{ }; use core::marker::PhantomData; use frame_support::{ - match_types, parameter_types, + parameter_types, traits::{ fungibles::{self, Balanced, Credit}, ConstU32, Contains, ContainsPair, Everything, Get, Nothing, @@ -57,13 +57,13 @@ use xcm_builder::{ use xcm_executor::{traits::JustTry, XcmExecutor}; parameter_types! { - pub const RelayLocation: MultiLocation = MultiLocation::parent(); + pub const RelayLocation: Location = Location::parent(); pub const RelayNetwork: Option = None; pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = X1(Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocation: InteriorLocation = [Parachain(ParachainInfo::parachain_id().into())].into(); } -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( @@ -81,7 +81,7 @@ pub type CurrencyTransactor = CurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: + // Do a simple punn to convert an AccountId32 Location into a native chain account ID: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -100,7 +100,7 @@ pub type FungiblesTransactor = FungiblesAdapter< AsPrefixedGeneralIndex, JustTry, >, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -145,14 +145,18 @@ parameter_types! { pub const MaxAssetsIntoHolding: u32 = 64; } -match_types! { - pub type ParentOrParentsExecutivePlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) } - }; - pub type CommonGoodAssetsParachain: impl Contains = { - MultiLocation { parents: 1, interior: X1(Parachain(1000)) } - }; +pub struct ParentOrParentsExecutivePlurality; +impl Contains for ParentOrParentsExecutivePlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [Plurality { id: BodyId::Executive, .. }])) + } +} + +pub struct CommonGoodAssetsParachain; +impl Contains for CommonGoodAssetsParachain { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, [Parachain(1000)])) + } } pub type Barrier = TrailingSetTopicAsId< @@ -189,23 +193,23 @@ pub type AccountIdOf = ::AccountId; /// Asset filter that allows all assets from a certain location matching asset id. pub struct AssetsFrom(PhantomData); -impl> ContainsPair for AssetsFrom { - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool { +impl> ContainsPair for AssetsFrom { + fn contains(asset: &Asset, origin: &Location) -> bool { let loc = T::get(); &loc == origin && - matches!(asset, MultiAsset { id: AssetId::Concrete(asset_loc), fun: Fungible(_a) } + matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) } if asset_loc.starts_with(&loc)) } } /// Asset filter that allows native/relay asset if coming from a certain location. pub struct NativeAssetFrom(PhantomData); -impl> ContainsPair for NativeAssetFrom { - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool { +impl> ContainsPair for NativeAssetFrom { + fn contains(asset: &Asset, origin: &Location) -> bool { let loc = T::get(); &loc == origin && - matches!(asset, MultiAsset { id: AssetId::Concrete(asset_loc), fun: Fungible(_a) } - if *asset_loc == MultiLocation::from(Parent)) + matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) } + if *asset_loc == Location::from(Parent)) } } @@ -239,11 +243,11 @@ where parameter_types! { /// The location that this chain recognizes as the Relay network's Asset Hub. - pub SystemAssetHubLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(1000))); + pub SystemAssetHubLocation: Location = Location::new(1, [Parachain(1000)]); // ALWAYS ensure that the index in PalletInstance stays up-to-date with // the Relay Chain's Asset Hub's Assets pallet index - pub SystemAssetHubAssetsPalletLocation: MultiLocation = - MultiLocation::new(1, X2(Parachain(1000), PalletInstance(50))); + pub SystemAssetHubAssetsPalletLocation: Location = + Location::new(1, [Parachain(1000), PalletInstance(50)]); pub CheckingAccount: AccountId = PolkadotXcm::check_account(); } diff --git a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs index 6df00d43e8d3..c7cd0ce59308 100644 --- a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs @@ -42,10 +42,10 @@ pub use frame_support::{ construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, - match_types, parameter_types, + parameter_types, traits::{ - AsEnsureOriginWithArg, ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, Everything, - IsInVec, Nothing, Randomness, + AsEnsureOriginWithArg, ConstBool, ConstU32, ConstU64, ConstU8, Contains, EitherOfDiverse, + Everything, IsInVec, Nothing, Randomness, }, weights::{ constants::{ @@ -322,14 +322,14 @@ impl pallet_message_queue::Config for Runtime { impl cumulus_pallet_aura_ext::Config for Runtime {} parameter_types! { - pub const RocLocation: MultiLocation = MultiLocation::parent(); + pub const RocLocation: Location = Location::parent(); pub const RococoNetwork: Option = Some(NetworkId::Rococo); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UniversalLocation: InteriorMultiLocation = X1(Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocation: InteriorLocation = [Parachain(ParachainInfo::parachain_id().into())].into(); pub CheckingAccount: AccountId = PolkadotXcm::check_account(); } -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( @@ -347,7 +347,7 @@ pub type CurrencyTransactor = CurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: + // Do a simple punn to convert an AccountId32 Location into a native chain account ID: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -370,7 +370,7 @@ pub type FungiblesTransactor = FungiblesAdapter< >, JustTry, >, - // Convert an XCM MultiLocation into a local account id: + // Convert an XCM Location into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -411,20 +411,22 @@ parameter_types! { // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate. pub UnitWeightCost: Weight = Weight::from_parts(1_000_000_000, 64 * 1024); // One ROC buys 1 second of weight. - pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), ROC); + pub const WeightPrice: (Location, u128) = (Location::parent(), ROC); pub const MaxInstructions: u32 = 100; } -match_types! { - // The parent or the parent's unit plurality. - pub type ParentOrParentsUnitPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) } - }; - // The location recognized as the Relay network's Asset Hub. - pub type AssetHub: impl Contains = { - MultiLocation { parents: 1, interior: X1(Parachain(1000)) } - }; +pub struct ParentOrParentsUnitPlurality; +impl Contains for ParentOrParentsUnitPlurality { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, HERE) | (1, [Plurality { id: BodyId::Unit, .. }])) + } +} + +pub struct AssetHub; +impl Contains for AssetHub { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, [Parachain(1000)])) + } } pub type Barrier = TrailingSetTopicAsId<( @@ -442,11 +444,11 @@ pub type Barrier = TrailingSetTopicAsId<( parameter_types! { pub MaxAssetsIntoHolding: u32 = 64; - pub SystemAssetHubLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(1000))); + pub SystemAssetHubLocation: Location = Location::new(1, [Parachain(1000)]); // ALWAYS ensure that the index in PalletInstance stays up-to-date with // the Relay Chain's Asset Hub's Assets pallet index - pub SystemAssetHubAssetsPalletLocation: MultiLocation = - MultiLocation::new(1, X2(Parachain(1000), PalletInstance(50))); + pub SystemAssetHubAssetsPalletLocation: Location = + Location::new(1, [Parachain(1000), PalletInstance(50)]); } pub type Reserves = (NativeAsset, AssetsFrom); diff --git a/cumulus/primitives/core/src/lib.rs b/cumulus/primitives/core/src/lib.rs index 835c9de649ea..32353fea4253 100644 --- a/cumulus/primitives/core/src/lib.rs +++ b/cumulus/primitives/core/src/lib.rs @@ -93,13 +93,13 @@ pub enum AggregateMessageOrigin { Sibling(ParaId), } -impl From for xcm::v3::MultiLocation { +impl From for Location { fn from(origin: AggregateMessageOrigin) -> Self { match origin { - AggregateMessageOrigin::Here => MultiLocation::here(), - AggregateMessageOrigin::Parent => MultiLocation::parent(), + AggregateMessageOrigin::Here => Location::here(), + AggregateMessageOrigin::Parent => Location::parent(), AggregateMessageOrigin::Sibling(id) => - MultiLocation::new(1, Junction::Parachain(id.into())), + Location::new(1, Junction::Parachain(id.into())), } } } diff --git a/cumulus/primitives/utility/src/lib.rs b/cumulus/primitives/utility/src/lib.rs index 03f827d7ee2f..638e8d4eb944 100644 --- a/cumulus/primitives/utility/src/lib.rs +++ b/cumulus/primitives/utility/src/lib.rs @@ -51,10 +51,7 @@ where { type Ticket = Vec; - fn validate( - dest: &mut Option, - msg: &mut Option>, - ) -> SendResult> { + fn validate(dest: &mut Option, msg: &mut Option>) -> SendResult> { let d = dest.take().ok_or(SendError::MissingArgument)?; if d.contains_parents_only(1) { @@ -90,14 +87,14 @@ struct AssetTraderRefunder { // The amount of weight bought minus the weigh already refunded weight_outstanding: Weight, // The concrete asset containing the asset location and outstanding balance - outstanding_concrete_asset: MultiAsset, + outstanding_concrete_asset: Asset, } -/// Charges for execution in the first multiasset of those selected for fee payment +/// Charges for execution in the first asset of those selected for fee payment /// Only succeeds for Concrete Fungible Assets -/// First tries to convert the this MultiAsset into a local assetId +/// First tries to convert the this Asset into a local assetId /// Then charges for this assetId as described by FeeCharger -/// Weight, paid balance, local asset Id and the multilocation is stored for +/// Weight, paid balance, local asset Id and the location is stored for /// later refund purposes /// Important: Errors if the Trader is being called twice by 2 BuyExecution instructions /// Alternatively we could just return payment in the aforementioned case @@ -123,15 +120,15 @@ impl< fn new() -> Self { Self(None, PhantomData) } - // We take first multiasset + // We take first asset // Check whether we can convert fee to asset_fee (is_sufficient, min_deposit) // If everything goes well, we charge. fn buy_weight( &mut self, weight: Weight, - payment: xcm_executor::Assets, + payment: xcm_executor::AssetsInHolding, context: &XcmContext, - ) -> Result { + ) -> Result { log::trace!(target: "xcm::weight", "TakeFirstAssetTrader::buy_weight weight: {:?}, payment: {:?}, context: {:?}", weight, payment, context); // Make sure we dont enter twice @@ -139,12 +136,12 @@ impl< return Err(XcmError::NotWithdrawable) } - // We take the very first multiasset from payment + // We take the very first asset from payment // (assets are sorted by fungibility/amount after this conversion) - let multiassets: MultiAssets = payment.clone().into(); + let assets: Assets = payment.clone().into(); - // Take the first multiasset from the selected MultiAssets - let first = multiassets.get(0).ok_or(XcmError::AssetNotFound)?; + // Take the first asset from the selected Assets + let first = assets.get(0).ok_or(XcmError::AssetNotFound)?; // Get the local asset id in which we can pay for fees let (local_asset_id, _) = @@ -166,13 +163,13 @@ impl< .try_into() .map_err(|_| XcmError::Overflow)?; - // Convert to the same kind of multiasset, with the required fungible balance - let required = first.id.into_multiasset(asset_balance.into()); + // Convert to the same kind of asset, with the required fungible balance + let required = first.id.clone().into_asset(asset_balance.into()); // Substract payment let unused = payment.checked_sub(required.clone()).map_err(|_| XcmError::TooExpensive)?; - // record weight and multiasset + // record weight and asset self.0 = Some(AssetTraderRefunder { weight_outstanding: weight, outstanding_concrete_asset: required, @@ -181,16 +178,16 @@ impl< Ok(unused) } - fn refund_weight(&mut self, weight: Weight, context: &XcmContext) -> Option { + fn refund_weight(&mut self, weight: Weight, context: &XcmContext) -> Option { log::trace!(target: "xcm::weight", "TakeFirstAssetTrader::refund_weight weight: {:?}, context: {:?}", weight, context); if let Some(AssetTraderRefunder { mut weight_outstanding, - outstanding_concrete_asset: MultiAsset { id, fun }, + outstanding_concrete_asset: Asset { id, fun }, }) = self.0.clone() { // Get the local asset id in which we can refund fees let (local_asset_id, outstanding_balance) = - Matcher::matches_fungibles(&(id, fun).into()).ok()?; + Matcher::matches_fungibles(&(id.clone(), fun).into()).ok()?; let minimum_balance = ConcreteAssets::minimum_balance(local_asset_id.clone()); @@ -220,7 +217,8 @@ impl< // Construct outstanding_concrete_asset with the same location id and substracted // balance - let outstanding_concrete_asset: MultiAsset = (id, outstanding_minus_substracted).into(); + let outstanding_concrete_asset: Asset = + (id.clone(), outstanding_minus_substracted).into(); // Substract from existing weight and balance weight_outstanding = weight_outstanding.saturating_sub(weight); @@ -267,11 +265,11 @@ impl< ReceiverAccount: Get>, > TakeRevenue for XcmFeesTo32ByteAccount { - fn take_revenue(revenue: MultiAsset) { + fn take_revenue(revenue: Asset) { if let Some(receiver) = ReceiverAccount::get() { let ok = FungiblesMutateAdapter::deposit_asset( &revenue, - &(X1(AccountId32 { network: None, id: receiver.into() }).into()), + &([AccountId32 { network: None, id: receiver.into() }].into()), None, ) .is_ok(); @@ -302,18 +300,18 @@ mod tests { }, }; use sp_runtime::DispatchError; - use xcm_executor::{traits::Error, Assets}; + use xcm_executor::{traits::Error, AssetsInHolding}; /// Validates [`validate`] for required Some(destination) and Some(message) struct OkFixedXcmHashWithAssertingRequiredInputsSender; impl OkFixedXcmHashWithAssertingRequiredInputsSender { const FIXED_XCM_HASH: [u8; 32] = [9; 32]; - fn fixed_delivery_asset() -> MultiAssets { - MultiAssets::new() + fn fixed_delivery_asset() -> Assets { + Assets::new() } - fn expected_delivery_result() -> Result<(XcmHash, MultiAssets), SendError> { + fn expected_delivery_result() -> Result<(XcmHash, Assets), SendError> { Ok((Self::FIXED_XCM_HASH, Self::fixed_delivery_asset())) } } @@ -321,7 +319,7 @@ mod tests { type Ticket = (); fn validate( - destination: &mut Option, + destination: &mut Option, message: &mut Option>, ) -> SendResult { assert!(destination.is_some()); @@ -377,7 +375,7 @@ mod tests { // ParentAsUmp - check dest/msg is valid let dest = (Parent, Here); - let mut dest_wrapper = Some(dest.into()); + let mut dest_wrapper = Some(dest.clone().into()); let mut msg_wrapper = Some(message.clone()); assert!( as SendXcm>::validate( &mut dest_wrapper, @@ -409,9 +407,9 @@ mod tests { type TestBalance = u128; struct TestAssets; impl MatchesFungibles for TestAssets { - fn matches_fungibles(a: &MultiAsset) -> Result<(TestAssetId, TestBalance), Error> { + fn matches_fungibles(a: &Asset) -> Result<(TestAssetId, TestBalance), Error> { match a { - MultiAsset { fun: Fungible(amount), id: Concrete(_id) } => Ok((1, *amount)), + Asset { fun: Fungible(amount), id: AssetId(_id) } => Ok((1, *amount)), _ => Err(Error::AssetNotHandled), } } @@ -498,7 +496,7 @@ mod tests { } } impl TakeRevenue for FeeChargerAssetsHandleRefund { - fn take_revenue(_: MultiAsset) {} + fn take_revenue(_: Asset) {} } // create new instance @@ -513,8 +511,8 @@ mod tests { let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; // prepare test data - let asset: MultiAsset = (Here, AMOUNT).into(); - let payment = Assets::from(asset); + let asset: Asset = (Here, AMOUNT).into(); + let payment = AssetsInHolding::from(asset); let weight_to_buy = Weight::from_parts(1_000, 1_000); // lets do first call (success) @@ -537,17 +535,17 @@ pub struct ToParentDeliveryHelper>, + ExistentialDeposit: Get>, PriceForDelivery: PriceForMessageDelivery, > pallet_xcm_benchmarks::EnsureDelivery for ToParentDeliveryHelper { fn ensure_successful_delivery( - origin_ref: &MultiLocation, - _dest: &MultiLocation, + origin_ref: &Location, + _dest: &Location, fee_reason: xcm_executor::traits::FeeReason, - ) -> (Option, Option) { - use xcm::latest::{MAX_INSTRUCTIONS_TO_DECODE, MAX_ITEMS_IN_MULTIASSETS}; + ) -> (Option, Option) { + use xcm::latest::{MAX_INSTRUCTIONS_TO_DECODE, MAX_ITEMS_IN_ASSETS}; use xcm_executor::{traits::FeeManager, FeesMode}; let mut fees_mode = None; @@ -560,8 +558,8 @@ impl< } // overestimate delivery fee - let mut max_assets: Vec = Vec::new(); - for i in 0..MAX_ITEMS_IN_MULTIASSETS { + let mut max_assets: Vec = Vec::new(); + for i in 0..MAX_ITEMS_IN_ASSETS { max_assets.push((GeneralIndex(i as u128), 100u128).into()); } let overestimated_xcm = diff --git a/cumulus/scripts/bridges_rococo_wococo.sh b/cumulus/scripts/bridges_rococo_wococo.sh index dd7c7062a3b3..402392395660 100755 --- a/cumulus/scripts/bridges_rococo_wococo.sh +++ b/cumulus/scripts/bridges_rococo_wococo.sh @@ -13,27 +13,27 @@ source "$(dirname "$0")"/bridges_common.sh # use polkadot_parachain_primitives::primitives::Sibling; # # parameter_types! { -# pub UniversalLocationAHR: InteriorMultiLocation = X2(GlobalConsensus(Rococo), Parachain(1000)); -# pub UniversalLocationAHW: InteriorMultiLocation = X2(GlobalConsensus(Wococo), Parachain(1000)); +# pub UniversalLocationAHR: InteriorLocation = [GlobalConsensus(Rococo), Parachain(1000)].into(); +# pub UniversalLocationAHW: InteriorLocation = [GlobalConsensus(Wococo), Parachain(1000)].into(); # } # # // SS58=42 # println!("GLOBAL_CONSENSUS_ROCOCO_SOVEREIGN_ACCOUNT=\"{}\"", # frame_support::sp_runtime::AccountId32::new( # GlobalConsensusConvertsFor::::convert_location( -# &MultiLocation { parents: 2, interior: X1(GlobalConsensus(Rococo)) }).unwrap() +# &Location::new(2, [GlobalConsensus(Rococo)] }).unwrap() # ).to_ss58check_with_version(42_u16.into()) # ); # println!("GLOBAL_CONSENSUS_ROCOCO_ASSET_HUB_ROCOCO_1000_SOVEREIGN_ACCOUNT=\"{}\"", # frame_support::sp_runtime::AccountId32::new( # GlobalConsensusParachainConvertsFor::::convert_location( -# &MultiLocation { parents: 2, interior: X2(GlobalConsensus(Rococo), Parachain(1000)) }).unwrap() +# &Location::new(2, [GlobalConsensus(Rococo), Parachain(1000)] }).unwrap() # ).to_ss58check_with_version(42_u16.into()) # ); # println!("ASSET_HUB_WOCOCO_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_WOCOCO=\"{}\"", # frame_support::sp_runtime::AccountId32::new( # SiblingParachainConvertsVia::::convert_location( -# &MultiLocation { parents: 1, interior: X1(Parachain(1000)) }).unwrap() +# &Location::new(1, [Parachain(1000)] }).unwrap() # ).to_ss58check_with_version(42_u16.into()) # ); # @@ -41,19 +41,19 @@ source "$(dirname "$0")"/bridges_common.sh # println!("GLOBAL_CONSENSUS_WOCOCO_SOVEREIGN_ACCOUNT=\"{}\"", # frame_support::sp_runtime::AccountId32::new( # GlobalConsensusConvertsFor::::convert_location( -# &MultiLocation { parents: 2, interior: X1(GlobalConsensus(Wococo)) }).unwrap() +# &Location::new(2, [GlobalConsensus(Wococo)] }).unwrap() # ).to_ss58check_with_version(42_u16.into()) # ); # println!("GLOBAL_CONSENSUS_WOCOCO_ASSET_HUB_WOCOCO_1000_SOVEREIGN_ACCOUNT=\"{}\"", # frame_support::sp_runtime::AccountId32::new( # GlobalConsensusParachainConvertsFor::::convert_location( -# &MultiLocation { parents: 2, interior: X2(GlobalConsensus(Wococo), Parachain(1000)) }).unwrap() +# &Location::new(2, [GlobalConsensus(Wococo), Parachain(1000)] }).unwrap() # ).to_ss58check_with_version(42_u16.into()) # ); # println!("ASSET_HUB_ROCOCO_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_ROCOCO=\"{}\"", # frame_support::sp_runtime::AccountId32::new( # SiblingParachainConvertsVia::::convert_location( -# &MultiLocation { parents: 1, interior: X1(Parachain(1000)) }).unwrap() +# &Location::new(1, [Parachain(1000)] }).unwrap() # ).to_ss58check_with_version(42_u16.into()) # ); # } diff --git a/cumulus/xcm/xcm-emulator/src/lib.rs b/cumulus/xcm/xcm-emulator/src/lib.rs index f2e4ff397c45..3a9f99b0eb9c 100644 --- a/cumulus/xcm/xcm-emulator/src/lib.rs +++ b/cumulus/xcm/xcm-emulator/src/lib.rs @@ -59,9 +59,9 @@ pub use polkadot_runtime_parachains::inclusion::{AggregateMessageOrigin, UmpQueu // Polkadot pub use polkadot_parachain_primitives::primitives::RelayChainBlockNumber; -pub use xcm::v3::prelude::{ - Ancestor, MultiAssets, MultiLocation, Parachain as ParachainJunction, Parent, WeightLimit, - XcmHash, X1, +pub use xcm::latest::prelude::{ + Ancestor, Assets, Junctions, Location, Parachain as ParachainJunction, Parent, WeightLimit, + XcmHash, }; pub use xcm_executor::traits::ConvertLocation; @@ -227,11 +227,11 @@ pub trait RelayChain: Chain { fn init(); - fn child_location_of(id: ParaId) -> MultiLocation { + fn child_location_of(id: ParaId) -> Location { (Ancestor(0), ParachainJunction(id.into())).into() } - fn sovereign_account_id_of(location: MultiLocation) -> AccountIdOf { + fn sovereign_account_id_of(location: Location) -> AccountIdOf { Self::SovereignAccountOf::convert_location(&location).unwrap() } @@ -259,15 +259,15 @@ pub trait Parachain: Chain { Self::ext_wrapper(|| Self::ParachainInfo::get()) } - fn parent_location() -> MultiLocation { + fn parent_location() -> Location { (Parent).into() } - fn sibling_location_of(para_id: ParaId) -> MultiLocation { - (Parent, X1(ParachainJunction(para_id.into()))).into() + fn sibling_location_of(para_id: ParaId) -> Location { + (Parent, ParachainJunction(para_id.into())).into() } - fn sovereign_account_id_of(location: MultiLocation) -> AccountIdOf { + fn sovereign_account_id_of(location: Location) -> AccountIdOf { Self::LocationToAccountId::convert_location(&location).unwrap() } } @@ -1422,10 +1422,10 @@ pub struct TestAccount { /// Default `Args` provided by xcm-emulator to be stored in a `Test` instance #[derive(Clone)] pub struct TestArgs { - pub dest: MultiLocation, - pub beneficiary: MultiLocation, + pub dest: Location, + pub beneficiary: Location, pub amount: Balance, - pub assets: MultiAssets, + pub assets: Assets, pub asset_id: Option, pub fee_asset_item: u32, pub weight_limit: WeightLimit, diff --git a/polkadot/runtime/common/src/impls.rs b/polkadot/runtime/common/src/impls.rs index e50ffb634b30..e6fcdfb96aee 100644 --- a/polkadot/runtime/common/src/impls.rs +++ b/polkadot/runtime/common/src/impls.rs @@ -21,7 +21,7 @@ use frame_support::traits::{Currency, Imbalance, OnUnbalanced}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use primitives::Balance; use sp_runtime::{traits::TryConvert, Perquintill, RuntimeDebug}; -use xcm::VersionedMultiLocation; +use xcm::VersionedLocation; /// Logic for the author to get a portion of fees. pub struct ToAuthor(sp_std::marker::PhantomData); @@ -108,11 +108,14 @@ pub fn era_payout( pub enum VersionedLocatableAsset { #[codec(index = 3)] V3 { - /// The (relative) location in which the asset ID is meaningful. location: xcm::v3::MultiLocation, - /// The asset's ID. asset_id: xcm::v3::AssetId, }, + #[codec(index = 4)] + V4 { + location: xcm::v4::Location, + asset_id: xcm::v4::AssetId, + }, } /// Converts the [`VersionedLocatableAsset`] to the [`xcm_builder::LocatableAssetId`]. @@ -124,23 +127,27 @@ impl TryConvert asset: VersionedLocatableAsset, ) -> Result { match asset { - VersionedLocatableAsset::V3 { location, asset_id } => - Ok(xcm_builder::LocatableAssetId { asset_id, location }), + VersionedLocatableAsset::V3 { location, asset_id } => Ok(xcm_builder::LocatableAssetId { location: location.try_into().map_err(|_| asset.clone())?, asset_id: asset_id.try_into().map_err(|_| asset.clone())? }), + VersionedLocatableAsset::V4 { location, asset_id } => Ok(xcm_builder::LocatableAssetId { location, asset_id }), } } } -/// Converts the [`VersionedMultiLocation`] to the [`xcm::latest::MultiLocation`]. -pub struct VersionedMultiLocationConverter; -impl TryConvert<&VersionedMultiLocation, xcm::latest::MultiLocation> - for VersionedMultiLocationConverter +/// Converts the [`VersionedLocation`] to the [`xcm::latest::Location`]. +pub struct VersionedLocationConverter; +impl TryConvert<&VersionedLocation, xcm::latest::Location> + for VersionedLocationConverter { fn try_convert( - location: &VersionedMultiLocation, - ) -> Result { + location: &VersionedLocation, + ) -> Result { let latest = match location.clone() { - VersionedMultiLocation::V2(l) => l.try_into().map_err(|_| location)?, - VersionedMultiLocation::V3(l) => l, + VersionedLocation::V2(l) => { + let v3: xcm::v3::MultiLocation = l.try_into().map_err(|_| location)?; + v3.try_into().map_err(|_| location)? + }, + VersionedLocation::V3(l) => l.try_into().map_err(|_| location)?, + VersionedLocation::V4(l) => l, }; Ok(latest) } @@ -158,11 +165,11 @@ pub mod benchmarks { pub struct AssetRateArguments; impl AssetKindFactory for AssetRateArguments { fn create_asset_kind(seed: u32) -> VersionedLocatableAsset { - VersionedLocatableAsset::V3 { - location: xcm::v3::MultiLocation::new(0, X1(Parachain(seed))), - asset_id: xcm::v3::MultiLocation::new( + VersionedLocatableAsset::V4 { + location: xcm::v4::Location::new(0, [xcm::v4::Junction::Parachain(seed)]), + asset_id: xcm::v4::Location::new( 0, - X2(PalletInstance(seed.try_into().unwrap()), GeneralIndex(seed.into())), + [xcm::v4::Junction::PalletInstance(seed.try_into().unwrap()), xcm::v4::Junction::GeneralIndex(seed.into())], ) .into(), } @@ -170,19 +177,19 @@ pub mod benchmarks { } /// Provide factory methods for the [`VersionedLocatableAsset`] and the `Beneficiary` of the - /// [`VersionedMultiLocation`]. The location of the asset is determined as a Parachain with an + /// [`VersionedLocation`]. The location of the asset is determined as a Parachain with an /// ID equal to the passed seed. pub struct TreasuryArguments; - impl TreasuryArgumentsFactory + impl TreasuryArgumentsFactory for TreasuryArguments { fn create_asset_kind(seed: u32) -> VersionedLocatableAsset { AssetRateArguments::create_asset_kind(seed) } - fn create_beneficiary(seed: [u8; 32]) -> VersionedMultiLocation { - VersionedMultiLocation::V3(xcm::v3::MultiLocation::new( + fn create_beneficiary(seed: [u8; 32]) -> VersionedLocation { + VersionedLocation::V4(xcm::v4::Location::new( 0, - X1(AccountId32 { network: None, id: seed }), + [xcm::v4::Junction::AccountId32 { network: None, id: seed }], )) } } diff --git a/polkadot/runtime/common/src/xcm_sender.rs b/polkadot/runtime/common/src/xcm_sender.rs index 4d31c92cdd3a..7f1100a13619 100644 --- a/polkadot/runtime/common/src/xcm_sender.rs +++ b/polkadot/runtime/common/src/xcm_sender.rs @@ -35,13 +35,13 @@ pub trait PriceForMessageDelivery { /// Type used for charging different prices to different destinations type Id; /// Return the assets required to deliver `message` to the given `para` destination. - fn price_for_delivery(id: Self::Id, message: &Xcm<()>) -> MultiAssets; + fn price_for_delivery(id: Self::Id, message: &Xcm<()>) -> Assets; } impl PriceForMessageDelivery for () { type Id = (); - fn price_for_delivery(_: Self::Id, _: &Xcm<()>) -> MultiAssets { - MultiAssets::new() + fn price_for_delivery(_: Self::Id, _: &Xcm<()>) -> Assets { + Assets::new() } } @@ -49,17 +49,17 @@ pub struct NoPriceForMessageDelivery(PhantomData); impl PriceForMessageDelivery for NoPriceForMessageDelivery { type Id = Id; - fn price_for_delivery(_: Self::Id, _: &Xcm<()>) -> MultiAssets { - MultiAssets::new() + fn price_for_delivery(_: Self::Id, _: &Xcm<()>) -> Assets { + Assets::new() } } /// Implementation of [`PriceForMessageDelivery`] which returns a fixed price. pub struct ConstantPrice(sp_std::marker::PhantomData); -impl> PriceForMessageDelivery for ConstantPrice { +impl> PriceForMessageDelivery for ConstantPrice { type Id = (); - fn price_for_delivery(_: Self::Id, _: &Xcm<()>) -> MultiAssets { + fn price_for_delivery(_: Self::Id, _: &Xcm<()>) -> Assets { T::get() } } @@ -84,7 +84,7 @@ impl, B: Get, M: Get, F: FeeTracker> PriceForMessage { type Id = F::Id; - fn price_for_delivery(id: Self::Id, msg: &Xcm<()>) -> MultiAssets { + fn price_for_delivery(id: Self::Id, msg: &Xcm<()>) -> Assets { let msg_fee = (msg.encoded_size() as u128).saturating_mul(M::get()); let fee_sum = B::get().saturating_add(msg_fee); let amount = F::get_fee_factor(id).saturating_mul_int(fee_sum); @@ -103,11 +103,11 @@ where type Ticket = (HostConfiguration>, ParaId, Vec); fn validate( - dest: &mut Option, + dest: &mut Option, msg: &mut Option>, ) -> SendResult<(HostConfiguration>, ParaId, Vec)> { let d = dest.take().ok_or(MissingArgument)?; - let id = if let MultiLocation { parents: 0, interior: X1(Parachain(id)) } = &d { + let id = if let (0, [Parachain(id)]) = d.unpack() { *id } else { *dest = Some(d); @@ -160,7 +160,7 @@ pub struct ToParachainDeliveryHelper< #[cfg(feature = "runtime-benchmarks")] impl< XcmConfig: xcm_executor::Config, - ExistentialDeposit: Get>, + ExistentialDeposit: Get>, PriceForDelivery: PriceForMessageDelivery, Parachain: Get, ToParachainHelper: EnsureForParachain, @@ -174,10 +174,10 @@ impl< > { fn ensure_successful_delivery( - origin_ref: &MultiLocation, - _dest: &MultiLocation, + origin_ref: &Location, + _dest: &Location, fee_reason: xcm_executor::traits::FeeReason, - ) -> (Option, Option) { + ) -> (Option, Option) { use xcm_executor::{ traits::{FeeManager, TransactAsset}, FeesMode, @@ -234,7 +234,7 @@ mod tests { parameter_types! { pub const BaseDeliveryFee: u128 = 300_000_000; pub const TransactionByteFee: u128 = 1_000_000; - pub FeeAssetId: AssetId = Concrete(Here.into()); + pub FeeAssetId: AssetId = AssetId(Here.into()); } struct TestFeeTracker; diff --git a/polkadot/runtime/rococo/constants/src/lib.rs b/polkadot/runtime/rococo/constants/src/lib.rs index 2f641d60fc8b..31336b6d6937 100644 --- a/polkadot/runtime/rococo/constants/src/lib.rs +++ b/polkadot/runtime/rococo/constants/src/lib.rs @@ -104,6 +104,7 @@ pub mod fee { /// System Parachains. pub mod system_parachain { use xcm::latest::prelude::*; + use frame_support::traits::Contains; /// Network's Asset Hub parachain ID. pub const ASSET_HUB_ID: u32 = 1000; @@ -114,10 +115,14 @@ pub mod system_parachain { /// BridgeHub parachain ID. pub const BRIDGE_HUB_ID: u32 = 1013; - frame_support::match_types! { - pub type SystemParachains: impl Contains = { - MultiLocation { parents: 0, interior: X1(Parachain(ASSET_HUB_ID | CONTRACTS_ID | ENCOINTER_ID | BRIDGE_HUB_ID)) } - }; + pub struct SystemParachains; + impl Contains for SystemParachains { + fn contains(location: &Location) -> bool { + matches!( + location.unpack(), + (0, [Parachain(ASSET_HUB_ID | CONTRACTS_ID | ENCOINTER_ID | BRIDGE_HUB_ID)]) + ) + } } } diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index 40ef22107a7c..d5c77f25343d 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -32,7 +32,7 @@ use primitives::{ use runtime_common::{ assigned_slots, auctions, claims, crowdloan, impl_runtime_weights, impls::{ - LocatableAssetConverter, ToAuthor, VersionedLocatableAsset, VersionedMultiLocationConverter, + LocatableAssetConverter, ToAuthor, VersionedLocatableAsset, VersionedLocationConverter, }, paras_registrar, paras_sudo_wrapper, prod_or_fast, slots, BlockHashCount, BlockLength, SlowAdjustingFeeUpdate, @@ -95,10 +95,7 @@ use sp_staking::SessionIndex; #[cfg(any(feature = "std", test))] use sp_version::NativeVersion; use sp_version::RuntimeVersion; -use xcm::{ - latest::{InteriorMultiLocation, Junction, Junction::PalletInstance}, - VersionedMultiLocation, -}; +use xcm::{latest::prelude::*, VersionedLocation}; use xcm_builder::PayOverXcm; pub use frame_system::Call as SystemCall; @@ -400,7 +397,7 @@ parameter_types! { pub const PayoutSpendPeriod: BlockNumber = 30 * DAYS; // The asset's interior location for the paying account. This is the Treasury // pallet instance (which sits at index 18). - pub TreasuryInteriorLocation: InteriorMultiLocation = PalletInstance(18).into(); + pub TreasuryInteriorLocation: InteriorLocation = PalletInstance(18).into(); pub const TipCountdown: BlockNumber = 1 * DAYS; pub const TipFindersFee: Percent = Percent::from_percent(20); @@ -431,7 +428,7 @@ impl pallet_treasury::Config for Runtime { type SpendFunds = Bounties; type SpendOrigin = TreasurySpender; type AssetKind = VersionedLocatableAsset; - type Beneficiary = VersionedMultiLocation; + type Beneficiary = VersionedLocation; type BeneficiaryLookup = IdentityLookup; type Paymaster = PayOverXcm< TreasuryInteriorLocation, @@ -441,7 +438,7 @@ impl pallet_treasury::Config for Runtime { Self::Beneficiary, Self::AssetKind, LocatableAssetConverter, - VersionedMultiLocationConverter, + VersionedLocationConverter, >; type BalanceConverter = AssetRate; type PayoutPeriod = PayoutSpendPeriod; @@ -477,7 +474,7 @@ impl pallet_bounties::Config for Runtime { parameter_types! { pub const MaxActiveChildBountyCount: u32 = 100; - pub const ChildBountyValueMinimum: Balance = BountyValueMinimum::get() / 10; + pub ChildBountyValueMinimum: Balance = BountyValueMinimum::get() / 10; } impl pallet_child_bounties::Config for Runtime { @@ -514,7 +511,7 @@ impl pallet_im_online::Config for Runtime { } parameter_types! { - pub const MaxSetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get(); + pub MaxSetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get(); } impl pallet_grandpa::Config for Runtime { @@ -1136,7 +1133,7 @@ impl pallet_nis::Config for Runtime { } parameter_types! { - pub const BeefySetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get(); + pub BeefySetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get(); } impl pallet_beefy::Config for Runtime { @@ -2091,7 +2088,7 @@ sp_api::impl_runtime_apis! { }; parameter_types! { - pub ExistentialDepositMultiAsset: Option = Some(( + pub ExistentialDepositAsset: Option = Some(( TokenLocation::get(), ExistentialDeposit::get() ).into()); @@ -2101,27 +2098,27 @@ sp_api::impl_runtime_apis! { impl frame_system_benchmarking::Config for Runtime {} impl frame_benchmarking::baseline::Config for Runtime {} impl pallet_xcm::benchmarking::Config for Runtime { - fn reachable_dest() -> Option { + fn reachable_dest() -> Option { Some(crate::xcm_config::AssetHub::get()) } - fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { // Relay/native token can be teleported to/from AH. Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Here.into()) + id: AssetId(Here.into()) }, crate::xcm_config::AssetHub::get(), )) } - fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { // Relay can reserve transfer native token to some random parachain. Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Here.into()) + id: AssetId(Here.into()) }, Parachain(43211234).into(), )) @@ -2132,29 +2129,29 @@ sp_api::impl_runtime_apis! { type AccountIdConverter = LocationConverter; type DeliveryHelper = runtime_common::xcm_sender::ToParachainDeliveryHelper< XcmConfig, - ExistentialDepositMultiAsset, + ExistentialDepositAsset, xcm_config::PriceForChildParachainDelivery, ToParachain, (), >; - fn valid_destination() -> Result { + fn valid_destination() -> Result { Ok(AssetHub::get()) } - fn worst_case_holding(_depositable_count: u32) -> MultiAssets { + fn worst_case_holding(_depositable_count: u32) -> Assets { // Rococo only knows about ROC - vec![MultiAsset{ - id: Concrete(TokenLocation::get()), + vec![Asset{ + id: AssetId(TokenLocation::get()), fun: Fungible(1_000_000 * UNITS), }].into() } } parameter_types! { - pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + pub TrustedTeleporter: Option<(Location, Asset)> = Some(( AssetHub::get(), - MultiAsset { fun: Fungible(1 * UNITS), id: Concrete(TokenLocation::get()) }, + Asset { fun: Fungible(1 * UNITS), id: AssetId(TokenLocation::get()) }, )); - pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None; + pub TrustedReserve: Option<(Location, Asset)> = None; } impl pallet_xcm_benchmarks::fungible::Config for Runtime { @@ -2164,9 +2161,9 @@ sp_api::impl_runtime_apis! { type TrustedTeleporter = TrustedTeleporter; type TrustedReserve = TrustedReserve; - fn get_multi_asset() -> MultiAsset { - MultiAsset { - id: Concrete(TokenLocation::get()), + fn get_asset() -> Asset { + Asset { + id: AssetId(TokenLocation::get()), fun: Fungible(1 * UNITS), } } @@ -2180,43 +2177,43 @@ sp_api::impl_runtime_apis! { (0u64, Response::Version(Default::default())) } - fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> { // Rococo doesn't support asset exchanges Err(BenchmarkError::Skip) } - fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + fn universal_alias() -> Result<(Location, Junction), BenchmarkError> { // The XCM executor of Rococo doesn't have a configured `UniversalAliases` Err(BenchmarkError::Skip) } - fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> { + fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> { Ok((AssetHub::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) } - fn subscribe_origin() -> Result { + fn subscribe_origin() -> Result { Ok(AssetHub::get()) } - fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { + fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> { let origin = AssetHub::get(); - let assets: MultiAssets = (Concrete(TokenLocation::get()), 1_000 * UNITS).into(); - let ticket = MultiLocation { parents: 0, interior: Here }; + let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into(); + let ticket = Location { parents: 0, interior: Here }; Ok((origin, ticket, assets)) } - fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { + fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> { // Rococo doesn't support asset locking Err(BenchmarkError::Skip) } fn export_message_origin_and_destination( - ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { + ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> { // Rococo doesn't support exporting messages Err(BenchmarkError::Skip) } - fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { + fn alias_origin() -> Result<(Location, Location), BenchmarkError> { // The XCM executor of Rococo doesn't have a configured `Aliasers` Err(BenchmarkError::Skip) } diff --git a/polkadot/runtime/rococo/src/weights/xcm/mod.rs b/polkadot/runtime/rococo/src/weights/xcm/mod.rs index cc485dfbaf7e..12f3df897b1e 100644 --- a/polkadot/runtime/rococo/src/weights/xcm/mod.rs +++ b/polkadot/runtime/rococo/src/weights/xcm/mod.rs @@ -33,25 +33,25 @@ pub enum AssetTypes { Unknown, } -impl From<&MultiAsset> for AssetTypes { - fn from(asset: &MultiAsset) -> Self { +impl From<&Asset> for AssetTypes { + fn from(asset: &Asset) -> Self { match asset { - MultiAsset { id: Concrete(MultiLocation { parents: 0, interior: Here }), .. } => + Asset { id: AssetId(Location { parents: 0, interior: Here }), .. } => AssetTypes::Balances, _ => AssetTypes::Unknown, } } } -trait WeighMultiAssets { - fn weigh_multi_assets(&self, balances_weight: Weight) -> Weight; +trait WeighAssets { + fn weigh_assets(&self, balances_weight: Weight) -> Weight; } // Rococo only knows about one asset, the balances pallet. const MAX_ASSETS: u64 = 1; -impl WeighMultiAssets for MultiAssetFilter { - fn weigh_multi_assets(&self, balances_weight: Weight) -> Weight { +impl WeighAssets for AssetFilter { + fn weigh_assets(&self, balances_weight: Weight) -> Weight { match self { Self::Definite(assets) => assets .inner() @@ -72,11 +72,11 @@ impl WeighMultiAssets for MultiAssetFilter { } } -impl WeighMultiAssets for MultiAssets { - fn weigh_multi_assets(&self, balances_weight: Weight) -> Weight { +impl WeighAssets for Assets { + fn weigh_assets(&self, balances_weight: Weight) -> Weight { self.inner() .into_iter() - .map(|m| >::from(m)) + .map(|m| >::from(m)) .map(|t| match t { AssetTypes::Balances => balances_weight, AssetTypes::Unknown => Weight::MAX, @@ -87,32 +87,28 @@ impl WeighMultiAssets for MultiAssets { pub struct RococoXcmWeight(core::marker::PhantomData); impl XcmWeightInfo for RococoXcmWeight { - fn withdraw_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::withdraw_asset()) + fn withdraw_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::withdraw_asset()) } - fn reserve_asset_deposited(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::reserve_asset_deposited()) + fn reserve_asset_deposited(assets: &Assets) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::reserve_asset_deposited()) } - fn receive_teleported_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::receive_teleported_asset()) + fn receive_teleported_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::receive_teleported_asset()) } fn query_response( _query_id: &u64, _response: &Response, _max_weight: &Weight, - _querier: &Option, + _querier: &Option, ) -> Weight { XcmGeneric::::query_response() } - fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::transfer_asset()) + fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::transfer_asset()) } - fn transfer_reserve_asset( - assets: &MultiAssets, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::transfer_reserve_asset()) + fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::transfer_reserve_asset()) } fn transact( _origin_kind: &OriginKind, @@ -140,45 +136,37 @@ impl XcmWeightInfo for RococoXcmWeight { fn clear_origin() -> Weight { XcmGeneric::::clear_origin() } - fn descend_origin(_who: &InteriorMultiLocation) -> Weight { + fn descend_origin(_who: &InteriorLocation) -> Weight { XcmGeneric::::descend_origin() } fn report_error(_query_response_info: &QueryResponseInfo) -> Weight { XcmGeneric::::report_error() } - fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::deposit_asset()) + fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::deposit_asset()) } - fn deposit_reserve_asset( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::deposit_reserve_asset()) + fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::deposit_reserve_asset()) } - fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight { + fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight { // Rococo does not currently support exchange asset operations Weight::MAX } fn initiate_reserve_withdraw( - assets: &MultiAssetFilter, - _reserve: &MultiLocation, + assets: &AssetFilter, + _reserve: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::initiate_reserve_withdraw()) + assets.weigh_assets(XcmBalancesWeight::::initiate_reserve_withdraw()) } - fn initiate_teleport( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::initiate_teleport()) + fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::initiate_teleport()) } - fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight { + fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } - fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight { + fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } fn refund_surplus() -> Weight { @@ -193,7 +181,7 @@ impl XcmWeightInfo for RococoXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } - fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight { + fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } fn trap(_code: &u64) -> Weight { @@ -205,13 +193,13 @@ impl XcmWeightInfo for RococoXcmWeight { fn unsubscribe_version() -> Weight { XcmGeneric::::unsubscribe_version() } - fn burn_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + fn burn_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::burn_asset()) } - fn expect_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + fn expect_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::expect_asset()) } - fn expect_origin(_origin: &Option) -> Weight { + fn expect_origin(_origin: &Option) -> Weight { XcmGeneric::::expect_origin() } fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { @@ -246,19 +234,19 @@ impl XcmWeightInfo for RococoXcmWeight { // Rococo relay should not support export message operations Weight::MAX } - fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn lock_asset(_: &Asset, _: &Location) -> Weight { // Rococo does not currently support asset locking operations Weight::MAX } - fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn unlock_asset(_: &Asset, _: &Location) -> Weight { // Rococo does not currently support asset locking operations Weight::MAX } - fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn note_unlockable(_: &Asset, _: &Location) -> Weight { // Rococo does not currently support asset locking operations Weight::MAX } - fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn request_unlock(_: &Asset, _: &Location) -> Weight { // Rococo does not currently support asset locking operations Weight::MAX } @@ -271,19 +259,19 @@ impl XcmWeightInfo for RococoXcmWeight { fn clear_topic() -> Weight { XcmGeneric::::clear_topic() } - fn alias_origin(_: &MultiLocation) -> Weight { + fn alias_origin(_: &Location) -> Weight { // XCM Executor does not currently support alias origin operations Weight::MAX } - fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { + fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } } #[test] fn all_counted_has_a_sane_weight_upper_limit() { - let assets = MultiAssetFilter::Wild(AllCounted(4294967295)); + let assets = AssetFilter::Wild(AllCounted(4294967295)); let weight = Weight::from_parts(1000, 1000); - assert_eq!(assets.weigh_multi_assets(weight), weight * MAX_ASSETS); + assert_eq!(assets.weigh_assets(weight), weight * MAX_ASSETS); } diff --git a/polkadot/runtime/rococo/src/xcm_config.rs b/polkadot/runtime/rococo/src/xcm_config.rs index c8f8f59dae99..b77b0e5eeeac 100644 --- a/polkadot/runtime/rococo/src/xcm_config.rs +++ b/polkadot/runtime/rococo/src/xcm_config.rs @@ -24,8 +24,8 @@ use super::{ use crate::governance::StakingAdmin; use frame_support::{ - match_types, parameter_types, - traits::{Everything, Nothing}, + parameter_types, + traits::{Contains, Everything, Nothing}, weights::Weight, }; use frame_system::EnsureRoot; @@ -49,9 +49,9 @@ use xcm_builder::{ use xcm_executor::XcmExecutor; parameter_types! { - pub const TokenLocation: MultiLocation = Here.into_location(); + pub TokenLocation: Location = Here.into_location(); pub const ThisNetwork: NetworkId = NetworkId::Rococo; - pub UniversalLocation: InteriorMultiLocation = ThisNetwork::get().into(); + pub UniversalLocation: InteriorLocation = ThisNetwork::get().into(); pub CheckAccount: AccountId = XcmPallet::check_account(); pub LocalCheckAccount: (AccountId, MintLocation) = (CheckAccount::get(), MintLocation::Local); pub TreasuryAccount: AccountId = Treasury::account_id(); @@ -67,7 +67,7 @@ pub type LocationConverter = ( ); /// Our asset transactor. This is what allows us to interest with the runtime facilities from the -/// point of view of XCM-only concepts like `MultiLocation` and `MultiAsset`. +/// point of view of XCM-only concepts like `Location` and `Asset`. /// /// Ours is only aware of the Balances pallet, which is mapped to `RocLocation`. pub type LocalAssetTransactor = XcmCurrencyAdapter< @@ -75,7 +75,7 @@ pub type LocalAssetTransactor = XcmCurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // We can convert the MultiLocations with our converter above: + // We can convert the Locations with our converter above: LocationConverter, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -97,7 +97,7 @@ parameter_types! { /// The amount of weight an XCM operation takes. This is a safe overestimate. pub const BaseXcmWeight: Weight = Weight::from_parts(1_000_000_000, 64 * 1024); /// The asset ID for the asset that we use to pay for message delivery fees. - pub FeeAssetId: AssetId = Concrete(TokenLocation::get()); + pub FeeAssetId: AssetId = AssetId(TokenLocation::get()); /// The base fee for the message delivery fees. pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); } @@ -113,21 +113,21 @@ pub type XcmRouter = WithUniqueTopic< >; parameter_types! { - pub const Roc: MultiAssetFilter = Wild(AllOf { fun: WildFungible, id: Concrete(TokenLocation::get()) }); - pub const AssetHub: MultiLocation = Parachain(ASSET_HUB_ID).into_location(); - pub const Contracts: MultiLocation = Parachain(CONTRACTS_ID).into_location(); - pub const Encointer: MultiLocation = Parachain(ENCOINTER_ID).into_location(); - pub const BridgeHub: MultiLocation = Parachain(BRIDGE_HUB_ID).into_location(); - pub const Tick: MultiLocation = Parachain(100).into_location(); - pub const Trick: MultiLocation = Parachain(110).into_location(); - pub const Track: MultiLocation = Parachain(120).into_location(); - pub const RocForTick: (MultiAssetFilter, MultiLocation) = (Roc::get(), Tick::get()); - pub const RocForTrick: (MultiAssetFilter, MultiLocation) = (Roc::get(), Trick::get()); - pub const RocForTrack: (MultiAssetFilter, MultiLocation) = (Roc::get(), Track::get()); - pub const RocForAssetHub: (MultiAssetFilter, MultiLocation) = (Roc::get(), AssetHub::get()); - pub const RocForContracts: (MultiAssetFilter, MultiLocation) = (Roc::get(), Contracts::get()); - pub const RocForEncointer: (MultiAssetFilter, MultiLocation) = (Roc::get(), Encointer::get()); - pub const RocForBridgeHub: (MultiAssetFilter, MultiLocation) = (Roc::get(), BridgeHub::get()); + pub Roc: AssetFilter = Wild(AllOf { fun: WildFungible, id: AssetId(TokenLocation::get()) }); + pub AssetHub: Location = Parachain(ASSET_HUB_ID).into_location(); + pub Contracts: Location = Parachain(CONTRACTS_ID).into_location(); + pub Encointer: Location = Parachain(ENCOINTER_ID).into_location(); + pub BridgeHub: Location = Parachain(BRIDGE_HUB_ID).into_location(); + pub Tick: Location = Parachain(100).into_location(); + pub Trick: Location = Parachain(110).into_location(); + pub Track: Location = Parachain(120).into_location(); + pub RocForTick: (AssetFilter, Location) = (Roc::get(), Tick::get()); + pub RocForTrick: (AssetFilter, Location) = (Roc::get(), Trick::get()); + pub RocForTrack: (AssetFilter, Location) = (Roc::get(), Track::get()); + pub RocForAssetHub: (AssetFilter, Location) = (Roc::get(), AssetHub::get()); + pub RocForContracts: (AssetFilter, Location) = (Roc::get(), Contracts::get()); + pub RocForEncointer: (AssetFilter, Location) = (Roc::get(), Encointer::get()); + pub RocForBridgeHub: (AssetFilter, Location) = (Roc::get(), BridgeHub::get()); pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 64; } @@ -141,10 +141,11 @@ pub type TrustedTeleporters = ( xcm_builder::Case, ); -match_types! { - pub type OnlyParachains: impl Contains = { - MultiLocation { parents: 0, interior: X1(Parachain(_)) } - }; +pub struct OnlyParachains; +impl Contains for OnlyParachains { + fn contains(loc: &Location) -> bool { + matches!(loc.unpack(), (0, [Parachain(_)])) + } } /// The barriers one of which must be passed for an XCM message to be executed. @@ -211,26 +212,26 @@ parameter_types! { pub const FellowsBodyId: BodyId = BodyId::Technical; } -/// Type to convert an `Origin` type value into a `MultiLocation` value which represents an interior +/// Type to convert an `Origin` type value into a `Location` value which represents an interior /// location of this chain. pub type LocalOriginToLocation = ( // And a usual Signed origin to be used in XCM as a corresponding AccountId32 SignedToAccountId32, ); -/// Type to convert the `StakingAdmin` origin to a Plurality `MultiLocation` value. +/// Type to convert the `StakingAdmin` origin to a Plurality `Location` value. pub type StakingAdminToPlurality = OriginToPluralityVoice; -/// Type to convert the Fellows origin to a Plurality `MultiLocation` value. +/// Type to convert the Fellows origin to a Plurality `Location` value. pub type FellowsToPlurality = OriginToPluralityVoice; -/// Type to convert a pallet `Origin` type value into a `MultiLocation` value which represents an +/// Type to convert a pallet `Origin` type value into a `Location` value which represents an /// interior location of this chain for a destination chain. pub type LocalPalletOriginToLocation = ( - // StakingAdmin origin to be used in XCM as a corresponding Plurality `MultiLocation` value. + // StakingAdmin origin to be used in XCM as a corresponding Plurality `Location` value. StakingAdminToPlurality, - // Fellows origin to be used in XCM as a corresponding Plurality `MultiLocation` value. + // Fellows origin to be used in XCM as a corresponding Plurality `Location` value. FellowsToPlurality, ); diff --git a/polkadot/runtime/test-runtime/src/lib.rs b/polkadot/runtime/test-runtime/src/lib.rs index 596e65eca068..34d327c49ab2 100644 --- a/polkadot/runtime/test-runtime/src/lib.rs +++ b/polkadot/runtime/test-runtime/src/lib.rs @@ -602,7 +602,7 @@ pub mod pallet_test_notifier { pub enum Event { QueryPrepared(QueryId), NotifyQueryPrepared(QueryId), - ResponseReceived(MultiLocation, QueryId, Response), + ResponseReceived(Location, QueryId, Response), } #[pallet::error] diff --git a/polkadot/runtime/test-runtime/src/xcm_config.rs b/polkadot/runtime/test-runtime/src/xcm_config.rs index ae4faecf7001..0d0dd3404f3e 100644 --- a/polkadot/runtime/test-runtime/src/xcm_config.rs +++ b/polkadot/runtime/test-runtime/src/xcm_config.rs @@ -27,7 +27,7 @@ use xcm_builder::{ }; use xcm_executor::{ traits::{TransactAsset, WeightTrader}, - Assets, + AssetsInHolding, }; parameter_types! { @@ -35,10 +35,10 @@ parameter_types! { pub const AnyNetwork: Option = None; pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 16; - pub const UniversalLocation: xcm::latest::InteriorMultiLocation = xcm::latest::Junctions::Here; + pub const UniversalLocation: xcm::latest::InteriorLocation = xcm::latest::Junctions::Here; } -/// Type to convert an `Origin` type value into a `MultiLocation` value which represents an interior +/// Type to convert an `Origin` type value into a `Location` value which represents an interior /// location of this chain. pub type LocalOriginToLocation = ( // And a usual Signed origin to be used in XCM as a corresponding AccountId32 @@ -48,8 +48,8 @@ pub type LocalOriginToLocation = ( pub struct DoNothingRouter; impl SendXcm for DoNothingRouter { type Ticket = (); - fn validate(_dest: &mut Option, _msg: &mut Option>) -> SendResult<()> { - Ok(((), MultiAssets::new())) + fn validate(_dest: &mut Option, _msg: &mut Option>) -> SendResult<()> { + Ok(((), Assets::new())) } fn deliver(_: ()) -> Result { Ok([0; 32]) @@ -61,19 +61,19 @@ pub type Barrier = AllowUnpaidExecutionFrom; pub struct DummyAssetTransactor; impl TransactAsset for DummyAssetTransactor { fn deposit_asset( - _what: &MultiAsset, - _who: &MultiLocation, + _what: &Asset, + _who: &Location, _context: Option<&XcmContext>, ) -> XcmResult { Ok(()) } fn withdraw_asset( - _what: &MultiAsset, - _who: &MultiLocation, + _what: &Asset, + _who: &Location, _maybe_context: Option<&XcmContext>, - ) -> Result { - let asset: MultiAsset = (Parent, 100_000).into(); + ) -> Result { + let asset: Asset = (Parent, 100_000).into(); Ok(asset.into()) } } @@ -87,10 +87,10 @@ impl WeightTrader for DummyWeightTrader { fn buy_weight( &mut self, _weight: Weight, - _payment: Assets, + _payment: AssetsInHolding, _context: &XcmContext, - ) -> Result { - Ok(Assets::default()) + ) -> Result { + Ok(AssetsInHolding::default()) } } diff --git a/polkadot/runtime/westend/constants/src/lib.rs b/polkadot/runtime/westend/constants/src/lib.rs index a06b3ba602a3..81775e709052 100644 --- a/polkadot/runtime/westend/constants/src/lib.rs +++ b/polkadot/runtime/westend/constants/src/lib.rs @@ -99,6 +99,7 @@ pub mod fee { /// System Parachains. pub mod system_parachain { use xcm::latest::prelude::*; + use frame_support::traits::Contains; /// Network's Asset Hub parachain ID. pub const ASSET_HUB_ID: u32 = 1000; @@ -107,10 +108,14 @@ pub mod system_parachain { /// BridgeHub parachain ID. pub const BRIDGE_HUB_ID: u32 = 1002; - frame_support::match_types! { - pub type SystemParachains: impl Contains = { - MultiLocation { parents: 0, interior: X1(Parachain(ASSET_HUB_ID | COLLECTIVES_ID | BRIDGE_HUB_ID ))} - }; + pub struct SystemParachains; + impl Contains for SystemParachains { + fn contains(location: &Location) -> bool { + matches!( + location.unpack(), + (0, [Parachain(ASSET_HUB_ID | COLLECTIVES_ID | BRIDGE_HUB_ID)]) + ) + } } } diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index d80640c016f7..96da0269f55b 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -58,7 +58,7 @@ use runtime_common::{ elections::OnChainAccuracy, impl_runtime_weights, impls::{ - LocatableAssetConverter, ToAuthor, VersionedLocatableAsset, VersionedMultiLocationConverter, + LocatableAssetConverter, ToAuthor, VersionedLocatableAsset, VersionedLocationConverter, }, paras_registrar, paras_sudo_wrapper, prod_or_fast, slots, BalanceToU256, BlockHashCount, BlockLength, CurrencyToVote, SlowAdjustingFeeUpdate, U256ToBalance, @@ -96,8 +96,8 @@ use sp_std::{collections::btree_map::BTreeMap, prelude::*}; use sp_version::NativeVersion; use sp_version::RuntimeVersion; use xcm::{ - latest::{InteriorMultiLocation, Junction, Junction::PalletInstance}, - VersionedMultiLocation, + latest::{InteriorLocation, Junction, Junction::PalletInstance}, + VersionedLocation, }; use xcm_builder::PayOverXcm; @@ -705,7 +705,7 @@ parameter_types! { pub const PayoutSpendPeriod: BlockNumber = 30 * DAYS; // The asset's interior location for the paying account. This is the Treasury // pallet instance (which sits at index 37). - pub TreasuryInteriorLocation: InteriorMultiLocation = PalletInstance(37).into(); + pub TreasuryInteriorLocation: InteriorLocation = PalletInstance(37).into(); pub const TipCountdown: BlockNumber = 1 * DAYS; pub const TipFindersFee: Percent = Percent::from_percent(20); @@ -736,7 +736,7 @@ impl pallet_treasury::Config for Runtime { type SpendFunds = (); type SpendOrigin = TreasurySpender; type AssetKind = VersionedLocatableAsset; - type Beneficiary = VersionedMultiLocation; + type Beneficiary = VersionedLocation; type BeneficiaryLookup = IdentityLookup; type Paymaster = PayOverXcm< TreasuryInteriorLocation, @@ -746,7 +746,7 @@ impl pallet_treasury::Config for Runtime { Self::Beneficiary, Self::AssetKind, LocatableAssetConverter, - VersionedMultiLocationConverter, + VersionedLocationConverter, >; type BalanceConverter = AssetRate; type PayoutPeriod = PayoutSpendPeriod; @@ -2181,24 +2181,24 @@ sp_api::impl_runtime_apis! { impl pallet_offences_benchmarking::Config for Runtime {} impl pallet_election_provider_support_benchmarking::Config for Runtime {} impl pallet_xcm::benchmarking::Config for Runtime { - fn reachable_dest() -> Option { + fn reachable_dest() -> Option { Some(crate::xcm_config::AssetHub::get()) } - fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { // Relay/native token can be teleported to/from AH. Some(( - MultiAsset { fun: Fungible(EXISTENTIAL_DEPOSIT), id: Concrete(Here.into()) }, + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), id: AssetId(Here.into()) }, crate::xcm_config::AssetHub::get(), )) } - fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { // Relay can reserve transfer native token to some random parachain. Some(( - MultiAsset { + Asset { fun: Fungible(EXISTENTIAL_DEPOSIT), - id: Concrete(Here.into()) + id: AssetId(Here.into()) }, crate::Junction::Parachain(43211234).into(), )) @@ -2209,13 +2209,13 @@ sp_api::impl_runtime_apis! { impl runtime_parachains::disputes::slashing::benchmarking::Config for Runtime {} use xcm::latest::{ - AssetId::*, Fungibility::*, InteriorMultiLocation, Junction, Junctions::*, - MultiAsset, MultiAssets, MultiLocation, NetworkId, Response, + AssetId, Fungibility::*, InteriorLocation, Junction, Junctions::*, + Asset, Assets, Location, NetworkId, Response, }; use xcm_config::{AssetHub, TokenLocation}; parameter_types! { - pub ExistentialDepositMultiAsset: Option = Some(( + pub ExistentialDepositAsset: Option = Some(( TokenLocation::get(), ExistentialDeposit::get() ).into()); @@ -2227,29 +2227,29 @@ sp_api::impl_runtime_apis! { type AccountIdConverter = xcm_config::LocationConverter; type DeliveryHelper = runtime_common::xcm_sender::ToParachainDeliveryHelper< xcm_config::XcmConfig, - ExistentialDepositMultiAsset, + ExistentialDepositAsset, xcm_config::PriceForChildParachainDelivery, ToParachain, (), >; - fn valid_destination() -> Result { + fn valid_destination() -> Result { Ok(AssetHub::get()) } - fn worst_case_holding(_depositable_count: u32) -> MultiAssets { + fn worst_case_holding(_depositable_count: u32) -> Assets { // Westend only knows about WND. - vec![MultiAsset{ - id: Concrete(TokenLocation::get()), + vec![Asset{ + id: AssetId(TokenLocation::get()), fun: Fungible(1_000_000 * UNITS), }].into() } } parameter_types! { - pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + pub TrustedTeleporter: Option<(Location, Asset)> = Some(( AssetHub::get(), - MultiAsset { fun: Fungible(1 * UNITS), id: Concrete(TokenLocation::get()) }, + Asset { fun: Fungible(1 * UNITS), id: AssetId(TokenLocation::get()) }, )); - pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None; + pub const TrustedReserve: Option<(Location, Asset)> = None; } impl pallet_xcm_benchmarks::fungible::Config for Runtime { @@ -2259,9 +2259,9 @@ sp_api::impl_runtime_apis! { type TrustedTeleporter = TrustedTeleporter; type TrustedReserve = TrustedReserve; - fn get_multi_asset() -> MultiAsset { - MultiAsset { - id: Concrete(TokenLocation::get()), + fn get_asset() -> Asset { + Asset { + id: AssetId(TokenLocation::get()), fun: Fungible(1 * UNITS), } } @@ -2275,43 +2275,43 @@ sp_api::impl_runtime_apis! { (0u64, Response::Version(Default::default())) } - fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> { // Westend doesn't support asset exchanges Err(BenchmarkError::Skip) } - fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + fn universal_alias() -> Result<(Location, Junction), BenchmarkError> { // The XCM executor of Westend doesn't have a configured `UniversalAliases` Err(BenchmarkError::Skip) } - fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> { + fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> { Ok((AssetHub::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) } - fn subscribe_origin() -> Result { + fn subscribe_origin() -> Result { Ok(AssetHub::get()) } - fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { + fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> { let origin = AssetHub::get(); - let assets: MultiAssets = (Concrete(TokenLocation::get()), 1_000 * UNITS).into(); - let ticket = MultiLocation { parents: 0, interior: Here }; + let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into(); + let ticket = Location { parents: 0, interior: Here }; Ok((origin, ticket, assets)) } - fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { + fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> { // Westend doesn't support asset locking Err(BenchmarkError::Skip) } fn export_message_origin_and_destination( - ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { + ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> { // Westend doesn't support exporting messages Err(BenchmarkError::Skip) } - fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { + fn alias_origin() -> Result<(Location, Location), BenchmarkError> { // The XCM executor of Westend doesn't have a configured `Aliasers` Err(BenchmarkError::Skip) } @@ -2382,13 +2382,10 @@ mod remote_tests { } mod clean_state_migration { - use super::Runtime; + use super::{Runtime, Vec}; use frame_support::{pallet_prelude::*, storage_alias, traits::OnRuntimeUpgrade}; use pallet_state_trie_migration::MigrationLimits; - #[cfg(not(feature = "std"))] - use sp_std::prelude::*; - #[storage_alias] type AutoLimits = StorageValue, ValueQuery>; diff --git a/polkadot/runtime/westend/src/weights/xcm/mod.rs b/polkadot/runtime/westend/src/weights/xcm/mod.rs index d5b3d8257ba5..0162012825ff 100644 --- a/polkadot/runtime/westend/src/weights/xcm/mod.rs +++ b/polkadot/runtime/westend/src/weights/xcm/mod.rs @@ -36,25 +36,25 @@ pub enum AssetTypes { Unknown, } -impl From<&MultiAsset> for AssetTypes { - fn from(asset: &MultiAsset) -> Self { +impl From<&Asset> for AssetTypes { + fn from(asset: &Asset) -> Self { match asset { - MultiAsset { id: Concrete(MultiLocation { parents: 0, interior: Here }), .. } => + Asset { id: AssetId(Location { parents: 0, interior: Here }), .. } => AssetTypes::Balances, _ => AssetTypes::Unknown, } } } -trait WeighMultiAssets { - fn weigh_multi_assets(&self, balances_weight: Weight) -> Weight; +trait WeighAssets { + fn weigh_assets(&self, balances_weight: Weight) -> Weight; } // Westend only knows about one asset, the balances pallet. const MAX_ASSETS: u64 = 1; -impl WeighMultiAssets for MultiAssetFilter { - fn weigh_multi_assets(&self, balances_weight: Weight) -> Weight { +impl WeighAssets for AssetFilter { + fn weigh_assets(&self, balances_weight: Weight) -> Weight { match self { Self::Definite(assets) => assets .inner() @@ -75,11 +75,11 @@ impl WeighMultiAssets for MultiAssetFilter { } } -impl WeighMultiAssets for MultiAssets { - fn weigh_multi_assets(&self, balances_weight: Weight) -> Weight { +impl WeighAssets for Assets { + fn weigh_assets(&self, balances_weight: Weight) -> Weight { self.inner() .into_iter() - .map(|m| >::from(m)) + .map(|m| >::from(m)) .map(|t| match t { AssetTypes::Balances => balances_weight, AssetTypes::Unknown => Weight::MAX, @@ -90,32 +90,28 @@ impl WeighMultiAssets for MultiAssets { pub struct WestendXcmWeight(core::marker::PhantomData); impl XcmWeightInfo for WestendXcmWeight { - fn withdraw_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::withdraw_asset()) + fn withdraw_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::withdraw_asset()) } - fn reserve_asset_deposited(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::reserve_asset_deposited()) + fn reserve_asset_deposited(assets: &Assets) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::reserve_asset_deposited()) } - fn receive_teleported_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::receive_teleported_asset()) + fn receive_teleported_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::receive_teleported_asset()) } fn query_response( _query_id: &u64, _response: &Response, _max_weight: &Weight, - _querier: &Option, + _querier: &Option, ) -> Weight { XcmGeneric::::query_response() } - fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::transfer_asset()) + fn transfer_asset(assets: &Assets, _dest: &Location) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::transfer_asset()) } - fn transfer_reserve_asset( - assets: &MultiAssets, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::transfer_reserve_asset()) + fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::transfer_reserve_asset()) } fn transact( _origin_kind: &OriginKind, @@ -143,45 +139,37 @@ impl XcmWeightInfo for WestendXcmWeight { fn clear_origin() -> Weight { XcmGeneric::::clear_origin() } - fn descend_origin(_who: &InteriorMultiLocation) -> Weight { + fn descend_origin(_who: &InteriorLocation) -> Weight { XcmGeneric::::descend_origin() } fn report_error(_query_repsonse_info: &QueryResponseInfo) -> Weight { XcmGeneric::::report_error() } - fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::deposit_asset()) + fn deposit_asset(assets: &AssetFilter, _dest: &Location) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::deposit_asset()) } - fn deposit_reserve_asset( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::deposit_reserve_asset()) + fn deposit_reserve_asset(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::deposit_reserve_asset()) } - fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight { + fn exchange_asset(_give: &AssetFilter, _receive: &Assets, _maximal: &bool) -> Weight { // Westend does not currently support exchange asset operations Weight::MAX } fn initiate_reserve_withdraw( - assets: &MultiAssetFilter, - _reserve: &MultiLocation, + assets: &AssetFilter, + _reserve: &Location, _xcm: &Xcm<()>, ) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::initiate_reserve_withdraw()) + assets.weigh_assets(XcmBalancesWeight::::initiate_reserve_withdraw()) } - fn initiate_teleport( - assets: &MultiAssetFilter, - _dest: &MultiLocation, - _xcm: &Xcm<()>, - ) -> Weight { - assets.weigh_multi_assets(XcmBalancesWeight::::initiate_teleport()) + fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { + assets.weigh_assets(XcmBalancesWeight::::initiate_teleport()) } - fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight { + fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } - fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight { + fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } fn refund_surplus() -> Weight { @@ -196,7 +184,7 @@ impl XcmWeightInfo for WestendXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } - fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight { + fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } fn trap(_code: &u64) -> Weight { @@ -208,13 +196,13 @@ impl XcmWeightInfo for WestendXcmWeight { fn unsubscribe_version() -> Weight { XcmGeneric::::unsubscribe_version() } - fn burn_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + fn burn_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::burn_asset()) } - fn expect_asset(assets: &MultiAssets) -> Weight { - assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + fn expect_asset(assets: &Assets) -> Weight { + assets.weigh_assets(XcmGeneric::::expect_asset()) } - fn expect_origin(_origin: &Option) -> Weight { + fn expect_origin(_origin: &Option) -> Weight { XcmGeneric::::expect_origin() } fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { @@ -249,19 +237,19 @@ impl XcmWeightInfo for WestendXcmWeight { // Westend relay should not support export message operations Weight::MAX } - fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn lock_asset(_: &Asset, _: &Location) -> Weight { // Westend does not currently support asset locking operations Weight::MAX } - fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn unlock_asset(_: &Asset, _: &Location) -> Weight { // Westend does not currently support asset locking operations Weight::MAX } - fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn note_unlockable(_: &Asset, _: &Location) -> Weight { // Westend does not currently support asset locking operations Weight::MAX } - fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight { + fn request_unlock(_: &Asset, _: &Location) -> Weight { // Westend does not currently support asset locking operations Weight::MAX } @@ -274,19 +262,19 @@ impl XcmWeightInfo for WestendXcmWeight { fn clear_topic() -> Weight { XcmGeneric::::clear_topic() } - fn alias_origin(_: &MultiLocation) -> Weight { + fn alias_origin(_: &Location) -> Weight { // XCM Executor does not currently support alias origin operations Weight::MAX } - fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { + fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } } #[test] fn all_counted_has_a_sane_weight_upper_limit() { - let assets = MultiAssetFilter::Wild(AllCounted(4294967295)); + let assets = AssetFilter::Wild(AllCounted(4294967295)); let weight = Weight::from_parts(1000, 1000); - assert_eq!(assets.weigh_multi_assets(weight), weight * MAX_ASSETS); + assert_eq!(assets.weigh_assets(weight), weight * MAX_ASSETS); } diff --git a/polkadot/runtime/westend/src/xcm_config.rs b/polkadot/runtime/westend/src/xcm_config.rs index 9ab6470f6dae..700bdd48bcc4 100644 --- a/polkadot/runtime/westend/src/xcm_config.rs +++ b/polkadot/runtime/westend/src/xcm_config.rs @@ -23,8 +23,8 @@ use super::{ }; use frame_support::{ - match_types, parameter_types, - traits::{Everything, Nothing}, + parameter_types, + traits::{Everything, Nothing, Contains}, }; use frame_system::EnsureRoot; use pallet_xcm::XcmPassthrough; @@ -49,14 +49,14 @@ use xcm_builder::{ use xcm_executor::XcmExecutor; parameter_types! { - pub const TokenLocation: MultiLocation = Here.into_location(); + pub const TokenLocation: Location = Here.into_location(); pub const ThisNetwork: NetworkId = Westend; - pub const UniversalLocation: InteriorMultiLocation = X1(GlobalConsensus(ThisNetwork::get())); + pub UniversalLocation: InteriorLocation = [GlobalConsensus(ThisNetwork::get())].into(); pub CheckAccount: AccountId = XcmPallet::check_account(); pub LocalCheckAccount: (AccountId, MintLocation) = (CheckAccount::get(), MintLocation::Local); pub TreasuryAccount: AccountId = Treasury::account_id(); /// The asset ID for the asset that we use to pay for message delivery fees. - pub FeeAssetId: AssetId = Concrete(TokenLocation::get()); + pub FeeAssetId: AssetId = AssetId(TokenLocation::get()); /// The base fee for the message delivery fees. pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); } @@ -75,7 +75,7 @@ pub type LocalAssetTransactor = XcmCurrencyAdapter< Balances, // Use this currency when it is a fungible asset matching the given location or name: IsConcrete, - // We can convert the MultiLocations with our converter above: + // We can convert the Locations with our converter above: LocationConverter, // Our chain's account ID type (we can't get away without mentioning it explicitly): AccountId, @@ -108,13 +108,13 @@ pub type XcmRouter = WithUniqueTopic< >; parameter_types! { - pub const AssetHub: MultiLocation = Parachain(ASSET_HUB_ID).into_location(); - pub const Collectives: MultiLocation = Parachain(COLLECTIVES_ID).into_location(); - pub const BridgeHub: MultiLocation = Parachain(BRIDGE_HUB_ID).into_location(); - pub const Wnd: MultiAssetFilter = Wild(AllOf { fun: WildFungible, id: Concrete(TokenLocation::get()) }); - pub const WndForAssetHub: (MultiAssetFilter, MultiLocation) = (Wnd::get(), AssetHub::get()); - pub const WndForCollectives: (MultiAssetFilter, MultiLocation) = (Wnd::get(), Collectives::get()); - pub const WndForBridgeHub: (MultiAssetFilter, MultiLocation) = (Wnd::get(), BridgeHub::get()); + pub AssetHub: Location = Parachain(ASSET_HUB_ID).into_location(); + pub Collectives: Location = Parachain(COLLECTIVES_ID).into_location(); + pub BridgeHub: Location = Parachain(BRIDGE_HUB_ID).into_location(); + pub Wnd: AssetFilter = Wild(AllOf { fun: WildFungible, id: AssetId(TokenLocation::get()) }); + pub WndForAssetHub: (AssetFilter, Location) = (Wnd::get(), AssetHub::get()); + pub WndForCollectives: (AssetFilter, Location) = (Wnd::get(), Collectives::get()); + pub WndForBridgeHub: (AssetFilter, Location) = (Wnd::get(), BridgeHub::get()); pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 64; } @@ -125,14 +125,18 @@ pub type TrustedTeleporters = ( xcm_builder::Case, ); -match_types! { - pub type OnlyParachains: impl Contains = { - MultiLocation { parents: 0, interior: X1(Parachain(_)) } - }; - pub type CollectivesOrFellows: impl Contains = { - MultiLocation { parents: 0, interior: X1(Parachain(COLLECTIVES_ID)) } | - MultiLocation { parents: 0, interior: X2(Parachain(COLLECTIVES_ID), Plurality { id: BodyId::Technical, .. }) } - }; +pub struct OnlyParachains; +impl Contains for OnlyParachains { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (0, [Parachain(_)])) + } +} + +pub struct CollectivesOrFellows; +impl Contains for CollectivesOrFellows { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (0, [Parachain(COLLECTIVES_ID)]) | (0, [Parachain(COLLECTIVES_ID), Plurality { id: BodyId::Technical, .. }])) + } } /// The barriers one of which must be passed for an XCM message to be executed. @@ -200,11 +204,10 @@ parameter_types! { pub const FellowshipAdminBodyId: BodyId = BodyId::Index(FELLOWSHIP_ADMIN_INDEX); } -/// Type to convert the `GeneralAdmin` origin to a Plurality `MultiLocation` value. +/// Type to convert the `GeneralAdmin` origin to a Plurality `Location` value. pub type GeneralAdminToPlurality = OriginToPluralityVoice; -/// Type to convert an `Origin` type value into a `MultiLocation` value which represents an interior /// location of this chain. pub type LocalOriginToLocation = ( GeneralAdminToPlurality, @@ -212,22 +215,22 @@ pub type LocalOriginToLocation = ( SignedToAccountId32, ); -/// Type to convert the `StakingAdmin` origin to a Plurality `MultiLocation` value. +/// Type to convert the `StakingAdmin` origin to a Plurality `Location` value. pub type StakingAdminToPlurality = OriginToPluralityVoice; -/// Type to convert the `FellowshipAdmin` origin to a Plurality `MultiLocation` value. +/// Type to convert the `FellowshipAdmin` origin to a Plurality `Location` value. pub type FellowshipAdminToPlurality = OriginToPluralityVoice; -/// Type to convert a pallet `Origin` type value into a `MultiLocation` value which represents an +/// Type to convert a pallet `Origin` type value into a `Location` value which represents an /// interior location of this chain for a destination chain. pub type LocalPalletOriginToLocation = ( - // GeneralAdmin origin to be used in XCM as a corresponding Plurality `MultiLocation` value. + // GeneralAdmin origin to be used in XCM as a corresponding Plurality `Location` value. GeneralAdminToPlurality, - // StakingAdmin origin to be used in XCM as a corresponding Plurality `MultiLocation` value. + // StakingAdmin origin to be used in XCM as a corresponding Plurality `Location` value. StakingAdminToPlurality, - // FellowshipAdmin origin to be used in XCM as a corresponding Plurality `MultiLocation` value. + // FellowshipAdmin origin to be used in XCM as a corresponding Plurality `Location` value. FellowshipAdminToPlurality, ); diff --git a/polkadot/xcm/Cargo.toml b/polkadot/xcm/Cargo.toml index 60c27f7fcfc3..b7a94c1063ee 100644 --- a/polkadot/xcm/Cargo.toml +++ b/polkadot/xcm/Cargo.toml @@ -14,7 +14,7 @@ log = { version = "0.4.17", default-features = false } parity-scale-codec = { version = "3.6.1", default-features = false, features = [ "derive", "max-encoded-len" ] } scale-info = { version = "2.10.0", default-features = false, features = ["derive", "serde"] } sp-weights = { path = "../../substrate/primitives/weights", default-features = false, features = ["serde"] } -serde = { version = "1.0.188", default-features = false, features = ["alloc", "derive"] } +serde = { version = "1.0.188", default-features = false, features = ["alloc", "derive", "rc"] } xcm-procedural = { path = "procedural" } environmental = { version = "1.1.4", default-features = false } diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs index d32eb8d4a52f..e96ec48fcba4 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs @@ -24,7 +24,7 @@ use frame_support::{ }; use sp_runtime::traits::{Bounded, Zero}; use sp_std::{prelude::*, vec}; -use xcm::latest::{prelude::*, MAX_ITEMS_IN_MULTIASSETS}; +use xcm::latest::{prelude::*, MAX_ITEMS_IN_ASSETS}; use xcm_executor::traits::{ConvertLocation, FeeReason, TransactAsset}; benchmarks_instance_pallet! { @@ -43,7 +43,7 @@ benchmarks_instance_pallet! { withdraw_asset { let (sender_account, sender_location) = account_and_location::(1); let worst_case_holding = T::worst_case_holding(0); - let asset = T::get_multi_asset(); + let asset = T::get_asset(); >::deposit_asset(&asset, &sender_location, None).unwrap(); // check the assets of origin. @@ -63,8 +63,8 @@ benchmarks_instance_pallet! { transfer_asset { let (sender_account, sender_location) = account_and_location::(1); - let asset = T::get_multi_asset(); - let assets: MultiAssets = vec![ asset.clone() ].into(); + let asset = T::get_asset(); + let assets: Assets = vec![ asset.clone() ].into(); // this xcm doesn't use holding let dest_location = T::valid_destination()?; @@ -95,10 +95,10 @@ benchmarks_instance_pallet! { ); let sender_account_balance_before = T::TransactAsset::balance(&sender_account); - let asset = T::get_multi_asset(); + let asset = T::get_asset(); >::deposit_asset(&asset, &sender_location, None).unwrap(); assert!(T::TransactAsset::balance(&sender_account) > sender_account_balance_before); - let assets: MultiAssets = vec![ asset ].into(); + let assets: Assets = vec![asset].into(); assert!(T::TransactAsset::balance(&dest_account).is_zero()); let mut executor = new_executor::(sender_location); @@ -129,7 +129,7 @@ benchmarks_instance_pallet! { BenchmarkResult::from_weight(Weight::MAX) ))?; - let assets: MultiAssets = vec![ transferable_reserve_asset ].into(); + let assets: Assets = vec![ transferable_reserve_asset ].into(); let mut executor = new_executor::(trusted_reserve); let instruction = Instruction::ReserveAssetDeposited(assets.clone()); @@ -143,7 +143,7 @@ benchmarks_instance_pallet! { initiate_reserve_withdraw { let (sender_account, sender_location) = account_and_location::(1); let holding = T::worst_case_holding(1); - let assets_filter = MultiAssetFilter::Definite(holding.clone().into_inner().into_iter().take(MAX_ITEMS_IN_MULTIASSETS).collect::>().into()); + let assets_filter = AssetFilter::Definite(holding.clone().into_inner().into_iter().take(MAX_ITEMS_IN_ASSETS).collect::>().into()); let reserve = T::valid_destination().map_err(|_| BenchmarkError::Skip)?; let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( @@ -188,7 +188,7 @@ benchmarks_instance_pallet! { )?; } - let assets: MultiAssets = vec![ teleportable_asset ].into(); + let assets: Assets = vec![ teleportable_asset ].into(); let mut executor = new_executor::(trusted_teleporter); let instruction = Instruction::ReceiveTeleportedAsset(assets.clone()); @@ -204,7 +204,7 @@ benchmarks_instance_pallet! { } deposit_asset { - let asset = T::get_multi_asset(); + let asset = T::get_asset(); let mut holding = T::worst_case_holding(1); // Add our asset to the holding. @@ -230,7 +230,7 @@ benchmarks_instance_pallet! { } deposit_reserve_asset { - let asset = T::get_multi_asset(); + let asset = T::get_asset(); let mut holding = T::worst_case_holding(1); // Add our asset to the holding. @@ -257,7 +257,7 @@ benchmarks_instance_pallet! { } initiate_teleport { - let asset = T::get_multi_asset(); + let asset = T::get_asset(); let mut holding = T::worst_case_holding(0); // Add our asset to the holding. diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/mock.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/mock.rs index 9adc706fc18a..79e2322ebff4 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/mock.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/mock.rs @@ -91,10 +91,10 @@ parameter_types! { pub struct MatchAnyFungible; impl xcm_executor::traits::MatchesFungible for MatchAnyFungible { - fn matches_fungible(m: &MultiAsset) -> Option { + fn matches_fungible(m: &Asset) -> Option { use sp_runtime::traits::SaturatedConversion; match m { - MultiAsset { fun: Fungible(amount), .. } => Some((*amount).saturated_into::()), + Asset { fun: Fungible(amount), .. } => Some((*amount).saturated_into::()), _ => None, } } @@ -148,13 +148,13 @@ impl crate::Config for Test { type XcmConfig = XcmConfig; type AccountIdConverter = AccountIdConverter; type DeliveryHelper = (); - fn valid_destination() -> Result { - let valid_destination: MultiLocation = - X1(AccountId32 { network: None, id: [0u8; 32] }).into(); + fn valid_destination() -> Result { + let valid_destination: Location = + [AccountId32 { network: None, id: [0u8; 32] }].into(); Ok(valid_destination) } - fn worst_case_holding(depositable_count: u32) -> MultiAssets { + fn worst_case_holding(depositable_count: u32) -> Assets { crate::mock_worst_case_holding( depositable_count, ::MaxAssetsIntoHolding::get(), @@ -167,19 +167,19 @@ pub type TrustedReserves = xcm_builder::Case; parameter_types! { pub const CheckingAccount: Option<(u64, MintLocation)> = Some((100, MintLocation::Local)); - pub const ChildTeleporter: MultiLocation = Parachain(1000).into_location(); - pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + pub ChildTeleporter: Location = Parachain(1000).into_location(); + pub TrustedTeleporter: Option<(Location, Asset)> = Some(( ChildTeleporter::get(), - MultiAsset { id: Concrete(Here.into_location()), fun: Fungible(100) }, + Asset { id: AssetId(Here.into_location()), fun: Fungible(100) }, )); - pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = Some(( + pub TrustedReserve: Option<(Location, Asset)> = Some(( ChildTeleporter::get(), - MultiAsset { id: Concrete(Here.into_location()), fun: Fungible(100) }, + Asset { id: AssetId(Here.into_location()), fun: Fungible(100) }, )); - pub const TeleportConcreteFungible: (MultiAssetFilter, MultiLocation) = - (Wild(AllOf { fun: WildFungible, id: Concrete(Here.into_location()) }), ChildTeleporter::get()); - pub const ReserveConcreteFungible: (MultiAssetFilter, MultiLocation) = - (Wild(AllOf { fun: WildFungible, id: Concrete(Here.into_location()) }), ChildTeleporter::get()); + pub TeleportConcreteFungible: (AssetFilter, Location) = + (Wild(AllOf { fun: WildFungible, id: AssetId(Here.into_location()) }), ChildTeleporter::get()); + pub ReserveConcreteFungible: (AssetFilter, Location) = + (Wild(AllOf { fun: WildFungible, id: AssetId(Here.into_location()) }), ChildTeleporter::get()); } impl xcm_balances_benchmark::Config for Test { @@ -188,10 +188,10 @@ impl xcm_balances_benchmark::Config for Test { type TrustedTeleporter = TrustedTeleporter; type TrustedReserve = TrustedReserve; - fn get_multi_asset() -> MultiAsset { + fn get_asset() -> Asset { let amount = >::minimum_balance() as u128; - MultiAsset { id: Concrete(Here.into()), fun: Fungible(amount) } + Asset { id: AssetId(Here.into()), fun: Fungible(amount) } } } diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/mod.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/mod.rs index 292921eb595f..e84355f4092b 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/mod.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/mod.rs @@ -37,14 +37,14 @@ pub mod pallet { type CheckedAccount: Get>; /// A trusted location which we allow teleports from, and the asset we allow to teleport. - type TrustedTeleporter: Get>; + type TrustedTeleporter: Get>; /// A trusted location where reserve assets are stored, and the asset we allow to be /// reserves. - type TrustedReserve: Get>; + type TrustedReserve: Get>; /// Give me a fungible asset that your asset transactor is going to accept. - fn get_multi_asset() -> xcm::latest::MultiAsset; + fn get_asset() -> xcm::latest::Asset; } #[pallet::pallet] diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs index 4a997666027f..87194e5bb6dd 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs @@ -77,7 +77,7 @@ benchmarks! { let mut executor = new_executor::(Default::default()); executor.set_holding(holding); - let fee_asset = Concrete(Here.into()); + let fee_asset = AssetId(Here.into()); let instruction = Instruction::>::BuyExecution { fees: (fee_asset, 100_000_000u128).into(), // should be something inside of holding @@ -95,7 +95,7 @@ benchmarks! { let mut executor = new_executor::(Default::default()); let (query_id, response) = T::worst_case_response(); let max_weight = Weight::MAX; - let querier: Option = Some(Here.into()); + let querier: Option = Some(Here.into()); let instruction = Instruction::QueryResponse { query_id, response, max_weight, querier }; let xcm = Xcm(vec![instruction]); }: { @@ -174,7 +174,7 @@ benchmarks! { descend_origin { let mut executor = new_executor::(Default::default()); - let who = X2(OnlyChild, OnlyChild); + let who = Junctions::from([OnlyChild, OnlyChild]); let instruction = Instruction::DescendOrigin(who.clone()); let xcm = Xcm(vec![instruction]); } : { @@ -182,7 +182,7 @@ benchmarks! { } verify { assert_eq!( executor.origin(), - &Some(MultiLocation { + &Some(Location { parents: 0, interior: who, }), @@ -544,7 +544,7 @@ benchmarks! { } verify { use frame_support::traits::Get; let universal_location = ::UniversalLocation::get(); - assert_eq!(executor.origin(), &Some(X1(alias).relative_to(&universal_location))); + assert_eq!(executor.origin(), &Some(Junctions::from([alias]).relative_to(&universal_location))); } export_message { @@ -560,8 +560,8 @@ benchmarks! { let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( &origin, - &destination.into(), - FeeReason::Export { network, destination }, + &destination.clone().into(), + FeeReason::Export { network, destination: destination.clone() }, ); let sender_account = T::AccountIdConverter::convert_location(&origin).unwrap(); let sender_account_balance_before = T::TransactAsset::balance(&sender_account); @@ -574,7 +574,7 @@ benchmarks! { executor.set_holding(expected_assets_in_holding.into()); } let xcm = Xcm(vec![ExportMessage { - network, destination, xcm: inner_xcm, + network, destination: destination.clone(), xcm: inner_xcm, }]); }: { executor.bench_process(xcm)?; diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mock.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mock.rs index 710ff0d80192..d84b9506019f 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mock.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mock.rs @@ -19,15 +19,15 @@ use crate::{generic, mock::*, *}; use codec::Decode; use frame_support::{ - derive_impl, match_types, parameter_types, - traits::{Everything, OriginTrait}, + derive_impl, parameter_types, + traits::{Contains, Everything, OriginTrait}, weights::Weight, }; use sp_core::H256; use sp_runtime::traits::{BlakeTwo256, IdentityLookup, TrailingZeroInput}; use xcm_builder::{ test_utils::{ - Assets, TestAssetExchanger, TestAssetLocker, TestAssetTrap, TestSubscriptionService, + AssetsInHolding, TestAssetExchanger, TestAssetLocker, TestAssetTrap, TestSubscriptionService, TestUniversalAliases, }, AliasForeignAccountId32, AllowUnpaidExecutionFrom, @@ -81,18 +81,18 @@ impl frame_system::Config for Test { pub struct NoAssetTransactor; impl xcm_executor::traits::TransactAsset for NoAssetTransactor { fn deposit_asset( - _: &MultiAsset, - _: &MultiLocation, + _: &Asset, + _: &Location, _: Option<&XcmContext>, ) -> Result<(), XcmError> { unreachable!(); } fn withdraw_asset( - _: &MultiAsset, - _: &MultiLocation, + _: &Asset, + _: &Location, _: Option<&XcmContext>, - ) -> Result { + ) -> Result { unreachable!(); } } @@ -102,10 +102,11 @@ parameter_types! { pub const MaxAssetsIntoHolding: u32 = 64; } -match_types! { - pub type OnlyParachains: impl Contains = { - MultiLocation { parents: 0, interior: X1(Parachain(_)) } - }; +pub struct OnlyParachains; +impl Contains for OnlyParachains { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (0, [Parachain(_)])) + } } type Aliasers = AliasForeignAccountId32; @@ -152,13 +153,13 @@ impl crate::Config for Test { type XcmConfig = XcmConfig; type AccountIdConverter = AccountIdConverter; type DeliveryHelper = (); - fn valid_destination() -> Result { - let valid_destination: MultiLocation = + fn valid_destination() -> Result { + let valid_destination: Location = Junction::AccountId32 { network: None, id: [0u8; 32] }.into(); Ok(valid_destination) } - fn worst_case_holding(depositable_count: u32) -> MultiAssets { + fn worst_case_holding(depositable_count: u32) -> Assets { crate::mock_worst_case_holding( depositable_count, ::MaxAssetsIntoHolding::get(), @@ -171,48 +172,47 @@ impl generic::Config for Test { type RuntimeCall = RuntimeCall; fn worst_case_response() -> (u64, Response) { - let assets: MultiAssets = (Concrete(Here.into()), 100).into(); + let assets: Assets = (AssetId(Here.into()), 100).into(); (0, Response::Assets(assets)) } - fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> { Ok(Default::default()) } - fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + fn universal_alias() -> Result<(Location, Junction), BenchmarkError> { Ok((Here.into(), GlobalConsensus(ByGenesis([0; 32])))) } fn transact_origin_and_runtime_call( - ) -> Result<(MultiLocation, ::RuntimeCall), BenchmarkError> { + ) -> Result<(Location, ::RuntimeCall), BenchmarkError> { Ok((Default::default(), frame_system::Call::remark_with_event { remark: vec![] }.into())) } - fn subscribe_origin() -> Result { + fn subscribe_origin() -> Result { Ok(Default::default()) } - fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { - let assets: MultiAssets = (Concrete(Here.into()), 100).into(); - let ticket = MultiLocation { parents: 0, interior: X1(GeneralIndex(0)) }; + fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> { + let assets: Assets = (AssetId(Here.into()), 100).into(); + let ticket = Location { parents: 0, interior: [GeneralIndex(0)].into() }; Ok((Default::default(), ticket, assets)) } - fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { - let assets: MultiAsset = (Concrete(Here.into()), 100).into(); + fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> { + let assets: Asset = (AssetId(Here.into()), 100).into(); Ok((Default::default(), account_id_junction::(1).into(), assets)) } fn export_message_origin_and_destination( - ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { + ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> { // No MessageExporter in tests Err(BenchmarkError::Skip) } - fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { - let origin: MultiLocation = - (Parachain(1), AccountId32 { network: None, id: [0; 32] }).into(); - let target: MultiLocation = AccountId32 { network: None, id: [0; 32] }.into(); + fn alias_origin() -> Result<(Location, Location), BenchmarkError> { + let origin: Location = (Parachain(1), AccountId32 { network: None, id: [0; 32] }).into(); + let target: Location = AccountId32 { network: None, id: [0; 32] }.into(); Ok((origin, target)) } } @@ -232,9 +232,9 @@ where ::AccountId: Decode, { fn convert_origin( - _origin: impl Into, + _origin: impl Into, _kind: OriginKind, - ) -> Result { + ) -> Result { Ok(RuntimeOrigin::signed( ::AccountId::decode(&mut TrailingZeroInput::zeroes()) .expect("infinite length input; no invalid inputs for type; qed"), diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mod.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mod.rs index cbdfa8d0112c..a533fd22c983 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mod.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mod.rs @@ -26,10 +26,7 @@ pub mod pallet { use frame_benchmarking::BenchmarkError; use frame_support::{dispatch::GetDispatchInfo, pallet_prelude::Encode}; use sp_runtime::traits::Dispatchable; - use xcm::latest::{ - InteriorMultiLocation, Junction, MultiAsset, MultiAssets, MultiLocation, NetworkId, - Response, - }; + use xcm::latest::{Asset, Assets, InteriorLocation, Junction, Location, NetworkId, Response}; #[pallet::config] pub trait Config: frame_system::Config + crate::Config { @@ -53,44 +50,44 @@ pub mod pallet { /// from, whereas the second element represents the assets that are being exchanged to. /// /// If set to `Err`, benchmarks which rely on an `exchange_asset` will be skipped. - fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError>; + fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError>; - /// A `(MultiLocation, Junction)` that is one of the `UniversalAliases` configured by the + /// A `(Location, Junction)` that is one of the `UniversalAliases` configured by the /// XCM executor. /// /// If set to `Err`, benchmarks which rely on a universal alias will be skipped. - fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError>; + fn universal_alias() -> Result<(Location, Junction), BenchmarkError>; - /// The `MultiLocation` and `RuntimeCall` used for successful transaction XCMs. + /// The `Location` and `RuntimeCall` used for successful transaction XCMs. /// /// If set to `Err`, benchmarks which rely on a `transact_origin_and_runtime_call` will be /// skipped. fn transact_origin_and_runtime_call( - ) -> Result<(MultiLocation, >::RuntimeCall), BenchmarkError>; + ) -> Result<(Location, >::RuntimeCall), BenchmarkError>; - /// A valid `MultiLocation` we can successfully subscribe to. + /// A valid `Location` we can successfully subscribe to. /// /// If set to `Err`, benchmarks which rely on a `subscribe_origin` will be skipped. - fn subscribe_origin() -> Result; + fn subscribe_origin() -> Result; /// Return an origin, ticket, and assets that can be trapped and claimed. - fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError>; + fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError>; /// Return an unlocker, owner and assets that can be locked and unlocked. - fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError>; + fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError>; - /// A `(MultiLocation, NetworkId, InteriorMultiLocation)` we can successfully export message + /// A `(Location, NetworkId, InteriorLocation)` we can successfully export message /// to. /// /// If set to `Err`, benchmarks which rely on `export_message` will be skipped. fn export_message_origin_and_destination( - ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError>; + ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError>; - /// A `(MultiLocation, MultiLocation)` that is one of the `Aliasers` configured by the XCM + /// A `(Location, Location)` that is one of the `Aliasers` configured by the XCM /// executor. /// /// If set to `Err`, benchmarks which rely on a universal alias will be skipped. - fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError>; + fn alias_origin() -> Result<(Location, Location), BenchmarkError>; } #[pallet::pallet] diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/lib.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/lib.rs index 3bf4aea1b25e..6ce8d3e99e8e 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/lib.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/lib.rs @@ -41,18 +41,18 @@ pub trait Config: frame_system::Config { /// `TransactAsset` is implemented. type XcmConfig: XcmConfig; - /// A converter between a multi-location to a sovereign account. + /// A converter between a location to a sovereign account. type AccountIdConverter: ConvertLocation; /// Helper that ensures successful delivery for XCM instructions which need `SendXcm`. type DeliveryHelper: EnsureDelivery; /// Does any necessary setup to create a valid destination for XCM messages. - /// Returns that destination's multi-location to be used in benchmarks. - fn valid_destination() -> Result; + /// Returns that destination's location to be used in benchmarks. + fn valid_destination() -> Result; /// Worst case scenario for a holding account in this runtime. - fn worst_case_holding(depositable_count: u32) -> MultiAssets; + fn worst_case_holding(depositable_count: u32) -> Assets; } const SEED: u32 = 0; @@ -66,21 +66,21 @@ pub type AssetTransactorOf = <::XcmConfig as XcmConfig>::AssetTr /// The call type of executor's config. Should eventually resolve to the same overarching call type. pub type XcmCallOf = <::XcmConfig as XcmConfig>::RuntimeCall; -pub fn mock_worst_case_holding(depositable_count: u32, max_assets: u32) -> MultiAssets { +pub fn mock_worst_case_holding(depositable_count: u32, max_assets: u32) -> Assets { let fungibles_amount: u128 = 100; let holding_fungibles = max_assets / 2 - depositable_count; let holding_non_fungibles = holding_fungibles; (0..holding_fungibles) .map(|i| { - MultiAsset { - id: Concrete(GeneralIndex(i as u128).into()), + Asset { + id: AssetId(GeneralIndex(i as u128).into()), fun: Fungible(fungibles_amount * i as u128), } .into() }) - .chain(core::iter::once(MultiAsset { id: Concrete(Here.into()), fun: Fungible(u128::MAX) })) - .chain((0..holding_non_fungibles).map(|i| MultiAsset { - id: Concrete(GeneralIndex(i as u128).into()), + .chain(core::iter::once(Asset { id: AssetId(Here.into()), fun: Fungible(u128::MAX) })) + .chain((0..holding_non_fungibles).map(|i| Asset { + id: AssetId(GeneralIndex(i as u128).into()), fun: NonFungible(asset_instance_from(i)), })) .collect::>() @@ -94,11 +94,11 @@ pub fn asset_instance_from(x: u32) -> AssetInstance { AssetInstance::Array4(instance) } -pub fn new_executor(origin: MultiLocation) -> ExecutorOf { +pub fn new_executor(origin: Location) -> ExecutorOf { ExecutorOf::::new(origin, [0; 32]) } -/// Build a multi-location from an account id. +/// Build a location from an account id. fn account_id_junction(index: u32) -> Junction { let account: T::AccountId = account("account", index, SEED); let mut encoded = account.encode(); @@ -108,8 +108,8 @@ fn account_id_junction(index: u32) -> Junction { Junction::AccountId32 { network: None, id } } -pub fn account_and_location(index: u32) -> (T::AccountId, MultiLocation) { - let location: MultiLocation = account_id_junction::(index).into(); +pub fn account_and_location(index: u32) -> (T::AccountId, Location) { + let location: Location = account_id_junction::(index).into(); let account = T::AccountIdConverter::convert_location(&location).unwrap(); (account, location) @@ -121,21 +121,21 @@ pub trait EnsureDelivery { /// Prepare all requirements for successful `XcmSender: SendXcm` passing (accounts, balances, /// channels ...). Returns: /// - possible `FeesMode` which is expected to be set to executor - /// - possible `MultiAssets` which are expected to be subsume to the Holding Register + /// - possible `Assets` which are expected to be subsume to the Holding Register fn ensure_successful_delivery( - origin_ref: &MultiLocation, - dest: &MultiLocation, + origin_ref: &Location, + dest: &Location, fee_reason: FeeReason, - ) -> (Option, Option); + ) -> (Option, Option); } /// `()` implementation does nothing which means no special requirements for environment. impl EnsureDelivery for () { fn ensure_successful_delivery( - _origin_ref: &MultiLocation, - _dest: &MultiLocation, + _origin_ref: &Location, + _dest: &Location, _fee_reason: FeeReason, - ) -> (Option, Option) { + ) -> (Option, Option) { // doing nothing (None, None) } diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/mock.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/mock.rs index e02c5bf08615..78a9e5f8a018 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/mock.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/mock.rs @@ -22,8 +22,8 @@ use xcm::latest::Weight; pub struct DevNull; impl xcm::opaque::latest::SendXcm for DevNull { type Ticket = (); - fn validate(_: &mut Option, _: &mut Option>) -> SendResult<()> { - Ok(((), MultiAssets::new())) + fn validate(_: &mut Option, _: &mut Option>) -> SendResult<()> { + Ok(((), Assets::new())) } fn deliver(_: ()) -> Result { Ok([0; 32]) @@ -31,13 +31,13 @@ impl xcm::opaque::latest::SendXcm for DevNull { } impl xcm_executor::traits::OnResponse for DevNull { - fn expecting_response(_: &MultiLocation, _: u64, _: Option<&MultiLocation>) -> bool { + fn expecting_response(_: &Location, _: u64, _: Option<&Location>) -> bool { false } fn on_response( - _: &MultiLocation, + _: &Location, _: u64, - _: Option<&MultiLocation>, + _: Option<&Location>, _: Response, _: Weight, _: &XcmContext, @@ -48,9 +48,9 @@ impl xcm_executor::traits::OnResponse for DevNull { pub struct AccountIdConverter; impl xcm_executor::traits::ConvertLocation for AccountIdConverter { - fn convert_location(ml: &MultiLocation) -> Option { - match ml { - MultiLocation { parents: 0, interior: X1(Junction::AccountId32 { id, .. }) } => + fn convert_location(ml: &Location) -> Option { + match ml.unpack() { + (0, [Junction::AccountId32 { id, .. }]) => Some(::decode(&mut &*id.to_vec()).unwrap()), _ => None, } @@ -58,14 +58,14 @@ impl xcm_executor::traits::ConvertLocation for AccountIdConverter { } parameter_types! { - pub UniversalLocation: InteriorMultiLocation = Junction::Parachain(101).into(); + pub UniversalLocation: InteriorLocation = Junction::Parachain(101).into(); pub UnitWeightCost: Weight = Weight::from_parts(10, 10); - pub WeightPrice: (AssetId, u128, u128) = (Concrete(Here.into()), 1_000_000, 1024); + pub WeightPrice: (AssetId, u128, u128) = (AssetId(Here.into()), 1_000_000, 1024); } pub struct AllAssetLocationsPass; -impl ContainsPair for AllAssetLocationsPass { - fn contains(_: &MultiAsset, _: &MultiLocation) -> bool { +impl ContainsPair for AllAssetLocationsPass { + fn contains(_: &Asset, _: &Location) -> bool { true } } diff --git a/polkadot/xcm/pallet-xcm/src/benchmarking.rs b/polkadot/xcm/pallet-xcm/src/benchmarking.rs index 3aca24791fc2..d9e0edb52f47 100644 --- a/polkadot/xcm/pallet-xcm/src/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm/src/benchmarking.rs @@ -32,30 +32,30 @@ pub struct Pallet(crate::Pallet); /// Trait that must be implemented by runtime to be able to benchmark pallet properly. pub trait Config: crate::Config { - /// A `MultiLocation` that can be reached via `XcmRouter`. Used only in benchmarks. + /// A `Location` that can be reached via `XcmRouter`. Used only in benchmarks. /// /// If `None`, the benchmarks that depend on a reachable destination will be skipped. - fn reachable_dest() -> Option { + fn reachable_dest() -> Option { None } - /// A `(MultiAsset, MultiLocation)` pair representing asset and the destination it can be + /// A `(Asset, Location)` pair representing asset and the destination it can be /// teleported to. Used only in benchmarks. /// /// Implementation should also make sure `dest` is reachable/connected. /// /// If `None`, the benchmarks that depend on this will be skipped. - fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { None } - /// A `(MultiAsset, MultiLocation)` pair representing asset and the destination it can be + /// A `(Asset, Location)` pair representing asset and the destination it can be /// reserve-transferred to. Used only in benchmarks. /// /// Implementation should also make sure `dest` is reachable/connected. /// /// If `None`, the benchmarks that depend on this will be skipped. - fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { None } } @@ -73,7 +73,7 @@ benchmarks! { return Err(BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX))) } let msg = Xcm(vec![ClearOrigin]); - let versioned_dest: VersionedMultiLocation = T::reachable_dest().ok_or( + let versioned_dest: VersionedLocation = T::reachable_dest().ok_or( BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)), )? .into(); @@ -89,7 +89,7 @@ benchmarks! { Fungible(amount) => *amount, _ => return Err(BenchmarkError::Stop("Benchmark asset not fungible")), }.into(); - let assets: MultiAssets = asset.into(); + let assets: Assets = asset.into(); let existential_deposit = T::ExistentialDeposit::get(); let caller = whitelisted_caller(); @@ -109,10 +109,10 @@ benchmarks! { } let recipient = [0u8; 32]; - let versioned_dest: VersionedMultiLocation = destination.into(); - let versioned_beneficiary: VersionedMultiLocation = + let versioned_dest: VersionedLocation = destination.into(); + let versioned_beneficiary: VersionedLocation = AccountId32 { network: None, id: recipient.into() }.into(); - let versioned_assets: VersionedMultiAssets = assets.into(); + let versioned_assets: VersionedAssets = assets.into(); }: _>(send_origin.into(), Box::new(versioned_dest), Box::new(versioned_beneficiary), Box::new(versioned_assets), 0) verify { // verify balance after transfer, decreased by transferred amount (+ maybe XCM delivery fees) @@ -128,7 +128,7 @@ benchmarks! { Fungible(amount) => *amount, _ => return Err(BenchmarkError::Stop("Benchmark asset not fungible")), }.into(); - let assets: MultiAssets = asset.into(); + let assets: Assets = asset.into(); let existential_deposit = T::ExistentialDeposit::get(); let caller = whitelisted_caller(); @@ -148,10 +148,10 @@ benchmarks! { } let recipient = [0u8; 32]; - let versioned_dest: VersionedMultiLocation = destination.into(); - let versioned_beneficiary: VersionedMultiLocation = + let versioned_dest: VersionedLocation = destination.into(); + let versioned_beneficiary: VersionedLocation = AccountId32 { network: None, id: recipient.into() }.into(); - let versioned_assets: VersionedMultiAssets = assets.into(); + let versioned_assets: VersionedAssets = assets.into(); }: _>(send_origin.into(), Box::new(versioned_dest), Box::new(versioned_beneficiary), Box::new(versioned_assets), 0) verify { // verify balance after transfer, decreased by transferred amount (+ maybe XCM delivery fees) @@ -180,7 +180,7 @@ benchmarks! { force_default_xcm_version {}: _(RawOrigin::Root, Some(2)) force_subscribe_version_notify { - let versioned_loc: VersionedMultiLocation = T::reachable_dest().ok_or( + let versioned_loc: VersionedLocation = T::reachable_dest().ok_or( BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)), )? .into(); @@ -190,7 +190,7 @@ benchmarks! { let loc = T::reachable_dest().ok_or( BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)), )?; - let versioned_loc: VersionedMultiLocation = loc.into(); + let versioned_loc: VersionedLocation = loc.clone().into(); let _ = crate::Pallet::::request_version_notify(loc); }: _(RawOrigin::Root, Box::new(versioned_loc)) @@ -198,7 +198,7 @@ benchmarks! { migrate_supported_version { let old_version = XCM_VERSION - 1; - let loc = VersionedMultiLocation::from(MultiLocation::from(Parent)); + let loc = VersionedLocation::from(Location::from(Parent)); SupportedVersion::::insert(old_version, loc, old_version); }: { crate::Pallet::::check_xcm_version_change(VersionMigrationStage::MigrateSupportedVersion, Weight::zero()); @@ -206,7 +206,7 @@ benchmarks! { migrate_version_notifiers { let old_version = XCM_VERSION - 1; - let loc = VersionedMultiLocation::from(MultiLocation::from(Parent)); + let loc = VersionedLocation::from(Location::from(Parent)); VersionNotifiers::::insert(old_version, loc, 0); }: { crate::Pallet::::check_xcm_version_change(VersionMigrationStage::MigrateVersionNotifiers, Weight::zero()); @@ -216,7 +216,7 @@ benchmarks! { let loc = T::reachable_dest().ok_or( BenchmarkError::Override(BenchmarkResult::from_weight(T::DbWeight::get().reads(1))), )?; - let loc = VersionedMultiLocation::from(loc); + let loc = VersionedLocation::from(loc); let current_version = T::AdvertisedXcmVersion::get(); VersionNotifyTargets::::insert(current_version, loc, (0, Weight::zero(), current_version)); }: { @@ -227,7 +227,7 @@ benchmarks! { let loc = T::reachable_dest().ok_or( BenchmarkError::Override(BenchmarkResult::from_weight(T::DbWeight::get().reads_writes(1, 3))), )?; - let loc = VersionedMultiLocation::from(loc); + let loc = VersionedLocation::from(loc); let current_version = T::AdvertisedXcmVersion::get(); let old_version = current_version - 1; VersionNotifyTargets::::insert(current_version, loc, (0, Weight::zero(), old_version)); @@ -242,7 +242,7 @@ benchmarks! { part: v2::BodyPart::Voice, } .into(); - let bad_loc = VersionedMultiLocation::from(bad_loc); + let bad_loc = VersionedLocation::from(bad_loc); let current_version = T::AdvertisedXcmVersion::get(); VersionNotifyTargets::::insert(current_version, bad_loc, (0, Weight::zero(), current_version)); }: { @@ -252,7 +252,7 @@ benchmarks! { migrate_version_notify_targets { let current_version = T::AdvertisedXcmVersion::get(); let old_version = current_version - 1; - let loc = VersionedMultiLocation::from(MultiLocation::from(Parent)); + let loc = VersionedLocation::from(Location::from(Parent)); VersionNotifyTargets::::insert(old_version, loc, (0, Weight::zero(), current_version)); }: { crate::Pallet::::check_xcm_version_change(VersionMigrationStage::MigrateAndNotifyOldTargets, Weight::zero()); @@ -262,7 +262,7 @@ benchmarks! { let loc = T::reachable_dest().ok_or( BenchmarkError::Override(BenchmarkResult::from_weight(T::DbWeight::get().reads_writes(1, 3))), )?; - let loc = VersionedMultiLocation::from(loc); + let loc = VersionedLocation::from(loc); let old_version = T::AdvertisedXcmVersion::get() - 1; VersionNotifyTargets::::insert(old_version, loc, (0, Weight::zero(), old_version)); }: { @@ -270,17 +270,17 @@ benchmarks! { } new_query { - let responder = MultiLocation::from(Parent); + let responder = Location::from(Parent); let timeout = 1u32.into(); - let match_querier = MultiLocation::from(Here); + let match_querier = Location::from(Here); }: { crate::Pallet::::new_query(responder, timeout, match_querier); } take_response { - let responder = MultiLocation::from(Parent); + let responder = Location::from(Parent); let timeout = 1u32.into(); - let match_querier = MultiLocation::from(Here); + let match_querier = Location::from(Here); let query_id = crate::Pallet::::new_query(responder, timeout, match_querier); let infos = (0 .. xcm::v3::MaxPalletsInfo::get()).map(|_| PalletInfo::new( u32::MAX, diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 8157620465f1..69d476bef607 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -59,7 +59,7 @@ use xcm_executor::{ DropAssets, MatchesFungible, OnResponse, Properties, QueryHandler, QueryResponseStatus, TransactAsset, TransferType, VersionChangeNotifier, WeightBounds, XcmAssetTransfers, }, - Assets, + AssetsInHolding, }; pub trait WeightInfo { @@ -197,45 +197,39 @@ pub mod pallet { // TODO: We should really use a trait which can handle multiple currencies. type Currency: LockableCurrency>; - /// The `MultiAsset` matcher for `Currency`. + /// The `Asset` matcher for `Currency`. type CurrencyMatcher: MatchesFungible>; - /// Required origin for sending XCM messages. If successful, it resolves to `MultiLocation` + /// Required origin for sending XCM messages. If successful, it resolves to `Location` /// which exists as an interior location within this chain's XCM context. - type SendXcmOrigin: EnsureOrigin< - ::RuntimeOrigin, - Success = MultiLocation, - >; + type SendXcmOrigin: EnsureOrigin<::RuntimeOrigin, Success = Location>; /// The type used to actually dispatch an XCM to its destination. type XcmRouter: SendXcm; /// Required origin for executing XCM messages, including the teleport functionality. If - /// successful, then it resolves to `MultiLocation` which exists as an interior location + /// successful, then it resolves to `Location` which exists as an interior location /// within this chain's XCM context. - type ExecuteXcmOrigin: EnsureOrigin< - ::RuntimeOrigin, - Success = MultiLocation, - >; + type ExecuteXcmOrigin: EnsureOrigin<::RuntimeOrigin, Success = Location>; /// Our XCM filter which messages to be executed using `XcmExecutor` must pass. - type XcmExecuteFilter: Contains<(MultiLocation, Xcm<::RuntimeCall>)>; + type XcmExecuteFilter: Contains<(Location, Xcm<::RuntimeCall>)>; /// Something to execute an XCM message. type XcmExecutor: ExecuteXcm<::RuntimeCall> + XcmAssetTransfers; /// Our XCM filter which messages to be teleported using the dedicated extrinsic must pass. - type XcmTeleportFilter: Contains<(MultiLocation, Vec)>; + type XcmTeleportFilter: Contains<(Location, Vec)>; /// Our XCM filter which messages to be reserve-transferred using the dedicated extrinsic /// must pass. - type XcmReserveTransferFilter: Contains<(MultiLocation, Vec)>; + type XcmReserveTransferFilter: Contains<(Location, Vec)>; /// Means of measuring the weight consumed by an XCM message locally. type Weigher: WeightBounds<::RuntimeCall>; /// This chain's Universal Location. - type UniversalLocation: Get; + type UniversalLocation: Get; /// The runtime `Origin` type. type RuntimeOrigin: From + From<::RuntimeOrigin>; @@ -259,9 +253,9 @@ pub mod pallet { /// The assets which we consider a given origin is trusted if they claim to have placed a /// lock. - type TrustedLockers: ContainsPair; + type TrustedLockers: ContainsPair; - /// How to get an `AccountId` value from a `MultiLocation`, useful for handling asset locks. + /// How to get an `AccountId` value from a `Location`, useful for handling asset locks. type SovereignAccountOf: ConvertLocation; /// The maximum number of local XCM locks that a single account may have. @@ -291,15 +285,15 @@ pub mod pallet { max_weight: Weight, ) -> Result { let origin_location = T::ExecuteXcmOrigin::ensure_origin(origin)?; - let hash = message.using_encoded(sp_io::hashing::blake2_256); + let mut hash = message.using_encoded(sp_io::hashing::blake2_256); let message = (*message).try_into().map_err(|()| Error::::BadVersion)?; let value = (origin_location, message); ensure!(T::XcmExecuteFilter::contains(&value), Error::::Filtered); let (origin_location, message) = value; - let outcome = T::XcmExecutor::execute_xcm_in_credit( + let outcome = T::XcmExecutor::prepare_and_execute( origin_location, message, - hash, + &mut hash, max_weight, max_weight, ); @@ -318,17 +312,17 @@ pub mod pallet { type WeightInfo = Self; fn send( origin: OriginFor, - dest: Box, + dest: Box, message: Box>, ) -> Result { let origin_location = T::SendXcmOrigin::ensure_origin(origin)?; let interior: Junctions = - origin_location.try_into().map_err(|_| Error::::InvalidOrigin)?; - let dest = MultiLocation::try_from(*dest).map_err(|()| Error::::BadVersion)?; + origin_location.clone().try_into().map_err(|_| Error::::InvalidOrigin)?; + let dest = Location::try_from(*dest).map_err(|()| Error::::BadVersion)?; let message: Xcm<()> = (*message).try_into().map_err(|()| Error::::BadVersion)?; let message_id = - Self::send_xcm(interior, dest, message.clone()).map_err(Error::::from)?; + Self::send_xcm(interior, dest.clone(), message.clone()).map_err(Error::::from)?; let e = Event::Sent { origin: origin_location, destination: dest, message, message_id }; Self::deposit_event(e); Ok(message_id) @@ -350,13 +344,13 @@ pub mod pallet { fn query( origin: OriginFor, timeout: BlockNumberFor, - match_querier: VersionedMultiLocation, + match_querier: VersionedLocation, ) -> Result { let responder = ::ExecuteXcmOrigin::ensure_origin(origin)?; let query_id = ::new_query( responder, timeout, - MultiLocation::try_from(match_querier) + Location::try_from(match_querier) .map_err(|_| Into::::into(Error::::BadVersion))?, ); @@ -370,16 +364,11 @@ pub mod pallet { /// Execution of an XCM message was attempted. Attempted { outcome: xcm::latest::Outcome }, /// A XCM message was sent. - Sent { - origin: MultiLocation, - destination: MultiLocation, - message: Xcm<()>, - message_id: XcmHash, - }, + Sent { origin: Location, destination: Location, message: Xcm<()>, message_id: XcmHash }, /// Query response received which does not match a registered query. This may be because a /// matching query was never registered, it may be because it is a duplicate response, or /// because the query timed out. - UnexpectedResponse { origin: MultiLocation, query_id: QueryId }, + UnexpectedResponse { origin: Location, query_id: QueryId }, /// Query response has been received and is ready for taking with `take_response`. There is /// no registered notification call. ResponseReady { query_id: QueryId, response: Response }, @@ -407,9 +396,9 @@ pub mod pallet { /// not match that expected. The query remains registered for a later, valid, response to /// be received and acted upon. InvalidResponder { - origin: MultiLocation, + origin: Location, query_id: QueryId, - expected_location: Option, + expected_location: Option, }, /// Expected query response has been received but the expected origin location placed in /// storage by this runtime previously cannot be decoded. The query remains registered. @@ -418,29 +407,29 @@ pub mod pallet { /// runtime should be readable prior to query timeout) and dangerous since the possibly /// valid response will be dropped. Manual governance intervention is probably going to be /// needed. - InvalidResponderVersion { origin: MultiLocation, query_id: QueryId }, + InvalidResponderVersion { origin: Location, query_id: QueryId }, /// Received query response has been read and removed. ResponseTaken { query_id: QueryId }, /// Some assets have been placed in an asset trap. - AssetsTrapped { hash: H256, origin: MultiLocation, assets: VersionedMultiAssets }, + AssetsTrapped { hash: H256, origin: Location, assets: VersionedAssets }, /// An XCM version change notification message has been attempted to be sent. /// /// The cost of sending it (borne by the chain) is included. VersionChangeNotified { - destination: MultiLocation, + destination: Location, result: XcmVersion, - cost: MultiAssets, + cost: Assets, message_id: XcmHash, }, /// The supported version of a location has been changed. This might be through an /// automatic notification or a manual intervention. - SupportedVersionChanged { location: MultiLocation, version: XcmVersion }, + SupportedVersionChanged { location: Location, version: XcmVersion }, /// A given location which had a version change subscription was dropped owing to an error /// sending the notification to it. - NotifyTargetSendFail { location: MultiLocation, query_id: QueryId, error: XcmError }, + NotifyTargetSendFail { location: Location, query_id: QueryId, error: XcmError }, /// A given location which had a version change subscription was dropped owing to an error /// migrating the location to our new XCM format. - NotifyTargetMigrationFail { location: VersionedMultiLocation, query_id: QueryId }, + NotifyTargetMigrationFail { location: VersionedLocation, query_id: QueryId }, /// Expected query response has been received but the expected querier location placed in /// storage by this runtime previously cannot be decoded. The query remains registered. /// @@ -448,48 +437,40 @@ pub mod pallet { /// runtime should be readable prior to query timeout) and dangerous since the possibly /// valid response will be dropped. Manual governance intervention is probably going to be /// needed. - InvalidQuerierVersion { origin: MultiLocation, query_id: QueryId }, + InvalidQuerierVersion { origin: Location, query_id: QueryId }, /// Expected query response has been received but the querier location of the response does /// not match the expected. The query remains registered for a later, valid, response to /// be received and acted upon. InvalidQuerier { - origin: MultiLocation, + origin: Location, query_id: QueryId, - expected_querier: MultiLocation, - maybe_actual_querier: Option, + expected_querier: Location, + maybe_actual_querier: Option, }, /// A remote has requested XCM version change notification from us and we have honored it. /// A version information message is sent to them and its cost is included. - VersionNotifyStarted { destination: MultiLocation, cost: MultiAssets, message_id: XcmHash }, + VersionNotifyStarted { destination: Location, cost: Assets, message_id: XcmHash }, /// We have requested that a remote chain send us XCM version change notifications. - VersionNotifyRequested { - destination: MultiLocation, - cost: MultiAssets, - message_id: XcmHash, - }, + VersionNotifyRequested { destination: Location, cost: Assets, message_id: XcmHash }, /// We have requested that a remote chain stops sending us XCM version change /// notifications. - VersionNotifyUnrequested { - destination: MultiLocation, - cost: MultiAssets, - message_id: XcmHash, - }, + VersionNotifyUnrequested { destination: Location, cost: Assets, message_id: XcmHash }, /// Fees were paid from a location for an operation (often for using `SendXcm`). - FeesPaid { paying: MultiLocation, fees: MultiAssets }, + FeesPaid { paying: Location, fees: Assets }, /// Some assets have been claimed from an asset trap - AssetsClaimed { hash: H256, origin: MultiLocation, assets: VersionedMultiAssets }, + AssetsClaimed { hash: H256, origin: Location, assets: VersionedAssets }, } #[pallet::origin] #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub enum Origin { /// It comes from somewhere in the XCM space wanting to transact. - Xcm(MultiLocation), + Xcm(Location), /// It comes as an expected response from an XCM location. - Response(MultiLocation), + Response(Location), } - impl From for Origin { - fn from(location: MultiLocation) -> Origin { + impl From for Origin { + fn from(location: Location) -> Origin { Origin::Xcm(location) } } @@ -506,7 +487,7 @@ pub mod pallet { Filtered, /// The message's weight could not be determined. UnweighableMessage, - /// The destination `MultiLocation` provided cannot be inverted. + /// The destination `Location` provided cannot be inverted. DestinationNotInvertible, /// The assets to be sent are empty. Empty, @@ -577,25 +558,25 @@ pub mod pallet { Pending { /// The `QueryResponse` XCM must have this origin to be considered a reply for this /// query. - responder: VersionedMultiLocation, + responder: VersionedLocation, /// The `QueryResponse` XCM must have this value as the `querier` field to be /// considered a reply for this query. If `None` then the querier is ignored. - maybe_match_querier: Option, + maybe_match_querier: Option, maybe_notify: Option<(u8, u8)>, timeout: BlockNumber, }, /// The query is for an ongoing version notification subscription. - VersionNotifier { origin: VersionedMultiLocation, is_active: bool }, + VersionNotifier { origin: VersionedLocation, is_active: bool }, /// A response has been received. Ready { response: VersionedResponse, at: BlockNumber }, } #[derive(Copy, Clone)] - pub(crate) struct LatestVersionedMultiLocation<'a>(pub(crate) &'a MultiLocation); - impl<'a> EncodeLike for LatestVersionedMultiLocation<'a> {} - impl<'a> Encode for LatestVersionedMultiLocation<'a> { + pub(crate) struct LatestVersionedLocation<'a>(pub(crate) &'a Location); + impl<'a> EncodeLike for LatestVersionedLocation<'a> {} + impl<'a> Encode for LatestVersionedLocation<'a> { fn encode(&self) -> Vec { - let mut r = VersionedMultiLocation::from(MultiLocation::default()).encode(); + let mut r = VersionedLocation::from(Location::default()).encode(); r.truncate(1); self.0.using_encoded(|d| r.extend_from_slice(d)); r @@ -628,7 +609,7 @@ pub mod pallet { /// The existing asset traps. /// - /// Key is the blake2 256 hash of (origin, versioned `MultiAssets`) pair. Value is the number of + /// Key is the blake2 256 hash of (origin, versioned `Assets`) pair. Value is the number of /// times this pair has been trapped (usually just 1 if it exists at all). #[pallet::storage] #[pallet::getter(fn asset_trap)] @@ -647,7 +628,7 @@ pub mod pallet { Twox64Concat, XcmVersion, Blake2_128Concat, - VersionedMultiLocation, + VersionedLocation, XcmVersion, OptionQuery, >; @@ -659,7 +640,7 @@ pub mod pallet { Twox64Concat, XcmVersion, Blake2_128Concat, - VersionedMultiLocation, + VersionedLocation, QueryId, OptionQuery, >; @@ -672,7 +653,7 @@ pub mod pallet { Twox64Concat, XcmVersion, Blake2_128Concat, - VersionedMultiLocation, + VersionedLocation, (QueryId, Weight, XcmVersion), OptionQuery, >; @@ -691,7 +672,7 @@ pub mod pallet { #[pallet::whitelist_storage] pub(super) type VersionDiscoveryQueue = StorageValue< _, - BoundedVec<(VersionedMultiLocation, u32), VersionDiscoveryQueueSize>, + BoundedVec<(VersionedLocation, u32), VersionDiscoveryQueueSize>, ValueQuery, >; @@ -706,9 +687,9 @@ pub mod pallet { /// Total amount of the asset held by the remote lock. pub amount: u128, /// The owner of the locked asset. - pub owner: VersionedMultiLocation, + pub owner: VersionedLocation, /// The location which holds the original lock. - pub locker: VersionedMultiLocation, + pub locker: VersionedLocation, /// Local consumers of the remote lock with a consumer identifier and the amount /// of fungible asset every consumer holds. /// Every consumer can hold up to total amount of the remote lock. @@ -742,7 +723,7 @@ pub mod pallet { _, Blake2_128Concat, T::AccountId, - BoundedVec<(BalanceOf, VersionedMultiLocation), T::MaxLockers>, + BoundedVec<(BalanceOf, VersionedLocation), T::MaxLockers>, OptionQuery, >; @@ -790,7 +771,7 @@ pub mod pallet { weight_used.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); q.sort_by_key(|i| i.1); while let Some((versioned_dest, _)) = q.pop() { - if let Ok(dest) = MultiLocation::try_from(versioned_dest) { + if let Ok(dest) = Location::try_from(versioned_dest) { if Self::request_version_notify(dest).is_ok() { // TODO: correct weights. weight_used.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); @@ -814,12 +795,12 @@ pub mod pallet { #[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)] enum QueryStatusV0 { Pending { - responder: VersionedMultiLocation, + responder: VersionedLocation, maybe_notify: Option<(u8, u8)>, timeout: BlockNumber, }, VersionNotifier { - origin: VersionedMultiLocation, + origin: VersionedLocation, is_active: bool, }, Ready { @@ -835,7 +816,7 @@ pub mod pallet { responder, maybe_notify, timeout, - maybe_match_querier: Some(MultiLocation::here().into()), + maybe_match_querier: Some(Location::here().into()), }, VersionNotifier { origin, is_active } => QueryStatus::VersionNotifier { origin, is_active }, @@ -884,7 +865,7 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::send())] pub fn send( origin: OriginFor, - dest: Box, + dest: Box, message: Box>, ) -> DispatchResult { >::send(origin, dest, message)?; @@ -900,9 +881,9 @@ pub mod pallet { /// with all fees taken as needed from the asset. /// /// - `origin`: Must be capable of withdrawing the `assets` and executing XCM. - /// - `dest`: Destination context for the assets. Will typically be `X2(Parent, - /// Parachain(..))` to send from parachain to parachain, or `X1(Parachain(..))` to send - /// from relay to parachain. + /// - `dest`: Destination context for the assets. Will typically be `[Parent, + /// Parachain(..)]` to send from parachain to parachain, or `[Parachain(..)]` to send from + /// relay to parachain. /// - `beneficiary`: A beneficiary location for the assets in the context of `dest`. Will /// generally be an `AccountId32` value. /// - `assets`: The assets to be withdrawn. The first item should be the currency used to to @@ -911,8 +892,8 @@ pub mod pallet { /// fees. #[pallet::call_index(1)] #[pallet::weight({ - let maybe_assets: Result = (*assets.clone()).try_into(); - let maybe_dest: Result = (*dest.clone()).try_into(); + let maybe_assets: Result = (*assets.clone()).try_into(); + let maybe_dest: Result = (*dest.clone()).try_into(); match (maybe_assets, maybe_dest) { (Ok(assets), Ok(dest)) => { use sp_std::vec; @@ -929,9 +910,9 @@ pub mod pallet { })] pub fn teleport_assets( origin: OriginFor, - dest: Box, - beneficiary: Box, - assets: Box, + dest: Box, + beneficiary: Box, + assets: Box, fee_asset_item: u32, ) -> DispatchResult { Self::do_teleport_assets(origin, dest, beneficiary, assets, fee_asset_item, Unlimited) @@ -947,9 +928,9 @@ pub mod pallet { /// with all fees taken as needed from the asset. /// /// - `origin`: Must be capable of withdrawing the `assets` and executing XCM. - /// - `dest`: Destination context for the assets. Will typically be `X2(Parent, - /// Parachain(..))` to send from parachain to parachain, or `X1(Parachain(..))` to send - /// from relay to parachain. + /// - `dest`: Destination context for the assets. Will typically be `[Parent, + /// Parachain(..)]` to send from parachain to parachain, or `[Parachain(..)]` to send from + /// relay to parachain. /// - `beneficiary`: A beneficiary location for the assets in the context of `dest`. Will /// generally be an `AccountId32` value. /// - `assets`: The assets to be withdrawn. This should include the assets used to pay the @@ -958,8 +939,8 @@ pub mod pallet { /// fees. #[pallet::call_index(2)] #[pallet::weight({ - let maybe_assets: Result = (*assets.clone()).try_into(); - let maybe_dest: Result = (*dest.clone()).try_into(); + let maybe_assets: Result = (*assets.clone()).try_into(); + let maybe_dest: Result = (*dest.clone()).try_into(); match (maybe_assets, maybe_dest) { (Ok(assets), Ok(dest)) => { use sp_std::vec; @@ -976,9 +957,9 @@ pub mod pallet { })] pub fn reserve_transfer_assets( origin: OriginFor, - dest: Box, - beneficiary: Box, - assets: Box, + dest: Box, + beneficiary: Box, + assets: Box, fee_asset_item: u32, ) -> DispatchResult { Self::do_reserve_transfer_assets( @@ -1023,16 +1004,12 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::force_xcm_version())] pub fn force_xcm_version( origin: OriginFor, - location: Box, + location: Box, version: XcmVersion, ) -> DispatchResult { T::AdminOrigin::ensure_origin(origin)?; let location = *location; - SupportedVersion::::insert( - XCM_VERSION, - LatestVersionedMultiLocation(&location), - version, - ); + SupportedVersion::::insert(XCM_VERSION, LatestVersionedLocation(&location), version); Self::deposit_event(Event::SupportedVersionChanged { location, version }); Ok(()) } @@ -1061,10 +1038,10 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::force_subscribe_version_notify())] pub fn force_subscribe_version_notify( origin: OriginFor, - location: Box, + location: Box, ) -> DispatchResult { T::AdminOrigin::ensure_origin(origin)?; - let location: MultiLocation = + let location: Location = (*location).try_into().map_err(|()| Error::::BadLocation)?; Self::request_version_notify(location).map_err(|e| { match e { @@ -1085,10 +1062,10 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::force_unsubscribe_version_notify())] pub fn force_unsubscribe_version_notify( origin: OriginFor, - location: Box, + location: Box, ) -> DispatchResult { T::AdminOrigin::ensure_origin(origin)?; - let location: MultiLocation = + let location: Location = (*location).try_into().map_err(|()| Error::::BadLocation)?; Self::unrequest_version_notify(location).map_err(|e| { match e { @@ -1108,9 +1085,9 @@ pub mod pallet { /// at risk. /// /// - `origin`: Must be capable of withdrawing the `assets` and executing XCM. - /// - `dest`: Destination context for the assets. Will typically be `X2(Parent, - /// Parachain(..))` to send from parachain to parachain, or `X1(Parachain(..))` to send - /// from relay to parachain. + /// - `dest`: Destination context for the assets. Will typically be `[Parent, + /// Parachain(..)]` to send from parachain to parachain, or `[Parachain(..)]` to send from + /// relay to parachain. /// - `beneficiary`: A beneficiary location for the assets in the context of `dest`. Will /// generally be an `AccountId32` value. /// - `assets`: The assets to be withdrawn. This should include the assets used to pay the @@ -1120,8 +1097,8 @@ pub mod pallet { /// - `weight_limit`: The remote-side weight limit, if any, for the XCM fee purchase. #[pallet::call_index(8)] #[pallet::weight({ - let maybe_assets: Result = (*assets.clone()).try_into(); - let maybe_dest: Result = (*dest.clone()).try_into(); + let maybe_assets: Result = (*assets.clone()).try_into(); + let maybe_dest: Result = (*dest.clone()).try_into(); match (maybe_assets, maybe_dest) { (Ok(assets), Ok(dest)) => { use sp_std::vec; @@ -1138,9 +1115,9 @@ pub mod pallet { })] pub fn limited_reserve_transfer_assets( origin: OriginFor, - dest: Box, - beneficiary: Box, - assets: Box, + dest: Box, + beneficiary: Box, + assets: Box, fee_asset_item: u32, weight_limit: WeightLimit, ) -> DispatchResult { @@ -1162,9 +1139,9 @@ pub mod pallet { /// at risk. /// /// - `origin`: Must be capable of withdrawing the `assets` and executing XCM. - /// - `dest`: Destination context for the assets. Will typically be `X2(Parent, - /// Parachain(..))` to send from parachain to parachain, or `X1(Parachain(..))` to send - /// from relay to parachain. + /// - `dest`: Destination context for the assets. Will typically be `[Parent, + /// Parachain(..)]` to send from parachain to parachain, or `[Parachain(..)]` to send from + /// relay to parachain. /// - `beneficiary`: A beneficiary location for the assets in the context of `dest`. Will /// generally be an `AccountId32` value. /// - `assets`: The assets to be withdrawn. The first item should be the currency used to to @@ -1174,8 +1151,8 @@ pub mod pallet { /// - `weight_limit`: The remote-side weight limit, if any, for the XCM fee purchase. #[pallet::call_index(9)] #[pallet::weight({ - let maybe_assets: Result = (*assets.clone()).try_into(); - let maybe_dest: Result = (*dest.clone()).try_into(); + let maybe_assets: Result = (*assets.clone()).try_into(); + let maybe_dest: Result = (*dest.clone()).try_into(); match (maybe_assets, maybe_dest) { (Ok(assets), Ok(dest)) => { use sp_std::vec; @@ -1192,9 +1169,9 @@ pub mod pallet { })] pub fn limited_teleport_assets( origin: OriginFor, - dest: Box, - beneficiary: Box, - assets: Box, + dest: Box, + beneficiary: Box, + assets: Box, fee_asset_item: u32, weight_limit: WeightLimit, ) -> DispatchResult { @@ -1233,9 +1210,9 @@ impl QueryHandler for Pallet { /// Attempt to create a new query ID and register it as a query that is yet to respond. fn new_query( - responder: impl Into, + responder: impl Into, timeout: BlockNumberFor, - match_querier: impl Into, + match_querier: impl Into, ) -> Self::QueryId { Self::do_new_query(responder, None, timeout, match_querier) } @@ -1244,7 +1221,7 @@ impl QueryHandler for Pallet { /// value. fn report_outcome( message: &mut Xcm<()>, - responder: impl Into, + responder: impl Into, timeout: Self::BlockNumber, ) -> Result { let responder = responder.into(); @@ -1288,8 +1265,8 @@ impl QueryHandler for Pallet { impl Pallet { /// Validate `assets` to be reserve-transferred and return their reserve location. fn validate_assets_and_find_reserve( - assets: &[MultiAsset], - dest: &MultiLocation, + assets: &[Asset], + dest: &Location, ) -> Result> { let mut reserve = None; for asset in assets.iter() { @@ -1315,17 +1292,17 @@ impl Pallet { fn do_reserve_transfer_assets( origin: OriginFor, - dest: Box, - beneficiary: Box, - assets: Box, + dest: Box, + beneficiary: Box, + assets: Box, fee_asset_item: u32, weight_limit: WeightLimit, ) -> DispatchResult { let origin_location = T::ExecuteXcmOrigin::ensure_origin(origin)?; let dest = (*dest).try_into().map_err(|()| Error::::BadVersion)?; - let beneficiary: MultiLocation = + let beneficiary: Location = (*beneficiary).try_into().map_err(|()| Error::::BadVersion)?; - let assets: MultiAssets = (*assets).try_into().map_err(|()| Error::::BadVersion)?; + let assets: Assets = (*assets).try_into().map_err(|()| Error::::BadVersion)?; log::trace!( target: "xcm::pallet_xcm::do_reserve_transfer_assets", "origin {:?}, dest {:?}, beneficiary {:?}, assets {:?}, fee-idx {:?}", @@ -1346,7 +1323,7 @@ impl Pallet { let assets_transfer_type = if assets.is_empty() { // Single asset to transfer (one used for fees where transfer type is determined above). ensure!(fees_transfer_type != TransferType::Teleport, Error::::Filtered); - fees_transfer_type + fees_transfer_type.clone() } else { // Find reserve for non-fee assets. Self::validate_assets_and_find_reserve(&assets, &dest)? @@ -1375,11 +1352,11 @@ impl Pallet { // build fees transfer instructions to be added to assets transfers XCM programs separate_fees_instructions = Some(match fees_transfer_type { TransferType::LocalReserve => - Self::local_reserve_fees_instructions(dest, fees, weight_limit)?, + Self::local_reserve_fees_instructions(dest.clone(), fees, weight_limit)?, TransferType::DestinationReserve => - Self::destination_reserve_fees_instructions(dest, fees, weight_limit)?, + Self::destination_reserve_fees_instructions(dest.clone(), fees, weight_limit)?, TransferType::Teleport => - Self::teleport_fees_instructions(dest, fees, weight_limit)?, + Self::teleport_fees_instructions(dest.clone(), fees, weight_limit)?, TransferType::RemoteReserve(_) => return Err(Error::::InvalidAssetUnsupportedReserve.into()), }); @@ -1399,17 +1376,17 @@ impl Pallet { fn do_teleport_assets( origin: OriginFor, - dest: Box, - beneficiary: Box, - assets: Box, + dest: Box, + beneficiary: Box, + assets: Box, fee_asset_item: u32, weight_limit: WeightLimit, ) -> DispatchResult { let origin_location = T::ExecuteXcmOrigin::ensure_origin(origin)?; let dest = (*dest).try_into().map_err(|()| Error::::BadVersion)?; - let beneficiary: MultiLocation = + let beneficiary: Location = (*beneficiary).try_into().map_err(|()| Error::::BadVersion)?; - let assets: MultiAssets = (*assets).try_into().map_err(|()| Error::::BadVersion)?; + let assets: Assets = (*assets).try_into().map_err(|()| Error::::BadVersion)?; ensure!(assets.len() <= MAX_ASSETS_FOR_TRANSFER, Error::::TooManyAssets); let value = (origin_location, assets.into_inner()); @@ -1435,12 +1412,12 @@ impl Pallet { } fn build_and_execute_xcm_transfer_type( - origin: MultiLocation, - dest: MultiLocation, - beneficiary: MultiLocation, - assets: Vec, + origin: Location, + dest: Location, + beneficiary: Location, + assets: Vec, transfer_type: TransferType, - fees: MultiAsset, + fees: Asset, separate_fees_instructions: Option<(Xcm<::RuntimeCall>, Xcm<()>)>, weight_limit: WeightLimit, ) -> DispatchResult { @@ -1453,7 +1430,7 @@ impl Pallet { let (mut local_xcm, remote_xcm) = match transfer_type { TransferType::LocalReserve => { let (local, remote) = Self::local_reserve_transfer_programs( - dest, + dest.clone(), beneficiary, assets, fees, @@ -1464,7 +1441,7 @@ impl Pallet { }, TransferType::DestinationReserve => { let (local, remote) = Self::destination_reserve_transfer_programs( - dest, + dest.clone(), beneficiary, assets, fees, @@ -1476,7 +1453,7 @@ impl Pallet { TransferType::RemoteReserve(reserve) => ( Self::remote_reserve_transfer_program( reserve, - dest, + dest.clone(), beneficiary, assets, fees, @@ -1485,23 +1462,22 @@ impl Pallet { None, ), TransferType::Teleport => ( - Self::teleport_assets_program(dest, beneficiary, assets, fees, weight_limit)?, + Self::teleport_assets_program(dest.clone(), beneficiary, assets, fees, weight_limit)?, None, ), }; let weight = T::Weigher::weight(&mut local_xcm).map_err(|()| Error::::UnweighableMessage)?; - let hash = local_xcm.using_encoded(sp_io::hashing::blake2_256); + let mut hash = local_xcm.using_encoded(sp_io::hashing::blake2_256); let outcome = - T::XcmExecutor::execute_xcm_in_credit(origin, local_xcm, hash, weight, weight); + T::XcmExecutor::prepare_and_execute(origin.clone(), local_xcm, &mut hash, weight, weight); Self::deposit_event(Event::Attempted { outcome: outcome.clone() }); if let Some(remote_xcm) = remote_xcm { outcome.ensure_complete().map_err(|_| Error::::LocalExecutionIncomplete)?; - - let (ticket, price) = validate_send::(dest, remote_xcm.clone()) + let (ticket, price) = validate_send::(dest.clone(), remote_xcm.clone()) .map_err(Error::::from)?; if origin != Here.into_location() { - Self::charge_fees(origin, price).map_err(|_| Error::::FeesNotMet)?; + Self::charge_fees(origin.clone(), price).map_err(|_| Error::::FeesNotMet)?; } let message_id = T::XcmRouter::deliver(ticket).map_err(Error::::from)?; @@ -1512,14 +1488,14 @@ impl Pallet { } fn local_reserve_fees_instructions( - dest: MultiLocation, - fees: MultiAsset, + dest: Location, + fees: Asset, weight_limit: WeightLimit, ) -> Result<(Xcm<::RuntimeCall>, Xcm<()>), Error> { let context = T::UniversalLocation::get(); let reanchored_fees = fees .clone() - .reanchored(&dest, context) + .reanchored(&dest, &context) .map_err(|_| Error::::CannotReanchor)?; let local_execute_xcm = Xcm(vec![ @@ -1536,21 +1512,21 @@ impl Pallet { } fn local_reserve_transfer_programs( - dest: MultiLocation, - beneficiary: MultiLocation, - assets: Vec, - fees: MultiAsset, + dest: Location, + beneficiary: Location, + assets: Vec, + fees: Asset, separate_fees_instructions: Option<(Xcm<::RuntimeCall>, Xcm<()>)>, weight_limit: WeightLimit, ) -> Result<(Xcm<::RuntimeCall>, Xcm<()>), Error> { // max assets is `assets` (+ potentially separately handled fee) let max_assets = assets.len() as u32 + separate_fees_instructions.as_ref().map(|_| 1).unwrap_or(0); - let assets: MultiAssets = assets.into(); + let assets: Assets = assets.into(); let context = T::UniversalLocation::get(); let mut reanchored_assets = assets.clone(); reanchored_assets - .reanchor(&dest, context) + .reanchor(&dest, &context) .map_err(|_| Error::::CannotReanchor)?; // fees are either handled through dedicated instructions, or batched together with assets @@ -1562,7 +1538,7 @@ impl Pallet { // start off with any necessary local fees specific instructions let mut local_execute_xcm = fees_local_xcm; // move `assets` to `dest`s local sovereign account - local_execute_xcm.push(TransferAsset { assets, beneficiary: dest }); + local_execute_xcm.push(TransferAsset { assets, beneficiary: dest.clone() }); // on destination chain, start off with custom fee instructions let mut xcm_on_dest = fees_remote_xcm; @@ -1577,7 +1553,7 @@ impl Pallet { // no custom fees instructions, they are batched together with `assets` transfer; // BuyExecution happens after receiving all `assets` let reanchored_fees = - fees.reanchored(&dest, context).map_err(|_| Error::::CannotReanchor)?; + fees.reanchored(&dest, &context).map_err(|_| Error::::CannotReanchor)?; // buy execution using `fees` batched together with above `reanchored_assets` xcm_on_dest.push(BuyExecution { fees: reanchored_fees, weight_limit }); } @@ -1588,16 +1564,16 @@ impl Pallet { } fn destination_reserve_fees_instructions( - dest: MultiLocation, - fees: MultiAsset, + dest: Location, + fees: Asset, weight_limit: WeightLimit, ) -> Result<(Xcm<::RuntimeCall>, Xcm<()>), Error> { let context = T::UniversalLocation::get(); let reanchored_fees = fees .clone() - .reanchored(&dest, context) + .reanchored(&dest, &context) .map_err(|_| Error::::CannotReanchor)?; - let fees: MultiAssets = fees.into(); + let fees: Assets = fees.into(); let local_execute_xcm = Xcm(vec![ // withdraw reserve-based fees (derivatives) @@ -1615,21 +1591,21 @@ impl Pallet { } fn destination_reserve_transfer_programs( - dest: MultiLocation, - beneficiary: MultiLocation, - assets: Vec, - fees: MultiAsset, + dest: Location, + beneficiary: Location, + assets: Vec, + fees: Asset, separate_fees_instructions: Option<(Xcm<::RuntimeCall>, Xcm<()>)>, weight_limit: WeightLimit, ) -> Result<(Xcm<::RuntimeCall>, Xcm<()>), Error> { // max assets is `assets` (+ potentially separately handled fee) let max_assets = assets.len() as u32 + separate_fees_instructions.as_ref().map(|_| 1).unwrap_or(0); - let assets: MultiAssets = assets.into(); + let assets: Assets = assets.into(); let context = T::UniversalLocation::get(); let mut reanchored_assets = assets.clone(); reanchored_assets - .reanchor(&dest, context) + .reanchor(&dest, &context) .map_err(|_| Error::::CannotReanchor)?; // fees are either handled through dedicated instructions, or batched together with assets @@ -1661,7 +1637,7 @@ impl Pallet { // no custom fees instructions, they are batched together with `assets` transfer; // BuyExecution happens after receiving all `assets` let reanchored_fees = - fees.reanchored(&dest, context).map_err(|_| Error::::CannotReanchor)?; + fees.reanchored(&dest, &context).map_err(|_| Error::::CannotReanchor)?; // buy execution using `fees` batched together with above `reanchored_assets` xcm_on_dest.push(BuyExecution { fees: reanchored_fees, weight_limit }); } @@ -1673,11 +1649,11 @@ impl Pallet { // function assumes fees and assets have the same remote reserve fn remote_reserve_transfer_program( - reserve: MultiLocation, - dest: MultiLocation, - beneficiary: MultiLocation, - assets: Vec, - fees: MultiAsset, + reserve: Location, + dest: Location, + beneficiary: Location, + assets: Vec, + fees: Asset, weight_limit: WeightLimit, ) -> Result::RuntimeCall>, Error> { let max_assets = assets.len() as u32; @@ -1687,13 +1663,13 @@ impl Pallet { let (fees_half_1, fees_half_2) = Self::halve_fees(fees)?; // identifies fee item as seen by `reserve` - to be used at reserve chain let reserve_fees = fees_half_1 - .reanchored(&reserve, context) + .reanchored(&reserve, &context) .map_err(|_| Error::::CannotReanchor)?; // identifies fee item as seen by `dest` - to be used at destination chain let dest_fees = - fees_half_2.reanchored(&dest, context).map_err(|_| Error::::CannotReanchor)?; + fees_half_2.reanchored(&dest, &context).map_err(|_| Error::::CannotReanchor)?; // identifies `dest` as seen by `reserve` - let dest = dest.reanchored(&reserve, context).map_err(|_| Error::::CannotReanchor)?; + let dest = dest.reanchored(&reserve, &context).map_err(|_| Error::::CannotReanchor)?; // xcm to be executed at dest let xcm_on_dest = Xcm(vec![ BuyExecution { fees: dest_fees, weight_limit: weight_limit.clone() }, @@ -1715,14 +1691,14 @@ impl Pallet { } fn teleport_fees_instructions( - dest: MultiLocation, - fees: MultiAsset, + dest: Location, + fees: Asset, weight_limit: WeightLimit, ) -> Result<(Xcm<::RuntimeCall>, Xcm<()>), Error> { let context = T::UniversalLocation::get(); let reanchored_fees = fees .clone() - .reanchored(&dest, context) + .reanchored(&dest, &context) .map_err(|_| Error::::CannotReanchor)?; // XcmContext irrelevant in teleports checks @@ -1744,7 +1720,7 @@ impl Pallet { &dummy_context, ); - let fees: MultiAssets = fees.into(); + let fees: Assets = fees.into(); let local_execute_xcm = Xcm(vec![ // withdraw fees WithdrawAsset(fees.clone()), @@ -1761,14 +1737,14 @@ impl Pallet { } fn teleport_assets_program( - dest: MultiLocation, - beneficiary: MultiLocation, - assets: Vec, - mut fees: MultiAsset, + dest: Location, + beneficiary: Location, + assets: Vec, + mut fees: Asset, weight_limit: WeightLimit, ) -> Result::RuntimeCall>, Error> { let context = T::UniversalLocation::get(); - fees.reanchor(&dest, context).map_err(|_| Error::::CannotReanchor)?; + fees.reanchor(&dest, &context).map_err(|_| Error::::CannotReanchor)?; let max_assets = assets.len() as u32; let xcm_on_dest = Xcm(vec![ BuyExecution { fees, weight_limit }, @@ -1782,14 +1758,14 @@ impl Pallet { } /// Halve `fees` fungible amount. - pub(crate) fn halve_fees(fees: MultiAsset) -> Result<(MultiAsset, MultiAsset), Error> { + pub(crate) fn halve_fees(fees: Asset) -> Result<(Asset, Asset), Error> { match fees.fun { Fungible(amount) => { let fee1 = amount.saturating_div(2); let fee2 = amount.saturating_sub(fee1); ensure!(fee1 > 0, Error::::FeesNotMet); ensure!(fee2 > 0, Error::::FeesNotMet); - Ok((MultiAsset::from((fees.id, fee1)), MultiAsset::from((fees.id, fee2)))) + Ok((Asset::from((fees.id.clone(), fee1)), Asset::from((fees.id.clone(), fee2)))) }, NonFungible(_) => Err(Error::::FeesNotMet), } @@ -1853,7 +1829,7 @@ impl Pallet { }; while let Some((key, value)) = iter.next() { let (query_id, max_weight, target_xcm_version) = value; - let new_key: MultiLocation = match key.clone().try_into() { + let new_key: Location = match key.clone().try_into() { Ok(k) if target_xcm_version != xcm_version => k, _ => { // We don't early return here since we need to be certain that we @@ -1865,7 +1841,7 @@ impl Pallet { let response = Response::Version(xcm_version); let message = Xcm(vec![QueryResponse { query_id, response, max_weight, querier: None }]); - let event = match send_xcm::(new_key, message) { + let event = match send_xcm::(new_key.clone(), message) { Ok((message_id, cost)) => { let value = (query_id, max_weight, xcm_version); VersionNotifyTargets::::insert(XCM_VERSION, key, value); @@ -1894,7 +1870,7 @@ impl Pallet { for v in 0..XCM_VERSION { for (old_key, value) in VersionNotifyTargets::::drain_prefix(v) { let (query_id, max_weight, target_xcm_version) = value; - let new_key = match MultiLocation::try_from(old_key.clone()) { + let new_key = match Location::try_from(old_key.clone()) { Ok(k) => k, Err(()) => { Self::deposit_event(Event::NotifyTargetMigrationFail { @@ -1909,7 +1885,7 @@ impl Pallet { }, }; - let versioned_key = LatestVersionedMultiLocation(&new_key); + let versioned_key = LatestVersionedLocation(&new_key); if target_xcm_version == xcm_version { VersionNotifyTargets::::insert(XCM_VERSION, versioned_key, value); weight_used.saturating_accrue(vnt_migrate_weight); @@ -1922,7 +1898,7 @@ impl Pallet { max_weight, querier: None, }]); - let event = match send_xcm::(new_key, message) { + let event = match send_xcm::(new_key.clone(), message) { Ok((message_id, cost)) => { VersionNotifyTargets::::insert( XCM_VERSION, @@ -1955,9 +1931,9 @@ impl Pallet { } /// Request that `dest` informs us of its version. - pub fn request_version_notify(dest: impl Into) -> XcmResult { + pub fn request_version_notify(dest: impl Into) -> XcmResult { let dest = dest.into(); - let versioned_dest = VersionedMultiLocation::from(dest); + let versioned_dest = VersionedLocation::from(dest.clone()); let already = VersionNotifiers::::contains_key(XCM_VERSION, &versioned_dest); ensure!(!already, XcmError::InvalidLocation); let query_id = QueryCounter::::mutate(|q| { @@ -1967,7 +1943,7 @@ impl Pallet { }); // TODO #3735: Correct weight. let instruction = SubscribeVersion { query_id, max_response_weight: Weight::zero() }; - let (message_id, cost) = send_xcm::(dest, Xcm(vec![instruction]))?; + let (message_id, cost) = send_xcm::(dest.clone(), Xcm(vec![instruction]))?; Self::deposit_event(Event::VersionNotifyRequested { destination: dest, cost, message_id }); VersionNotifiers::::insert(XCM_VERSION, &versioned_dest, query_id); let query_status = @@ -1977,12 +1953,13 @@ impl Pallet { } /// Request that `dest` ceases informing us of its version. - pub fn unrequest_version_notify(dest: impl Into) -> XcmResult { + pub fn unrequest_version_notify(dest: impl Into) -> XcmResult { let dest = dest.into(); - let versioned_dest = LatestVersionedMultiLocation(&dest); + let versioned_dest = LatestVersionedLocation(&dest); let query_id = VersionNotifiers::::take(XCM_VERSION, versioned_dest) .ok_or(XcmError::InvalidLocation)?; - let (message_id, cost) = send_xcm::(dest, Xcm(vec![UnsubscribeVersion]))?; + let (message_id, cost) = + send_xcm::(dest.clone(), Xcm(vec![UnsubscribeVersion]))?; Self::deposit_event(Event::VersionNotifyUnrequested { destination: dest, cost, @@ -1997,13 +1974,13 @@ impl Pallet { /// are not charged (and instead borne by the chain). pub fn send_xcm( interior: impl Into, - dest: impl Into, + dest: impl Into, mut message: Xcm<()>, ) -> Result { let interior = interior.into(); let dest = dest.into(); let maybe_fee_payer = if interior != Junctions::Here { - message.0.insert(0, DescendOrigin(interior)); + message.0.insert(0, DescendOrigin(interior.clone())); Some(interior.into()) } else { None @@ -2023,10 +2000,10 @@ impl Pallet { /// Create a new expectation of a query response with the querier being here. fn do_new_query( - responder: impl Into, + responder: impl Into, maybe_notify: Option<(u8, u8)>, timeout: BlockNumberFor, - match_querier: impl Into, + match_querier: impl Into, ) -> u64 { QueryCounter::::mutate(|q| { let r = *q; @@ -2068,7 +2045,7 @@ impl Pallet { /// may be put in the overweight queue and need to be manually executed. pub fn report_outcome_notify( message: &mut Xcm<()>, - responder: impl Into, + responder: impl Into, notify: impl Into<::RuntimeCall>, timeout: BlockNumberFor, ) -> Result<(), XcmError> { @@ -2088,10 +2065,10 @@ impl Pallet { /// Attempt to create a new query ID and register it as a query that is yet to respond, and /// which will call a dispatchable when a response happens. pub fn new_notify_query( - responder: impl Into, + responder: impl Into, notify: impl Into<::RuntimeCall>, timeout: BlockNumberFor, - match_querier: impl Into, + match_querier: impl Into, ) -> u64 { let notify = notify.into().using_encoded(|mut bytes| Decode::decode(&mut bytes)).expect( "decode input is output of Call encode; Call guaranteed to have two enums; qed", @@ -2101,13 +2078,13 @@ impl Pallet { /// Note that a particular destination to whom we would like to send a message is unknown /// and queue it for version discovery. - fn note_unknown_version(dest: &MultiLocation) { + fn note_unknown_version(dest: &Location) { log::trace!( target: "xcm::pallet_xcm::note_unknown_version", "XCM version is unknown for destination: {:?}", dest, ); - let versioned_dest = VersionedMultiLocation::from(*dest); + let versioned_dest = VersionedLocation::from(dest.clone()); VersionDiscoveryQueue::::mutate(|q| { if let Some(index) = q.iter().position(|i| &i.0 == &versioned_dest) { // exists - just bump the count. @@ -2123,8 +2100,8 @@ impl Pallet { /// Fails if: /// - the `assets` are not known on this chain; /// - the `assets` cannot be withdrawn with that location as the Origin. - fn charge_fees(location: MultiLocation, assets: MultiAssets) -> DispatchResult { - T::XcmExecutor::charge_fees(location, assets.clone()) + fn charge_fees(location: Location, assets: Assets) -> DispatchResult { + T::XcmExecutor::charge_fees(location.clone(), assets.clone()) .map_err(|_| Error::::FeesNotMet)?; Self::deposit_event(Event::FeesPaid { paying: location, fees: assets }); Ok(()) @@ -2134,7 +2111,7 @@ impl Pallet { pub struct LockTicket { sovereign_account: T::AccountId, amount: BalanceOf, - unlocker: MultiLocation, + unlocker: Location, item_index: Option, } @@ -2168,7 +2145,7 @@ impl xcm_executor::traits::Enact for LockTicket { pub struct UnlockTicket { sovereign_account: T::AccountId, amount: BalanceOf, - unlocker: MultiLocation, + unlocker: Location, } impl xcm_executor::traits::Enact for UnlockTicket { @@ -2205,8 +2182,8 @@ impl xcm_executor::traits::Enact for UnlockTicket { pub struct ReduceTicket { key: (u32, T::AccountId, VersionedAssetId), amount: u128, - locker: VersionedMultiLocation, - owner: VersionedMultiLocation, + locker: VersionedLocation, + owner: VersionedLocation, } impl xcm_executor::traits::Enact for ReduceTicket { @@ -2232,9 +2209,9 @@ impl xcm_executor::traits::AssetLock for Pallet { type ReduceTicket = ReduceTicket; fn prepare_lock( - unlocker: MultiLocation, - asset: MultiAsset, - owner: MultiLocation, + unlocker: Location, + asset: Asset, + owner: Location, ) -> Result, xcm_executor::traits::LockError> { use xcm_executor::traits::LockError::*; let sovereign_account = T::SovereignAccountOf::convert_location(&owner).ok_or(BadOwner)?; @@ -2247,9 +2224,9 @@ impl xcm_executor::traits::AssetLock for Pallet { } fn prepare_unlock( - unlocker: MultiLocation, - asset: MultiAsset, - owner: MultiLocation, + unlocker: Location, + asset: Asset, + owner: Location, ) -> Result, xcm_executor::traits::LockError> { use xcm_executor::traits::LockError::*; let sovereign_account = T::SovereignAccountOf::convert_location(&owner).ok_or(BadOwner)?; @@ -2263,9 +2240,9 @@ impl xcm_executor::traits::AssetLock for Pallet { } fn note_unlockable( - locker: MultiLocation, - asset: MultiAsset, - mut owner: MultiLocation, + locker: Location, + asset: Asset, + mut owner: Location, ) -> Result<(), xcm_executor::traits::LockError> { use xcm_executor::traits::LockError::*; ensure!(T::TrustedLockers::contains(&locker, &asset), NotTrusted); @@ -2292,9 +2269,9 @@ impl xcm_executor::traits::AssetLock for Pallet { } fn prepare_reduce_unlockable( - locker: MultiLocation, - asset: MultiAsset, - mut owner: MultiLocation, + locker: Location, + asset: Asset, + mut owner: Location, ) -> Result { use xcm_executor::traits::LockError::*; let amount = match asset.fun { @@ -2322,10 +2299,10 @@ impl xcm_executor::traits::AssetLock for Pallet { impl WrapVersion for Pallet { fn wrap_version( - dest: &MultiLocation, + dest: &Location, xcm: impl Into>, ) -> Result, ()> { - SupportedVersion::::get(XCM_VERSION, LatestVersionedMultiLocation(dest)) + SupportedVersion::::get(XCM_VERSION, LatestVersionedLocation(dest)) .or_else(|| { Self::note_unknown_version(dest); SafeXcmVersion::::get() @@ -2352,21 +2329,21 @@ impl VersionChangeNotifier for Pallet { /// If the `location` has an ongoing notification and when this function is called, then an /// error should be returned. fn start( - dest: &MultiLocation, + dest: &Location, query_id: QueryId, max_weight: Weight, _context: &XcmContext, ) -> XcmResult { - let versioned_dest = LatestVersionedMultiLocation(dest); + let versioned_dest = LatestVersionedLocation(dest); let already = VersionNotifyTargets::::contains_key(XCM_VERSION, versioned_dest); ensure!(!already, XcmError::InvalidLocation); let xcm_version = T::AdvertisedXcmVersion::get(); let response = Response::Version(xcm_version); let instruction = QueryResponse { query_id, response, max_weight, querier: None }; - let (message_id, cost) = send_xcm::(*dest, Xcm(vec![instruction]))?; + let (message_id, cost) = send_xcm::(dest.clone(), Xcm(vec![instruction]))?; Self::deposit_event(Event::::VersionNotifyStarted { - destination: *dest, + destination: dest.clone(), cost, message_id, }); @@ -2378,27 +2355,31 @@ impl VersionChangeNotifier for Pallet { /// Stop notifying `location` should the XCM change. This is a no-op if there was never a /// subscription. - fn stop(dest: &MultiLocation, _context: &XcmContext) -> XcmResult { - VersionNotifyTargets::::remove(XCM_VERSION, LatestVersionedMultiLocation(dest)); + fn stop(dest: &Location, _context: &XcmContext) -> XcmResult { + VersionNotifyTargets::::remove(XCM_VERSION, LatestVersionedLocation(dest)); Ok(()) } /// Return true if a location is subscribed to XCM version changes. - fn is_subscribed(dest: &MultiLocation) -> bool { - let versioned_dest = LatestVersionedMultiLocation(dest); + fn is_subscribed(dest: &Location) -> bool { + let versioned_dest = LatestVersionedLocation(dest); VersionNotifyTargets::::contains_key(XCM_VERSION, versioned_dest) } } impl DropAssets for Pallet { - fn drop_assets(origin: &MultiLocation, assets: Assets, _context: &XcmContext) -> Weight { + fn drop_assets(origin: &Location, assets: AssetsInHolding, _context: &XcmContext) -> Weight { if assets.is_empty() { return Weight::zero() } - let versioned = VersionedMultiAssets::from(MultiAssets::from(assets)); + let versioned = VersionedAssets::from(Assets::from(assets)); let hash = BlakeTwo256::hash_of(&(&origin, &versioned)); AssetTraps::::mutate(hash, |n| *n += 1); - Self::deposit_event(Event::AssetsTrapped { hash, origin: *origin, assets: versioned }); + Self::deposit_event(Event::AssetsTrapped { + hash, + origin: origin.clone(), + assets: versioned, + }); // TODO #3735: Put the real weight in there. Weight::zero() } @@ -2406,71 +2387,75 @@ impl DropAssets for Pallet { impl ClaimAssets for Pallet { fn claim_assets( - origin: &MultiLocation, - ticket: &MultiLocation, - assets: &MultiAssets, + origin: &Location, + ticket: &Location, + assets: &Assets, _context: &XcmContext, ) -> bool { - let mut versioned = VersionedMultiAssets::from(assets.clone()); - match (ticket.parents, &ticket.interior) { - (0, X1(GeneralIndex(i))) => + let mut versioned = VersionedAssets::from(assets.clone()); + match ticket.unpack() { + (0, [GeneralIndex(i)]) => versioned = match versioned.into_version(*i as u32) { Ok(v) => v, Err(()) => return false, }, - (0, Here) => (), + (0, []) => (), _ => return false, }; - let hash = BlakeTwo256::hash_of(&(origin, versioned.clone())); + let hash = BlakeTwo256::hash_of(&(origin.clone(), versioned.clone())); match AssetTraps::::get(hash) { 0 => return false, 1 => AssetTraps::::remove(hash), n => AssetTraps::::insert(hash, n - 1), } - Self::deposit_event(Event::AssetsClaimed { hash, origin: *origin, assets: versioned }); + Self::deposit_event(Event::AssetsClaimed { + hash, + origin: origin.clone(), + assets: versioned, + }); return true } } impl OnResponse for Pallet { fn expecting_response( - origin: &MultiLocation, + origin: &Location, query_id: QueryId, - querier: Option<&MultiLocation>, + querier: Option<&Location>, ) -> bool { match Queries::::get(query_id) { Some(QueryStatus::Pending { responder, maybe_match_querier, .. }) => - MultiLocation::try_from(responder).map_or(false, |r| origin == &r) && + Location::try_from(responder).map_or(false, |r| origin == &r) && maybe_match_querier.map_or(true, |match_querier| { - MultiLocation::try_from(match_querier).map_or(false, |match_querier| { + Location::try_from(match_querier).map_or(false, |match_querier| { querier.map_or(false, |q| q == &match_querier) }) }), Some(QueryStatus::VersionNotifier { origin: r, .. }) => - MultiLocation::try_from(r).map_or(false, |r| origin == &r), + Location::try_from(r).map_or(false, |r| origin == &r), _ => false, } } fn on_response( - origin: &MultiLocation, + origin: &Location, query_id: QueryId, - querier: Option<&MultiLocation>, + querier: Option<&Location>, response: Response, max_weight: Weight, _context: &XcmContext, ) -> Weight { - let origin = *origin; + let origin = origin.clone(); match (response, Queries::::get(query_id)) { ( Response::Version(v), Some(QueryStatus::VersionNotifier { origin: expected_origin, is_active }), ) => { - let origin: MultiLocation = match expected_origin.try_into() { + let origin: Location = match expected_origin.try_into() { Ok(o) if o == origin => o, Ok(o) => { Self::deposit_event(Event::InvalidResponder { - origin, + origin: origin.clone(), query_id, expected_location: Some(o), }); @@ -2478,7 +2463,7 @@ impl OnResponse for Pallet { }, _ => { Self::deposit_event(Event::InvalidResponder { - origin, + origin: origin.clone(), query_id, expected_location: None, }); @@ -2490,15 +2475,14 @@ impl OnResponse for Pallet { if !is_active { Queries::::insert( query_id, - QueryStatus::VersionNotifier { origin: origin.into(), is_active: true }, + QueryStatus::VersionNotifier { + origin: origin.clone().into(), + is_active: true, + }, ); } // We're being notified of a version change. - SupportedVersion::::insert( - XCM_VERSION, - LatestVersionedMultiLocation(&origin), - v, - ); + SupportedVersion::::insert(XCM_VERSION, LatestVersionedLocation(&origin), v); Self::deposit_event(Event::SupportedVersionChanged { location: origin, version: v, @@ -2510,16 +2494,19 @@ impl OnResponse for Pallet { Some(QueryStatus::Pending { responder, maybe_notify, maybe_match_querier, .. }), ) => { if let Some(match_querier) = maybe_match_querier { - let match_querier = match MultiLocation::try_from(match_querier) { + let match_querier = match Location::try_from(match_querier) { Ok(mq) => mq, Err(_) => { - Self::deposit_event(Event::InvalidQuerierVersion { origin, query_id }); + Self::deposit_event(Event::InvalidQuerierVersion { + origin: origin.clone(), + query_id, + }); return Weight::zero() }, }; if querier.map_or(true, |q| q != &match_querier) { Self::deposit_event(Event::InvalidQuerier { - origin, + origin: origin.clone(), query_id, expected_querier: match_querier, maybe_actual_querier: querier.cloned(), @@ -2527,16 +2514,19 @@ impl OnResponse for Pallet { return Weight::zero() } } - let responder = match MultiLocation::try_from(responder) { + let responder = match Location::try_from(responder) { Ok(r) => r, Err(_) => { - Self::deposit_event(Event::InvalidResponderVersion { origin, query_id }); + Self::deposit_event(Event::InvalidResponderVersion { + origin: origin.clone(), + query_id, + }); return Weight::zero() }, }; if origin != responder { Self::deposit_event(Event::InvalidResponder { - origin, + origin: origin.clone(), query_id, expected_location: Some(responder), }); @@ -2564,7 +2554,7 @@ impl OnResponse for Pallet { Self::deposit_event(e); return Weight::zero() } - let dispatch_origin = Origin::Response(origin).into(); + let dispatch_origin = Origin::Response(origin.clone()).into(); match call.dispatch(dispatch_origin) { Ok(post_info) => { let e = Event::Notified { query_id, pallet_index, call_index }; @@ -2602,7 +2592,7 @@ impl OnResponse for Pallet { } }, _ => { - let e = Event::UnexpectedResponse { origin, query_id }; + let e = Event::UnexpectedResponse { origin: origin.clone(), query_id }; Self::deposit_event(e); Weight::zero() }, @@ -2612,7 +2602,7 @@ impl OnResponse for Pallet { impl CheckSuspension for Pallet { fn is_suspended( - _origin: &MultiLocation, + _origin: &Location, _instructions: &mut [Instruction], _max_weight: Weight, _properties: &mut Properties, @@ -2624,7 +2614,7 @@ impl CheckSuspension for Pallet { /// Ensure that the origin `o` represents an XCM (`Transact`) origin. /// /// Returns `Ok` with the location of the XCM sender or an `Err` otherwise. -pub fn ensure_xcm(o: OuterOrigin) -> Result +pub fn ensure_xcm(o: OuterOrigin) -> Result where OuterOrigin: Into>, { @@ -2637,7 +2627,7 @@ where /// Ensure that the origin `o` represents an XCM response origin. /// /// Returns `Ok` with the location of the responder or an `Err` otherwise. -pub fn ensure_response(o: OuterOrigin) -> Result +pub fn ensure_response(o: OuterOrigin) -> Result where OuterOrigin: Into>, { @@ -2647,41 +2637,39 @@ where } } -/// Filter for `MultiLocation` to find those which represent a strict majority approval of an +/// Filter for `Location` to find those which represent a strict majority approval of an /// identified plurality. /// /// May reasonably be used with `EnsureXcm`. pub struct IsMajorityOfBody(PhantomData<(Prefix, Body)>); -impl, Body: Get> Contains +impl, Body: Get> Contains for IsMajorityOfBody { - fn contains(l: &MultiLocation) -> bool { + fn contains(l: &Location) -> bool { let maybe_suffix = l.match_and_split(&Prefix::get()); matches!(maybe_suffix, Some(Plurality { id, part }) if id == &Body::get() && part.is_majority()) } } -/// Filter for `MultiLocation` to find those which represent a voice of an identified plurality. +/// Filter for `Location` to find those which represent a voice of an identified plurality. /// /// May reasonably be used with `EnsureXcm`. pub struct IsVoiceOfBody(PhantomData<(Prefix, Body)>); -impl, Body: Get> Contains - for IsVoiceOfBody -{ - fn contains(l: &MultiLocation) -> bool { +impl, Body: Get> Contains for IsVoiceOfBody { + fn contains(l: &Location) -> bool { let maybe_suffix = l.match_and_split(&Prefix::get()); matches!(maybe_suffix, Some(Plurality { id, part }) if id == &Body::get() && part == &BodyPart::Voice) } } -/// `EnsureOrigin` implementation succeeding with a `MultiLocation` value to recognize and filter +/// `EnsureOrigin` implementation succeeding with a `Location` value to recognize and filter /// the `Origin::Xcm` item. pub struct EnsureXcm(PhantomData); -impl, F: Contains> EnsureOrigin for EnsureXcm +impl, F: Contains> EnsureOrigin for EnsureXcm where O::PalletsOrigin: From + TryInto, { - type Success = MultiLocation; + type Success = Location; fn try_origin(outer: O) -> Result { outer.try_with_caller(|caller| { @@ -2699,15 +2687,14 @@ where } } -/// `EnsureOrigin` implementation succeeding with a `MultiLocation` value to recognize and filter +/// `EnsureOrigin` implementation succeeding with a `Location` value to recognize and filter /// the `Origin::Response` item. pub struct EnsureResponse(PhantomData); -impl, F: Contains> EnsureOrigin - for EnsureResponse +impl, F: Contains> EnsureOrigin for EnsureResponse where O::PalletsOrigin: From + TryInto, { - type Success = MultiLocation; + type Success = Location; fn try_origin(outer: O) -> Result { outer.try_with_caller(|caller| { @@ -2724,16 +2711,16 @@ where } } -/// A simple passthrough where we reuse the `MultiLocation`-typed XCM origin as the inner value of +/// A simple passthrough where we reuse the `Location`-typed XCM origin as the inner value of /// this crate's `Origin::Xcm` value. pub struct XcmPassthrough(PhantomData); impl> ConvertOrigin for XcmPassthrough { fn convert_origin( - origin: impl Into, + origin: impl Into, kind: OriginKind, - ) -> Result { + ) -> Result { let origin = origin.into(); match kind { OriginKind::Xcm => Ok(crate::Origin::Xcm(origin).into()), diff --git a/polkadot/xcm/pallet-xcm/src/mock.rs b/polkadot/xcm/pallet-xcm/src/mock.rs index 026838993f1d..7e8f28b65772 100644 --- a/polkadot/xcm/pallet-xcm/src/mock.rs +++ b/polkadot/xcm/pallet-xcm/src/mock.rs @@ -16,9 +16,9 @@ use codec::Encode; use frame_support::{ - construct_runtime, match_types, parameter_types, + construct_runtime, parameter_types, traits::{ - AsEnsureOriginWithArg, ConstU128, ConstU32, Equals, Everything, EverythingBut, Nothing, + AsEnsureOriginWithArg, ConstU128, ConstU32, Equals, Everything, EverythingBut, Nothing, Contains }, weights::Weight, }; @@ -75,7 +75,7 @@ pub mod pallet_test_notifier { pub enum Event { QueryPrepared(QueryId), NotifyQueryPrepared(QueryId), - ResponseReceived(MultiLocation, QueryId, Response), + ResponseReceived(Location, QueryId, Response), } #[pallet::error] @@ -88,7 +88,7 @@ pub mod pallet_test_notifier { impl Pallet { #[pallet::call_index(0)] #[pallet::weight(Weight::from_parts(1_000_000, 1_000_000))] - pub fn prepare_new_query(origin: OriginFor, querier: MultiLocation) -> DispatchResult { + pub fn prepare_new_query(origin: OriginFor, querier: Location) -> DispatchResult { let who = ensure_signed(origin)?; let id = who .using_encoded(|mut d| <[u8; 32]>::decode(&mut d)) @@ -104,10 +104,7 @@ pub mod pallet_test_notifier { #[pallet::call_index(1)] #[pallet::weight(Weight::from_parts(1_000_000, 1_000_000))] - pub fn prepare_new_notify_query( - origin: OriginFor, - querier: MultiLocation, - ) -> DispatchResult { + pub fn prepare_new_notify_query(origin: OriginFor, querier: Location) -> DispatchResult { let who = ensure_signed(origin)?; let id = who .using_encoded(|mut d| <[u8; 32]>::decode(&mut d)) @@ -143,7 +140,7 @@ construct_runtime!( { System: frame_system::{Pallet, Call, Storage, Config, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Assets: pallet_assets::{Pallet, Call, Storage, Config, Event}, + AssetsPallet: pallet_assets::{Pallet, Call, Storage, Config, Event}, ParasOrigin: origin::{Pallet, Origin}, XcmPallet: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config}, TestNotifier: pallet_test_notifier::{Pallet, Call, Event}, @@ -151,12 +148,12 @@ construct_runtime!( ); thread_local! { - pub static SENT_XCM: RefCell)>> = RefCell::new(Vec::new()); + pub static SENT_XCM: RefCell)>> = RefCell::new(Vec::new()); } -pub(crate) fn sent_xcm() -> Vec<(MultiLocation, Xcm<()>)> { +pub(crate) fn sent_xcm() -> Vec<(Location, Xcm<()>)> { SENT_XCM.with(|q| (*q.borrow()).clone()) } -pub(crate) fn take_sent_xcm() -> Vec<(MultiLocation, Xcm<()>)> { +pub(crate) fn take_sent_xcm() -> Vec<(Location, Xcm<()>)> { SENT_XCM.with(|q| { let mut r = Vec::new(); std::mem::swap(&mut r, &mut *q.borrow_mut()); @@ -166,15 +163,15 @@ pub(crate) fn take_sent_xcm() -> Vec<(MultiLocation, Xcm<()>)> { /// Sender that never returns error. pub struct TestSendXcm; impl SendXcm for TestSendXcm { - type Ticket = (MultiLocation, Xcm<()>); + type Ticket = (Location, Xcm<()>); fn validate( - dest: &mut Option, + dest: &mut Option, msg: &mut Option>, - ) -> SendResult<(MultiLocation, Xcm<()>)> { + ) -> SendResult<(Location, Xcm<()>)> { let pair = (dest.take().unwrap(), msg.take().unwrap()); - Ok((pair, MultiAssets::new())) + Ok((pair, Assets::new())) } - fn deliver(pair: (MultiLocation, Xcm<()>)) -> Result { + fn deliver(pair: (Location, Xcm<()>)) -> Result { let hash = fake_message_hash(&pair.1); SENT_XCM.with(|q| q.borrow_mut().push(pair)); Ok(hash) @@ -183,11 +180,11 @@ impl SendXcm for TestSendXcm { /// Sender that returns error if `X8` junction and stops routing pub struct TestSendXcmErrX8; impl SendXcm for TestSendXcmErrX8 { - type Ticket = (MultiLocation, Xcm<()>); + type Ticket = (Location, Xcm<()>); fn validate( - dest: &mut Option, + dest: &mut Option, _: &mut Option>, - ) -> SendResult<(MultiLocation, Xcm<()>)> { + ) -> SendResult<(Location, Xcm<()>)> { if dest.as_ref().unwrap().len() == 8 { dest.take(); Err(SendError::Transport("Destination location full")) @@ -195,7 +192,7 @@ impl SendXcm for TestSendXcmErrX8 { Err(SendError::NotApplicable) } } - fn deliver(pair: (MultiLocation, Xcm<()>)) -> Result { + fn deliver(pair: (Location, Xcm<()>)) -> Result { let hash = fake_message_hash(&pair.1); SENT_XCM.with(|q| q.borrow_mut().push(pair)); Ok(hash) @@ -204,18 +201,18 @@ impl SendXcm for TestSendXcmErrX8 { parameter_types! { pub Para3000: u32 = 3000; - pub Para3000Location: MultiLocation = Parachain(Para3000::get()).into(); + pub Para3000Location: Location = Parachain(Para3000::get()).into(); pub Para3000PaymentAmount: u128 = 1; - pub Para3000PaymentMultiAssets: MultiAssets = MultiAssets::from(MultiAsset::from((Here, Para3000PaymentAmount::get()))); + pub Para3000PaymentAssets: Assets = Assets::from(Asset::from((Here, Para3000PaymentAmount::get()))); } /// Sender only sends to `Parachain(3000)` destination requiring payment. pub struct TestPaidForPara3000SendXcm; impl SendXcm for TestPaidForPara3000SendXcm { - type Ticket = (MultiLocation, Xcm<()>); + type Ticket = (Location, Xcm<()>); fn validate( - dest: &mut Option, + dest: &mut Option, msg: &mut Option>, - ) -> SendResult<(MultiLocation, Xcm<()>)> { + ) -> SendResult<(Location, Xcm<()>)> { if let Some(dest) = dest.as_ref() { if !dest.eq(&Para3000Location::get()) { return Err(SendError::NotApplicable) @@ -225,9 +222,9 @@ impl SendXcm for TestPaidForPara3000SendXcm { } let pair = (dest.take().unwrap(), msg.take().unwrap()); - Ok((pair, Para3000PaymentMultiAssets::get())) + Ok((pair, Para3000PaymentAssets::get())) } - fn deliver(pair: (MultiLocation, Xcm<()>)) -> Result { + fn deliver(pair: (Location, Xcm<()>)) -> Result { let hash = fake_message_hash(&pair.1); SENT_XCM.with(|q| q.borrow_mut().push(pair)); Ok(hash) @@ -291,17 +288,17 @@ impl pallet_balances::Config for Test { /// Simple conversion of `u32` into an `AssetId` for use in benchmarking. pub struct XcmBenchmarkHelper; #[cfg(feature = "runtime-benchmarks")] -impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { - fn create_asset_id_parameter(id: u32) -> MultiLocation { - MultiLocation { parents: 1, interior: X1(Parachain(id)) } +impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { + fn create_asset_id_parameter(id: u32) -> Location { + Location::new(1, [Parachain(id)]) } } impl pallet_assets::Config for Test { type RuntimeEvent = RuntimeEvent; type Balance = Balance; - type AssetId = MultiLocation; - type AssetIdParameter = MultiLocation; + type AssetId = Location; + type AssetIdParameter = Location; type Currency = Balances; type CreateOrigin = AsEnsureOriginWithArg>; type ForceOrigin = EnsureRoot; @@ -342,50 +339,50 @@ pub const USDT_PARA_ID: u32 = 2003; pub const OTHER_PARA_ID: u32 = 2009; parameter_types! { - pub const RelayLocation: MultiLocation = Here.into_location(); - pub const NativeAsset: MultiAsset = MultiAsset { + pub const RelayLocation: Location = Here.into_location(); + pub const NativeAsset: Asset = Asset { fun: Fungible(10), - id: Concrete(Here.into_location()), - }; - pub const SystemParachainLocation: MultiLocation = MultiLocation { - parents: 0, - interior: X1(Parachain(SOME_SYSTEM_PARA)) - }; - pub const ForeignReserveLocation: MultiLocation = MultiLocation { - parents: 0, - interior: X1(Parachain(FOREIGN_ASSET_RESERVE_PARA_ID)) + id: AssetId(Here.into_location()), }; - pub const ForeignAsset: MultiAsset = MultiAsset { + pub SystemParachainLocation: Location = Location::new( + 0, + [Parachain(SOME_SYSTEM_PARA)] + ); + pub ForeignReserveLocation: Location = Location::new( + 0, + [Parachain(FOREIGN_ASSET_RESERVE_PARA_ID)] + ); + pub ForeignAsset: Asset = Asset { fun: Fungible(10), - id: Concrete(MultiLocation { - parents: 0, - interior: X2(Parachain(FOREIGN_ASSET_RESERVE_PARA_ID), FOREIGN_ASSET_INNER_JUNCTION), - }), - }; - pub const UsdcReserveLocation: MultiLocation = MultiLocation { - parents: 0, - interior: X1(Parachain(USDC_RESERVE_PARA_ID)) + id: AssetId(Location::new( + 0, + [Parachain(FOREIGN_ASSET_RESERVE_PARA_ID), FOREIGN_ASSET_INNER_JUNCTION], + )), }; - pub const Usdc: MultiAsset = MultiAsset { + pub UsdcReserveLocation: Location = Location::new( + 0, + [Parachain(USDC_RESERVE_PARA_ID)] + ); + pub Usdc: Asset = Asset { fun: Fungible(10), - id: Concrete(MultiLocation { - parents: 0, - interior: X2(Parachain(USDC_RESERVE_PARA_ID), USDC_INNER_JUNCTION), - }), - }; - pub const UsdtTeleportLocation: MultiLocation = MultiLocation { - parents: 0, - interior: X1(Parachain(USDT_PARA_ID)) + id: AssetId(Location::new( + 0, + [Parachain(USDC_RESERVE_PARA_ID), USDC_INNER_JUNCTION], + )), }; - pub const Usdt: MultiAsset = MultiAsset { + pub UsdtTeleportLocation: Location = Location::new( + 0, + [Parachain(USDT_PARA_ID)] + ); + pub Usdt: Asset = Asset { fun: Fungible(10), - id: Concrete(MultiLocation { - parents: 0, - interior: X1(Parachain(USDT_PARA_ID)), - }), + id: AssetId(Location::new( + 0, + [Parachain(USDT_PARA_ID)], + )), }; - pub const AnyNetwork: Option = None; - pub UniversalLocation: InteriorMultiLocation = Here; + pub AnyNetwork: Option = None; + pub UniversalLocation: InteriorLocation = Here; pub UnitWeightCost: u64 = 1_000; pub CheckingAccount: AccountId = XcmPallet::check_account(); } @@ -397,7 +394,7 @@ pub type SovereignAccountOf = ( ); pub type ForeignAssetsConvertedConcreteId = MatchedConvertedConcreteId< - MultiLocation, + Location, Balance, // Excludes relay/parent chain currency EverythingBut<(Equals,)>, @@ -408,7 +405,7 @@ pub type ForeignAssetsConvertedConcreteId = MatchedConvertedConcreteId< pub type AssetTransactors = ( XcmCurrencyAdapter, SovereignAccountOf, AccountId, ()>, FungiblesAdapter< - Assets, + AssetsPallet, ForeignAssetsConvertedConcreteId, SovereignAccountOf, AccountId, @@ -426,23 +423,25 @@ type LocalOriginConverter = ( parameter_types! { pub const BaseXcmWeight: Weight = Weight::from_parts(1_000, 1_000); - pub CurrencyPerSecondPerByte: (AssetId, u128, u128) = (Concrete(RelayLocation::get()), 1, 1); - pub TrustedLocal: (MultiAssetFilter, MultiLocation) = (All.into(), Here.into()); - pub TrustedSystemPara: (MultiAssetFilter, MultiLocation) = (NativeAsset::get().into(), SystemParachainLocation::get()); - pub TrustedUsdt: (MultiAssetFilter, MultiLocation) = (Usdt::get().into(), UsdtTeleportLocation::get()); - pub TeleportUsdtToForeign: (MultiAssetFilter, MultiLocation) = (Usdt::get().into(), ForeignReserveLocation::get()); - pub TrustedForeign: (MultiAssetFilter, MultiLocation) = (ForeignAsset::get().into(), ForeignReserveLocation::get()); - pub TrustedUsdc: (MultiAssetFilter, MultiLocation) = (Usdc::get().into(), UsdcReserveLocation::get()); + pub CurrencyPerSecondPerByte: (AssetId, u128, u128) = (AssetId(RelayLocation::get()), 1, 1); + pub TrustedLocal: (AssetFilter, Location) = (All.into(), Here.into()); + pub TrustedSystemPara: (AssetFilter, Location) = (NativeAsset::get().into(), SystemParachainLocation::get()); + pub TrustedUsdt: (AssetFilter, Location) = (Usdt::get().into(), UsdtTeleportLocation::get()); + pub TeleportUsdtToForeign: (AssetFilter, Location) = (Usdt::get().into(), ForeignReserveLocation::get()); + pub TrustedForeign: (AssetFilter, Location) = (ForeignAsset::get().into(), ForeignReserveLocation::get()); + pub TrustedUsdc: (AssetFilter, Location) = (Usdc::get().into(), UsdcReserveLocation::get()); pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 64; pub XcmFeesTargetAccount: AccountId = AccountId::new([167u8; 32]); } pub const XCM_FEES_NOT_WAIVED_USER_ACCOUNT: [u8; 32] = [37u8; 32]; -match_types! { - pub type XcmFeesNotWaivedLocations: impl Contains = { - MultiLocation { parents: 0, interior: X1(Junction::AccountId32 {network: None, id: XCM_FEES_NOT_WAIVED_USER_ACCOUNT})} - }; + +pub struct XcmFeesNotWaivedLocations; +impl Contains for XcmFeesNotWaivedLocations { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (0, [Junction::AccountId32 { network: None, id: XCM_FEES_NOT_WAIVED_USER_ACCOUNT }])) + } } pub type Barrier = ( @@ -493,7 +492,7 @@ impl xcm_executor::Config for XcmConfig { pub type LocalOriginToLocation = SignedToAccountId32; parameter_types! { - pub static AdvertisedXcmVersion: pallet_xcm::XcmVersion = 3; + pub static AdvertisedXcmVersion: pallet_xcm::XcmVersion = 4; } impl pallet_xcm::Config for Test { @@ -532,17 +531,17 @@ impl pallet_test_notifier::Config for Test { #[cfg(feature = "runtime-benchmarks")] impl super::benchmarking::Config for Test { - fn reachable_dest() -> Option { + fn reachable_dest() -> Option { Some(Parachain(1000).into()) } - fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { Some((NativeAsset::get(), SystemParachainLocation::get())) } - fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { Some(( - MultiAsset { fun: Fungible(10), id: Concrete(Here.into_location()) }, + Asset { fun: Fungible(10), id: AssetId(Here.into_location()) }, Parachain(OTHER_PARA_ID).into(), )) } @@ -556,13 +555,13 @@ pub(crate) fn last_events(n: usize) -> Vec { System::events().into_iter().map(|e| e.event).rev().take(n).rev().collect() } -pub(crate) fn buy_execution(fees: impl Into) -> Instruction { +pub(crate) fn buy_execution(fees: impl Into) -> Instruction { use xcm::latest::prelude::*; BuyExecution { fees: fees.into(), weight_limit: Unlimited } } pub(crate) fn buy_limited_execution( - fees: impl Into, + fees: impl Into, weight_limit: WeightLimit, ) -> Instruction { use xcm::latest::prelude::*; diff --git a/polkadot/xcm/pallet-xcm/src/tests/assets_transfer.rs b/polkadot/xcm/pallet-xcm/src/tests/assets_transfer.rs index b02b0fd33c32..243d02d46397 100644 --- a/polkadot/xcm/pallet-xcm/src/tests/assets_transfer.rs +++ b/polkadot/xcm/pallet-xcm/src/tests/assets_transfer.rs @@ -32,7 +32,7 @@ use xcm_executor::traits::ConvertLocation; // Helper function to deduplicate testing different teleport types. fn do_test_and_verify_teleport_assets( - expected_beneficiary: MultiLocation, + expected_beneficiary: Location, call: Call, expected_weight_limit: WeightLimit, ) { @@ -65,7 +65,7 @@ fn do_test_and_verify_teleport_assets( let _check_v2_ok: xcm::v2::Xcm<()> = versioned_sent.try_into().unwrap(); assert_eq!( last_event(), - RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete(weight) }) + RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete { used: weight } }) ); }); } @@ -76,9 +76,9 @@ fn do_test_and_verify_teleport_assets( /// local effects. #[test] fn teleport_assets_works() { - let beneficiary: MultiLocation = AccountId32 { network: None, id: BOB.into() }.into(); + let beneficiary: Location = AccountId32 { network: None, id: BOB.into() }.into(); do_test_and_verify_teleport_assets( - beneficiary, + beneficiary.clone(), || { assert_ok!(XcmPallet::teleport_assets( RuntimeOrigin::signed(ALICE), @@ -98,11 +98,11 @@ fn teleport_assets_works() { /// local effects. #[test] fn limited_teleport_assets_works() { - let beneficiary: MultiLocation = AccountId32 { network: None, id: BOB.into() }.into(); + let beneficiary: Location = AccountId32 { network: None, id: BOB.into() }.into(); let weight_limit = WeightLimit::Limited(Weight::from_parts(5000, 5000)); let expected_weight_limit = weight_limit.clone(); do_test_and_verify_teleport_assets( - beneficiary, + beneficiary.clone(), || { assert_ok!(XcmPallet::limited_teleport_assets( RuntimeOrigin::signed(ALICE), @@ -121,7 +121,7 @@ fn limited_teleport_assets_works() { /// /// Asserts that the sender's balance is decreased and the beneficiary's balance /// is increased. Verifies the correct message is sent and event is emitted. -/// Verifies that XCM router fees (`SendXcm::validate` -> `MultiAssets`) are withdrawn from correct +/// Verifies that XCM router fees (`SendXcm::validate` -> `Assets`) are withdrawn from correct /// user account and deposited to a correct target account (`XcmFeesTargetAccount`). #[test] fn reserve_transfer_assets_with_paid_router_works() { @@ -135,13 +135,13 @@ fn reserve_transfer_assets_with_paid_router_works() { new_test_ext_with_balances(balances).execute_with(|| { let xcm_router_fee_amount = Para3000PaymentAmount::get(); let weight = BaseXcmWeight::get(); - let dest: MultiLocation = + let dest: Location = Junction::AccountId32 { network: None, id: user_account.clone().into() }.into(); assert_eq!(Balances::total_balance(&user_account), INITIAL_BALANCE); assert_ok!(XcmPallet::reserve_transfer_assets( RuntimeOrigin::signed(user_account.clone()), Box::new(Parachain(paid_para_id).into()), - Box::new(dest.into()), + Box::new(dest.clone().into()), Box::new((Here, SEND_AMOUNT).into()), 0, )); @@ -162,7 +162,7 @@ fn reserve_transfer_assets_with_paid_router_works() { INITIAL_BALANCE + xcm_router_fee_amount ); - let dest_para: MultiLocation = Parachain(paid_para_id).into(); + let dest_para: Location = Parachain(paid_para_id).into(); assert_eq!( sent_xcm(), vec![( @@ -171,14 +171,14 @@ fn reserve_transfer_assets_with_paid_router_works() { ReserveAssetDeposited((Parent, SEND_AMOUNT).into()), ClearOrigin, buy_execution((Parent, SEND_AMOUNT)), - DepositAsset { assets: AllCounted(1).into(), beneficiary: dest }, + DepositAsset { assets: AllCounted(1).into(), beneficiary: dest.clone() }, ]), )] ); let mut last_events = last_events(5).into_iter(); assert_eq!( last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete(weight) }) + RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete { used: weight } }) ); // balances events last_events.next().unwrap(); @@ -187,7 +187,7 @@ fn reserve_transfer_assets_with_paid_router_works() { last_events.next().unwrap(), RuntimeEvent::XcmPallet(crate::Event::FeesPaid { paying: dest, - fees: Para3000PaymentMultiAssets::get(), + fees: Para3000PaymentAssets::get(), }) ); assert!(matches!( @@ -202,45 +202,45 @@ fn set_up_foreign_asset( inner_junction: Option, initial_amount: u128, is_sufficient: bool, -) -> (MultiLocation, AccountId, MultiLocation) { +) -> (Location, AccountId, Location) { let reserve_location = RelayLocation::get().pushed_with_interior(Parachain(reserve_para_id)).unwrap(); let reserve_sovereign_account = SovereignAccountOf::convert_location(&reserve_location).unwrap(); - let foreign_asset_id_multilocation = if let Some(junction) = inner_junction { - reserve_location.pushed_with_interior(junction).unwrap() + let foreign_asset_id_location = if let Some(junction) = inner_junction { + reserve_location.clone().pushed_with_interior(junction).unwrap() } else { - reserve_location + reserve_location.clone() }; // create sufficient (to be used as fees as well) foreign asset (0 total issuance) - assert_ok!(Assets::force_create( + assert_ok!(AssetsPallet::force_create( RuntimeOrigin::root(), - foreign_asset_id_multilocation, + foreign_asset_id_location.clone(), BOB, is_sufficient, 1 )); // this asset should have been teleported/reserve-transferred in, but for this test we just // mint it locally. - assert_ok!(Assets::mint( + assert_ok!(AssetsPallet::mint( RuntimeOrigin::signed(BOB), - foreign_asset_id_multilocation, + foreign_asset_id_location.clone(), ALICE, initial_amount )); - (reserve_location, reserve_sovereign_account, foreign_asset_id_multilocation) + (reserve_location, reserve_sovereign_account, foreign_asset_id_location) } // Helper function that provides correct `fee_index` after `sort()` done by -// `vec![MultiAsset, MultiAsset].into()`. -fn into_multiassets_checked( - fee_asset: MultiAsset, - transfer_asset: MultiAsset, -) -> (MultiAssets, usize, MultiAsset, MultiAsset) { - let assets: MultiAssets = vec![fee_asset.clone(), transfer_asset.clone()].into(); +// `vec![Asset, Asset].into()`. +fn into_assets_checked( + fee_asset: Asset, + transfer_asset: Asset, +) -> (Assets, usize, Asset, Asset) { + let assets: Assets = vec![fee_asset.clone(), transfer_asset.clone()].into(); let fee_index = if assets.get(0).unwrap().eq(&fee_asset) { 0 } else { 1 }; (assets, fee_index, fee_asset, transfer_asset) } @@ -266,12 +266,12 @@ fn limited_reserve_transfer_assets_with_local_asset_reserve_and_local_fee_reserv (ParaId::from(OTHER_PARA_ID).into_account_truncating(), INITIAL_BALANCE), ]; - let beneficiary: MultiLocation = + let beneficiary: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); let weight_limit = WeightLimit::Limited(Weight::from_parts(5000, 5000)); let expected_weight_limit = weight_limit.clone(); - let expected_beneficiary = beneficiary; - let dest: MultiLocation = Parachain(OTHER_PARA_ID).into(); + let expected_beneficiary = beneficiary.clone(); + let dest: Location = Parachain(OTHER_PARA_ID).into(); new_test_ext_with_balances(balances).execute_with(|| { let weight = BaseXcmWeight::get(); @@ -279,8 +279,8 @@ fn limited_reserve_transfer_assets_with_local_asset_reserve_and_local_fee_reserv // call extrinsic assert_ok!(XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), - Box::new(dest.into()), - Box::new(beneficiary.into()), + Box::new(dest.clone().into()), + Box::new(beneficiary.clone().into()), Box::new((Here, SEND_AMOUNT).into()), 0, weight_limit, @@ -300,7 +300,7 @@ fn limited_reserve_transfer_assets_with_local_asset_reserve_and_local_fee_reserv buy_limited_execution((Parent, SEND_AMOUNT), expected_weight_limit), DepositAsset { assets: AllCounted(1).into(), - beneficiary: expected_beneficiary + beneficiary: expected_beneficiary.clone() }, ]), )] @@ -308,13 +308,13 @@ fn limited_reserve_transfer_assets_with_local_asset_reserve_and_local_fee_reserv let mut last_events = last_events(3).into_iter(); assert_eq!( last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete(weight) }) + RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete { used: weight } }) ); assert_eq!( last_events.next().unwrap(), RuntimeEvent::XcmPallet(crate::Event::FeesPaid { paying: expected_beneficiary, - fees: MultiAssets::new(), + fees: Assets::new(), }) ); assert!(matches!( @@ -347,12 +347,12 @@ fn limited_reserve_transfer_assets_with_local_asset_reserve_and_local_fee_reserv fn reserve_transfer_assets_with_destination_asset_reserve_and_local_fee_reserve_works() { let weight = BaseXcmWeight::get() * 3; let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = + let beneficiary: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { // create non-sufficient foreign asset BLA (0 total issuance) let foreign_initial_amount = 142; - let (reserve_location, reserve_sovereign_account, foreign_asset_id_multilocation) = + let (reserve_location, reserve_sovereign_account, foreign_asset_id_location) = set_up_foreign_asset( FOREIGN_ASSET_RESERVE_PARA_ID, Some(FOREIGN_ASSET_INNER_JUNCTION), @@ -363,27 +363,27 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_local_fee_reserve_ // transfer destination is reserve location (no teleport trust) let dest = reserve_location; - let (assets, fee_index, fee_asset, xfer_asset) = into_multiassets_checked( + let (assets, fee_index, fee_asset, xfer_asset) = into_assets_checked( // native asset for fee - local reserve - (MultiLocation::here(), FEE_AMOUNT).into(), + (Location::here(), FEE_AMOUNT).into(), // foreign asset to transfer - destination reserve - (foreign_asset_id_multilocation, SEND_AMOUNT).into(), + (foreign_asset_id_location.clone(), SEND_AMOUNT).into(), ); // reanchor according to test-case let context = UniversalLocation::get(); - let expected_fee = fee_asset.reanchored(&dest, context).unwrap(); - let expected_asset = xfer_asset.reanchored(&dest, context).unwrap(); + let expected_fee = fee_asset.reanchored(&dest, &context).unwrap(); + let expected_asset = xfer_asset.reanchored(&dest, &context).unwrap(); // balances checks before - assert_eq!(Assets::balance(foreign_asset_id_multilocation, ALICE), foreign_initial_amount); + assert_eq!(AssetsPallet::balance(foreign_asset_id_location.clone(), ALICE), foreign_initial_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer assert_ok!(XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), - Box::new(dest.into()), - Box::new(beneficiary.into()), + Box::new(dest.clone().into()), + Box::new(beneficiary.clone().into()), Box::new(assets.into()), fee_index as u32, Unlimited, @@ -392,24 +392,24 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_local_fee_reserve_ let mut last_events = last_events(3).into_iter(); assert_eq!( last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete(weight) }) + RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete { used: weight } }) ); // Alice spent (transferred) amount assert_eq!( - Assets::balance(foreign_asset_id_multilocation, ALICE), + AssetsPallet::balance(foreign_asset_id_location.clone(), ALICE), foreign_initial_amount - SEND_AMOUNT ); // Alice used native asset for fees assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE - FEE_AMOUNT); // Destination account (parachain account) added native reserve used as fee to balances assert_eq!(Balances::free_balance(reserve_sovereign_account.clone()), FEE_AMOUNT); - assert_eq!(Assets::balance(foreign_asset_id_multilocation, reserve_sovereign_account), 0); + assert_eq!(AssetsPallet::balance(foreign_asset_id_location.clone(), reserve_sovereign_account), 0); // Verify total and active issuance of foreign BLA have decreased (burned on // reserve-withdraw) let expected_issuance = foreign_initial_amount - SEND_AMOUNT; - assert_eq!(Assets::total_issuance(foreign_asset_id_multilocation), expected_issuance); - assert_eq!(Assets::active_issuance(foreign_asset_id_multilocation), expected_issuance); + assert_eq!(AssetsPallet::total_issuance(foreign_asset_id_location.clone()), expected_issuance); + assert_eq!(AssetsPallet::active_issuance(foreign_asset_id_location), expected_issuance); // Verify sent XCM program assert_eq!( @@ -423,7 +423,7 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_local_fee_reserve_ buy_limited_execution(expected_fee, Unlimited), WithdrawAsset(expected_asset.into()), ClearOrigin, - DepositAsset { assets: AllCounted(2).into(), beneficiary }, + DepositAsset { assets: AllCounted(2).into(), beneficiary: beneficiary.clone() }, ]) )] ); @@ -431,7 +431,7 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_local_fee_reserve_ last_events.next().unwrap(), RuntimeEvent::XcmPallet(crate::Event::FeesPaid { paying: beneficiary, - fees: MultiAssets::new(), + fees: Assets::new(), }) ); assert!(matches!( @@ -448,12 +448,12 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_local_fee_reserve_ #[test] fn reserve_transfer_assets_with_remote_asset_reserve_and_local_fee_reserve_disallowed() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = + let beneficiary: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { // create non-sufficient foreign asset BLA (0 total issuance) let foreign_initial_amount = 142; - let (_, _, foreign_asset_id_multilocation) = set_up_foreign_asset( + let (_, _, foreign_asset_id_location) = set_up_foreign_asset( FOREIGN_ASSET_RESERVE_PARA_ID, Some(FOREIGN_ASSET_INNER_JUNCTION), foreign_initial_amount, @@ -464,15 +464,15 @@ fn reserve_transfer_assets_with_remote_asset_reserve_and_local_fee_reserve_disal // chain) let dest = RelayLocation::get().pushed_with_interior(Parachain(OTHER_PARA_ID)).unwrap(); - let (assets, fee_index, _, _) = into_multiassets_checked( + let (assets, fee_index, _, _) = into_assets_checked( // native asset for fee - local reserve - (MultiLocation::here(), FEE_AMOUNT).into(), + (Location::here(), FEE_AMOUNT).into(), // foreign asset to transfer - remote reserve - (foreign_asset_id_multilocation, SEND_AMOUNT).into(), + (foreign_asset_id_location.clone(), SEND_AMOUNT).into(), ); // balances checks before - assert_eq!(Assets::balance(foreign_asset_id_multilocation, ALICE), foreign_initial_amount); + assert_eq!(AssetsPallet::balance(foreign_asset_id_location.clone(), ALICE), foreign_initial_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // try the transfer @@ -494,14 +494,14 @@ fn reserve_transfer_assets_with_remote_asset_reserve_and_local_fee_reserve_disal ); // Alice transferred nothing - assert_eq!(Assets::balance(foreign_asset_id_multilocation, ALICE), foreign_initial_amount); + assert_eq!(AssetsPallet::balance(foreign_asset_id_location.clone(), ALICE), foreign_initial_amount); // Alice spent native asset for fees assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // Verify total and active issuance of foreign BLA asset have decreased (burned on // reserve-withdraw) let expected_issuance = foreign_initial_amount; - assert_eq!(Assets::total_issuance(foreign_asset_id_multilocation), expected_issuance); - assert_eq!(Assets::active_issuance(foreign_asset_id_multilocation), expected_issuance); + assert_eq!(AssetsPallet::total_issuance(foreign_asset_id_location.clone()), expected_issuance); + assert_eq!(AssetsPallet::active_issuance(foreign_asset_id_location), expected_issuance); }); } @@ -523,12 +523,12 @@ fn reserve_transfer_assets_with_remote_asset_reserve_and_local_fee_reserve_disal #[test] fn reserve_transfer_assets_with_local_asset_reserve_and_destination_fee_reserve_works() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = + let beneficiary: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { // create sufficient foreign asset USDC (0 total issuance) let usdc_initial_local_amount = 142; - let (usdc_reserve_location, usdc_chain_sovereign_account, usdc_id_multilocation) = + let (usdc_reserve_location, usdc_chain_sovereign_account, usdc_id_location) = set_up_foreign_asset( USDC_RESERVE_PARA_ID, Some(USDC_INNER_JUNCTION), @@ -539,27 +539,27 @@ fn reserve_transfer_assets_with_local_asset_reserve_and_destination_fee_reserve_ // native assets transfer to fee reserve location (no teleport trust) let dest = usdc_reserve_location; - let (assets, fee_index, fee_asset, xfer_asset) = into_multiassets_checked( + let (assets, fee_index, fee_asset, xfer_asset) = into_assets_checked( // usdc for fees (is sufficient on local chain too) - destination reserve - (usdc_id_multilocation, FEE_AMOUNT).into(), + (usdc_id_location.clone(), FEE_AMOUNT).into(), // native asset to transfer (not used for fees) - local reserve - (MultiLocation::here(), SEND_AMOUNT).into(), + (Location::here(), SEND_AMOUNT).into(), ); // reanchor according to test-case let context = UniversalLocation::get(); - let expected_fee = fee_asset.reanchored(&dest, context).unwrap(); - let expected_asset = xfer_asset.reanchored(&dest, context).unwrap(); + let expected_fee = fee_asset.reanchored(&dest, &context).unwrap(); + let expected_asset = xfer_asset.reanchored(&dest, &context).unwrap(); // balances checks before - assert_eq!(Assets::balance(usdc_id_multilocation, ALICE), usdc_initial_local_amount); + assert_eq!(AssetsPallet::balance(usdc_id_location.clone(), ALICE), usdc_initial_local_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer assert_ok!(XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), - Box::new(dest.into()), - Box::new(beneficiary.into()), + Box::new(dest.clone().into()), + Box::new(beneficiary.clone().into()), Box::new(assets.into()), fee_index as u32, Unlimited, @@ -568,13 +568,13 @@ fn reserve_transfer_assets_with_local_asset_reserve_and_destination_fee_reserve_ let mut last_events = last_events(3).into_iter(); assert_eq!( last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete(weight) }) + RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete { used: weight } }) ); assert_eq!( last_events.next().unwrap(), RuntimeEvent::XcmPallet(crate::Event::FeesPaid { - paying: beneficiary, - fees: MultiAssets::new(), + paying: beneficiary.clone(), + fees: Assets::new(), }) ); assert!(matches!( @@ -584,18 +584,18 @@ fn reserve_transfer_assets_with_local_asset_reserve_and_destination_fee_reserve_ // Alice spent (fees) amount assert_eq!( - Assets::balance(usdc_id_multilocation, ALICE), + AssetsPallet::balance(usdc_id_location.clone(), ALICE), usdc_initial_local_amount - FEE_AMOUNT ); // Alice used native asset for transfer assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE - SEND_AMOUNT); // Sovereign account of dest parachain holds `SEND_AMOUNT` native asset in local reserve assert_eq!(Balances::free_balance(usdc_chain_sovereign_account.clone()), SEND_AMOUNT); - assert_eq!(Assets::balance(usdc_id_multilocation, usdc_chain_sovereign_account), 0); + assert_eq!(AssetsPallet::balance(usdc_id_location.clone(), usdc_chain_sovereign_account), 0); // Verify total and active issuance of USDC have decreased (burned on reserve-withdraw) let expected_issuance = usdc_initial_local_amount - FEE_AMOUNT; - assert_eq!(Assets::total_issuance(usdc_id_multilocation), expected_issuance); - assert_eq!(Assets::active_issuance(usdc_id_multilocation), expected_issuance); + assert_eq!(AssetsPallet::total_issuance(usdc_id_location.clone()), expected_issuance); + assert_eq!(AssetsPallet::active_issuance(usdc_id_location), expected_issuance); // Verify sent XCM program assert_eq!( @@ -632,13 +632,13 @@ fn reserve_transfer_assets_with_local_asset_reserve_and_destination_fee_reserve_ #[test] fn reserve_transfer_assets_with_destination_asset_reserve_and_destination_fee_reserve_works() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = + let beneficiary: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { // we'll send just this foreign asset back to its reserve location and use it for fees as // well let foreign_initial_amount = 142; - let (reserve_location, reserve_sovereign_account, foreign_asset_id_multilocation) = + let (reserve_location, reserve_sovereign_account, foreign_asset_id_location) = set_up_foreign_asset( FOREIGN_ASSET_RESERVE_PARA_ID, Some(FOREIGN_ASSET_INNER_JUNCTION), @@ -648,22 +648,22 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_destination_fee_re // transfer destination is reserve location let dest = reserve_location; - let assets: MultiAssets = vec![(foreign_asset_id_multilocation, SEND_AMOUNT).into()].into(); + let assets: Assets = vec![(foreign_asset_id_location.clone(), SEND_AMOUNT).into()].into(); let fee_index = 0; // reanchor according to test-case let mut expected_assets = assets.clone(); - expected_assets.reanchor(&dest, UniversalLocation::get()).unwrap(); + expected_assets.reanchor(&dest, &UniversalLocation::get()).unwrap(); // balances checks before - assert_eq!(Assets::balance(foreign_asset_id_multilocation, ALICE), foreign_initial_amount); + assert_eq!(AssetsPallet::balance(foreign_asset_id_location.clone(), ALICE), foreign_initial_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer assert_ok!(XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), - Box::new(dest.into()), - Box::new(beneficiary.into()), + Box::new(dest.clone().into()), + Box::new(beneficiary.clone().into()), Box::new(assets.into()), fee_index, Unlimited, @@ -673,13 +673,13 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_destination_fee_re let mut last_events = last_events(3).into_iter(); assert_eq!( last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete(weight) }) + RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete { used: weight } }) ); assert_eq!( last_events.next().unwrap(), RuntimeEvent::XcmPallet(crate::Event::FeesPaid { - paying: beneficiary, - fees: MultiAssets::new(), + paying: beneficiary.clone(), + fees: Assets::new(), }) ); assert!(matches!( @@ -689,19 +689,19 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_destination_fee_re // Alice spent (transferred) amount assert_eq!( - Assets::balance(foreign_asset_id_multilocation, ALICE), + AssetsPallet::balance(foreign_asset_id_location.clone(), ALICE), foreign_initial_amount - SEND_AMOUNT ); // Alice's native asset balance is untouched assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // Reserve sovereign account has same balances assert_eq!(Balances::free_balance(reserve_sovereign_account.clone()), 0); - assert_eq!(Assets::balance(foreign_asset_id_multilocation, reserve_sovereign_account), 0); + assert_eq!(AssetsPallet::balance(foreign_asset_id_location.clone(), reserve_sovereign_account), 0); // Verify total and active issuance of foreign BLA have decreased (burned on // reserve-withdraw) let expected_issuance = foreign_initial_amount - SEND_AMOUNT; - assert_eq!(Assets::total_issuance(foreign_asset_id_multilocation), expected_issuance); - assert_eq!(Assets::active_issuance(foreign_asset_id_multilocation), expected_issuance); + assert_eq!(AssetsPallet::total_issuance(foreign_asset_id_location.clone()), expected_issuance); + assert_eq!(AssetsPallet::active_issuance(foreign_asset_id_location), expected_issuance); // Verify sent XCM program assert_eq!( @@ -712,7 +712,7 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_destination_fee_re WithdrawAsset(expected_assets.clone()), ClearOrigin, buy_limited_execution(expected_assets.get(0).unwrap().clone(), Unlimited), - DepositAsset { assets: AllCounted(1).into(), beneficiary }, + DepositAsset { assets: AllCounted(1).into(), beneficiary: beneficiary.clone() }, ]), )] ); @@ -727,12 +727,12 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_destination_fee_re #[test] fn reserve_transfer_assets_with_remote_asset_reserve_and_destination_fee_reserve_disallowed() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = + let beneficiary: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { // create sufficient foreign asset USDC (0 total issuance) let usdc_initial_local_amount = 42; - let (usdc_chain, _, usdc_id_multilocation) = set_up_foreign_asset( + let (usdc_chain, _, usdc_id_location) = set_up_foreign_asset( USDC_RESERVE_PARA_ID, Some(USDC_INNER_JUNCTION), usdc_initial_local_amount, @@ -741,7 +741,7 @@ fn reserve_transfer_assets_with_remote_asset_reserve_and_destination_fee_reserve // create non-sufficient foreign asset BLA (0 total issuance) let foreign_initial_amount = 142; - let (_, _, foreign_asset_id_multilocation) = set_up_foreign_asset( + let (_, _, foreign_asset_id_location) = set_up_foreign_asset( FOREIGN_ASSET_RESERVE_PARA_ID, Some(FOREIGN_ASSET_INNER_JUNCTION), foreign_initial_amount, @@ -752,16 +752,16 @@ fn reserve_transfer_assets_with_remote_asset_reserve_and_destination_fee_reserve // reserve chain) let dest = usdc_chain; - let (assets, fee_index, _, _) = into_multiassets_checked( + let (assets, fee_index, _, _) = into_assets_checked( // USDC for fees (is sufficient on local chain too) - destination reserve - (usdc_id_multilocation, FEE_AMOUNT).into(), + (usdc_id_location.clone(), FEE_AMOUNT).into(), // foreign asset to transfer (not used for fees) - remote reserve - (foreign_asset_id_multilocation, SEND_AMOUNT).into(), + (foreign_asset_id_location.clone(), SEND_AMOUNT).into(), ); // balances checks before - assert_eq!(Assets::balance(usdc_id_multilocation, ALICE), usdc_initial_local_amount); - assert_eq!(Assets::balance(foreign_asset_id_multilocation, ALICE), foreign_initial_amount); + assert_eq!(AssetsPallet::balance(usdc_id_location.clone(), ALICE), usdc_initial_local_amount); + assert_eq!(AssetsPallet::balance(foreign_asset_id_location.clone(), ALICE), foreign_initial_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer @@ -784,14 +784,14 @@ fn reserve_transfer_assets_with_remote_asset_reserve_and_destination_fee_reserve // Alice native asset untouched assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); - assert_eq!(Assets::balance(usdc_id_multilocation, ALICE), usdc_initial_local_amount); - assert_eq!(Assets::balance(foreign_asset_id_multilocation, ALICE), foreign_initial_amount); + assert_eq!(AssetsPallet::balance(usdc_id_location.clone(), ALICE), usdc_initial_local_amount); + assert_eq!(AssetsPallet::balance(foreign_asset_id_location.clone(), ALICE), foreign_initial_amount); let expected_usdc_issuance = usdc_initial_local_amount; - assert_eq!(Assets::total_issuance(usdc_id_multilocation), expected_usdc_issuance); - assert_eq!(Assets::active_issuance(usdc_id_multilocation), expected_usdc_issuance); + assert_eq!(AssetsPallet::total_issuance(usdc_id_location.clone()), expected_usdc_issuance); + assert_eq!(AssetsPallet::active_issuance(usdc_id_location.clone()), expected_usdc_issuance); let expected_bla_issuance = foreign_initial_amount; - assert_eq!(Assets::total_issuance(foreign_asset_id_multilocation), expected_bla_issuance); - assert_eq!(Assets::active_issuance(foreign_asset_id_multilocation), expected_bla_issuance); + assert_eq!(AssetsPallet::total_issuance(foreign_asset_id_location.clone()), expected_bla_issuance); + assert_eq!(AssetsPallet::active_issuance(foreign_asset_id_location), expected_bla_issuance); }); } @@ -802,12 +802,12 @@ fn reserve_transfer_assets_with_remote_asset_reserve_and_destination_fee_reserve #[test] fn reserve_transfer_assets_with_local_asset_reserve_and_remote_fee_reserve_disallowed() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = + let beneficiary: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { // create sufficient foreign asset USDC (0 total issuance) let usdc_initial_local_amount = 142; - let (_, usdc_chain_sovereign_account, usdc_id_multilocation) = set_up_foreign_asset( + let (_, usdc_chain_sovereign_account, usdc_id_location) = set_up_foreign_asset( USDC_RESERVE_PARA_ID, Some(USDC_INNER_JUNCTION), usdc_initial_local_amount, @@ -818,15 +818,15 @@ fn reserve_transfer_assets_with_local_asset_reserve_and_remote_fee_reserve_disal let dest = RelayLocation::get().pushed_with_interior(Parachain(OTHER_PARA_ID)).unwrap(); let dest_sovereign_account = SovereignAccountOf::convert_location(&dest).unwrap(); - let (assets, fee_index, _, _) = into_multiassets_checked( + let (assets, fee_index, _, _) = into_assets_checked( // USDC for fees (is sufficient on local chain too) - remote reserve - (usdc_id_multilocation, FEE_AMOUNT).into(), + (usdc_id_location.clone(), FEE_AMOUNT).into(), // native asset to transfer (not used for fees) - local reserve - (MultiLocation::here(), SEND_AMOUNT).into(), + (Location::here(), SEND_AMOUNT).into(), ); // balances checks before - assert_eq!(Assets::balance(usdc_id_multilocation, ALICE), usdc_initial_local_amount); + assert_eq!(AssetsPallet::balance(usdc_id_location.clone(), ALICE), usdc_initial_local_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer @@ -846,15 +846,15 @@ fn reserve_transfer_assets_with_local_asset_reserve_and_remote_fee_reserve_disal message: Some("InvalidAssetUnsupportedReserve") })) ); - assert_eq!(Assets::balance(usdc_id_multilocation, ALICE), usdc_initial_local_amount); + assert_eq!(AssetsPallet::balance(usdc_id_location.clone(), ALICE), usdc_initial_local_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // Sovereign account of reserve parachain is unchanged assert_eq!(Balances::free_balance(usdc_chain_sovereign_account.clone()), 0); - assert_eq!(Assets::balance(usdc_id_multilocation, usdc_chain_sovereign_account), 0); + assert_eq!(AssetsPallet::balance(usdc_id_location.clone(), usdc_chain_sovereign_account), 0); assert_eq!(Balances::free_balance(dest_sovereign_account), 0); let expected_usdc_issuance = usdc_initial_local_amount; - assert_eq!(Assets::total_issuance(usdc_id_multilocation), expected_usdc_issuance); - assert_eq!(Assets::active_issuance(usdc_id_multilocation), expected_usdc_issuance); + assert_eq!(AssetsPallet::total_issuance(usdc_id_location.clone()), expected_usdc_issuance); + assert_eq!(AssetsPallet::active_issuance(usdc_id_location), expected_usdc_issuance); }); } @@ -866,12 +866,12 @@ fn reserve_transfer_assets_with_local_asset_reserve_and_remote_fee_reserve_disal #[test] fn reserve_transfer_assets_with_destination_asset_reserve_and_remote_fee_reserve_disallowed() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = + let beneficiary: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { // create sufficient foreign asset USDC (0 total issuance) let usdc_initial_local_amount = 42; - let (_, usdc_chain_sovereign_account, usdc_id_multilocation) = set_up_foreign_asset( + let (_, usdc_chain_sovereign_account, usdc_id_location) = set_up_foreign_asset( USDC_RESERVE_PARA_ID, Some(USDC_INNER_JUNCTION), usdc_initial_local_amount, @@ -880,7 +880,7 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_remote_fee_reserve // create non-sufficient foreign asset BLA (0 total issuance) let foreign_initial_amount = 142; - let (reserve_location, foreign_sovereign_account, foreign_asset_id_multilocation) = + let (reserve_location, foreign_sovereign_account, foreign_asset_id_location) = set_up_foreign_asset( FOREIGN_ASSET_RESERVE_PARA_ID, Some(FOREIGN_ASSET_INNER_JUNCTION), @@ -892,15 +892,15 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_remote_fee_reserve let dest = reserve_location; let dest_sovereign_account = foreign_sovereign_account; - let (assets, fee_index, _, _) = into_multiassets_checked( + let (assets, fee_index, _, _) = into_assets_checked( // USDC for fees (is sufficient on local chain too) - remote reserve - (usdc_id_multilocation, FEE_AMOUNT).into(), + (usdc_id_location.clone(), FEE_AMOUNT).into(), // foreign asset to transfer (not used for fees) - destination reserve - (foreign_asset_id_multilocation, SEND_AMOUNT).into(), + (foreign_asset_id_location.clone(), SEND_AMOUNT).into(), ); // balances checks before - assert_eq!(Assets::balance(usdc_id_multilocation, ALICE), usdc_initial_local_amount); + assert_eq!(AssetsPallet::balance(usdc_id_location.clone(), ALICE), usdc_initial_local_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer @@ -922,18 +922,18 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_remote_fee_reserve ); // Alice native asset untouched assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); - assert_eq!(Assets::balance(usdc_id_multilocation, ALICE), usdc_initial_local_amount); - assert_eq!(Assets::balance(foreign_asset_id_multilocation, ALICE), foreign_initial_amount); + assert_eq!(AssetsPallet::balance(usdc_id_location.clone(), ALICE), usdc_initial_local_amount); + assert_eq!(AssetsPallet::balance(foreign_asset_id_location.clone(), ALICE), foreign_initial_amount); assert_eq!(Balances::free_balance(usdc_chain_sovereign_account.clone()), 0); - assert_eq!(Assets::balance(usdc_id_multilocation, usdc_chain_sovereign_account), 0); + assert_eq!(AssetsPallet::balance(usdc_id_location.clone(), usdc_chain_sovereign_account), 0); assert_eq!(Balances::free_balance(dest_sovereign_account.clone()), 0); - assert_eq!(Assets::balance(foreign_asset_id_multilocation, dest_sovereign_account), 0); + assert_eq!(AssetsPallet::balance(foreign_asset_id_location.clone(), dest_sovereign_account), 0); let expected_usdc_issuance = usdc_initial_local_amount; - assert_eq!(Assets::total_issuance(usdc_id_multilocation), expected_usdc_issuance); - assert_eq!(Assets::active_issuance(usdc_id_multilocation), expected_usdc_issuance); + assert_eq!(AssetsPallet::total_issuance(usdc_id_location.clone()), expected_usdc_issuance); + assert_eq!(AssetsPallet::active_issuance(usdc_id_location.clone()), expected_usdc_issuance); let expected_bla_issuance = foreign_initial_amount; - assert_eq!(Assets::total_issuance(foreign_asset_id_multilocation), expected_bla_issuance); - assert_eq!(Assets::active_issuance(foreign_asset_id_multilocation), expected_bla_issuance); + assert_eq!(AssetsPallet::total_issuance(foreign_asset_id_location.clone()), expected_bla_issuance); + assert_eq!(AssetsPallet::active_issuance(foreign_asset_id_location), expected_bla_issuance); }); } @@ -955,12 +955,12 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_remote_fee_reserve #[test] fn reserve_transfer_assets_with_remote_asset_reserve_and_remote_fee_reserve_works() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = + let beneficiary: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { // create sufficient foreign asset USDC (0 total issuance) let usdc_initial_local_amount = 142; - let (usdc_chain, usdc_chain_sovereign_account, usdc_id_multilocation) = + let (usdc_chain, usdc_chain_sovereign_account, usdc_id_location) = set_up_foreign_asset( USDC_RESERVE_PARA_ID, Some(USDC_INNER_JUNCTION), @@ -971,51 +971,51 @@ fn reserve_transfer_assets_with_remote_asset_reserve_and_remote_fee_reserve_work // transfer destination is some other parachain let dest = RelayLocation::get().pushed_with_interior(Parachain(OTHER_PARA_ID)).unwrap(); - let assets: MultiAssets = vec![(usdc_id_multilocation, SEND_AMOUNT).into()].into(); + let assets: Assets = vec![(usdc_id_location.clone(), SEND_AMOUNT).into()].into(); let fee_index = 0; // reanchor according to test-case let context = UniversalLocation::get(); - let expected_dest_on_reserve = dest.reanchored(&usdc_chain, context).unwrap(); + let expected_dest_on_reserve = dest.clone().reanchored(&usdc_chain, &context).unwrap(); let fees = assets.get(fee_index).unwrap().clone(); let (fees_half_1, fees_half_2) = XcmPallet::halve_fees(fees).unwrap(); let mut expected_assets_on_reserve = assets.clone(); - expected_assets_on_reserve.reanchor(&usdc_chain, context).unwrap(); - let expected_fee_on_reserve = fees_half_1.reanchored(&usdc_chain, context).unwrap(); - let expected_fee_on_dest = fees_half_2.reanchored(&dest, context).unwrap(); + expected_assets_on_reserve.reanchor(&usdc_chain, &context).unwrap(); + let expected_fee_on_reserve = fees_half_1.reanchored(&usdc_chain, &context).unwrap(); + let expected_fee_on_dest = fees_half_2.reanchored(&dest, &context).unwrap(); // balances checks before - assert_eq!(Assets::balance(usdc_id_multilocation, ALICE), usdc_initial_local_amount); + assert_eq!(AssetsPallet::balance(usdc_id_location.clone(), ALICE), usdc_initial_local_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer assert_ok!(XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), - Box::new(dest.into()), - Box::new(beneficiary.into()), + Box::new(dest.clone().into()), + Box::new(beneficiary.clone().into()), Box::new(assets.into()), fee_index as u32, Unlimited, )); assert!(matches!( last_event(), - RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete(_) }) + RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete { .. } }) )); // Alice spent (transferred) amount assert_eq!( - Assets::balance(usdc_id_multilocation, ALICE), + AssetsPallet::balance(usdc_id_location.clone(), ALICE), usdc_initial_local_amount - SEND_AMOUNT ); // Alice's native asset balance is untouched assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // Destination account (parachain account) has expected (same) balances assert_eq!(Balances::free_balance(usdc_chain_sovereign_account.clone()), 0); - assert_eq!(Assets::balance(usdc_id_multilocation, usdc_chain_sovereign_account), 0); + assert_eq!(AssetsPallet::balance(usdc_id_location.clone(), usdc_chain_sovereign_account), 0); // Verify total and active issuance of USDC have decreased (burned on reserve-withdraw) let expected_usdc_issuance = usdc_initial_local_amount - SEND_AMOUNT; - assert_eq!(Assets::total_issuance(usdc_id_multilocation), expected_usdc_issuance); - assert_eq!(Assets::active_issuance(usdc_id_multilocation), expected_usdc_issuance); + assert_eq!(AssetsPallet::total_issuance(usdc_id_location.clone()), expected_usdc_issuance); + assert_eq!(AssetsPallet::active_issuance(usdc_id_location.clone()), expected_usdc_issuance); // Verify sent XCM program assert_eq!( @@ -1061,38 +1061,38 @@ fn reserve_transfer_assets_with_remote_asset_reserve_and_remote_fee_reserve_work #[test] fn reserve_transfer_assets_with_local_asset_reserve_and_teleported_fee_works() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = + let beneficiary: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { // create sufficient foreign asset USDT (0 total issuance) let usdt_initial_local_amount = 42; - let (usdt_chain, usdt_chain_sovereign_account, usdt_id_multilocation) = + let (usdt_chain, usdt_chain_sovereign_account, usdt_id_location) = set_up_foreign_asset(USDT_PARA_ID, None, usdt_initial_local_amount, true); // native assets transfer destination is USDT chain (teleport trust only for USDT) let dest = usdt_chain; - let (assets, fee_index, fee_asset, xfer_asset) = into_multiassets_checked( + let (assets, fee_index, fee_asset, xfer_asset) = into_assets_checked( // USDT for fees (is sufficient on local chain too) - teleported - (usdt_id_multilocation, FEE_AMOUNT).into(), + (usdt_id_location.clone(), FEE_AMOUNT).into(), // native asset to transfer (not used for fees) - local reserve - (MultiLocation::here(), SEND_AMOUNT).into(), + (Location::here(), SEND_AMOUNT).into(), ); // reanchor according to test-case let context = UniversalLocation::get(); - let expected_fee = fee_asset.reanchored(&dest, context).unwrap(); - let expected_asset = xfer_asset.reanchored(&dest, context).unwrap(); + let expected_fee = fee_asset.reanchored(&dest, &context).unwrap(); + let expected_asset = xfer_asset.reanchored(&dest, &context).unwrap(); // balances checks before - assert_eq!(Assets::balance(usdt_id_multilocation, ALICE), usdt_initial_local_amount); + assert_eq!(AssetsPallet::balance(usdt_id_location.clone(), ALICE), usdt_initial_local_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer assert_ok!(XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), - Box::new(dest.into()), - Box::new(beneficiary.into()), + Box::new(dest.clone().into()), + Box::new(beneficiary.clone().into()), Box::new(assets.into()), fee_index as u32, Unlimited, @@ -1101,13 +1101,13 @@ fn reserve_transfer_assets_with_local_asset_reserve_and_teleported_fee_works() { let mut last_events = last_events(3).into_iter(); assert_eq!( last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete(weight) }) + RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete { used: weight } }) ); assert_eq!( last_events.next().unwrap(), RuntimeEvent::XcmPallet(crate::Event::FeesPaid { - paying: beneficiary, - fees: MultiAssets::new(), + paying: beneficiary.clone(), + fees: Assets::new(), }) ); assert!(matches!( @@ -1116,18 +1116,18 @@ fn reserve_transfer_assets_with_local_asset_reserve_and_teleported_fee_works() { )); // Alice spent (fees) amount assert_eq!( - Assets::balance(usdt_id_multilocation, ALICE), + AssetsPallet::balance(usdt_id_location.clone(), ALICE), usdt_initial_local_amount - FEE_AMOUNT ); // Alice used native asset for transfer assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE - SEND_AMOUNT); // Sovereign account of dest parachain holds `SEND_AMOUNT` native asset in local reserve assert_eq!(Balances::free_balance(usdt_chain_sovereign_account.clone()), SEND_AMOUNT); - assert_eq!(Assets::balance(usdt_id_multilocation, usdt_chain_sovereign_account), 0); + assert_eq!(AssetsPallet::balance(usdt_id_location.clone(), usdt_chain_sovereign_account), 0); // Verify total and active issuance have decreased (teleported) let expected_usdt_issuance = usdt_initial_local_amount - FEE_AMOUNT; - assert_eq!(Assets::total_issuance(usdt_id_multilocation), expected_usdt_issuance); - assert_eq!(Assets::active_issuance(usdt_id_multilocation), expected_usdt_issuance); + assert_eq!(AssetsPallet::total_issuance(usdt_id_location.clone()), expected_usdt_issuance); + assert_eq!(AssetsPallet::active_issuance(usdt_id_location), expected_usdt_issuance); // Verify sent XCM program assert_eq!( @@ -1168,17 +1168,17 @@ fn reserve_transfer_assets_with_local_asset_reserve_and_teleported_fee_works() { #[test] fn reserve_transfer_assets_with_destination_asset_reserve_and_teleported_fee_works() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = + let beneficiary: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { // create sufficient foreign asset USDT (0 total issuance) let usdt_initial_local_amount = 42; - let (_, usdt_chain_sovereign_account, usdt_id_multilocation) = + let (_, usdt_chain_sovereign_account, usdt_id_location) = set_up_foreign_asset(USDT_PARA_ID, None, usdt_initial_local_amount, true); // create non-sufficient foreign asset BLA (0 total issuance) let foreign_initial_amount = 142; - let (reserve_location, foreign_sovereign_account, foreign_asset_id_multilocation) = + let (reserve_location, foreign_sovereign_account, foreign_asset_id_location) = set_up_foreign_asset( FOREIGN_ASSET_RESERVE_PARA_ID, Some(FOREIGN_ASSET_INNER_JUNCTION), @@ -1190,27 +1190,27 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_teleported_fee_wor let dest = reserve_location; let dest_sovereign_account = foreign_sovereign_account; - let (assets, fee_index, fee_asset, xfer_asset) = into_multiassets_checked( + let (assets, fee_index, fee_asset, xfer_asset) = into_assets_checked( // USDT for fees (is sufficient on local chain too) - teleported - (usdt_id_multilocation, FEE_AMOUNT).into(), + (usdt_id_location.clone(), FEE_AMOUNT).into(), // foreign asset to transfer (not used for fees) - destination reserve - (foreign_asset_id_multilocation, SEND_AMOUNT).into(), + (foreign_asset_id_location.clone(), SEND_AMOUNT).into(), ); // reanchor according to test-case let context = UniversalLocation::get(); - let expected_fee = fee_asset.reanchored(&dest, context).unwrap(); - let expected_asset = xfer_asset.reanchored(&dest, context).unwrap(); + let expected_fee = fee_asset.reanchored(&dest, &context).unwrap(); + let expected_asset = xfer_asset.reanchored(&dest, &context).unwrap(); // balances checks before - assert_eq!(Assets::balance(usdt_id_multilocation, ALICE), usdt_initial_local_amount); + assert_eq!(AssetsPallet::balance(usdt_id_location.clone(), ALICE), usdt_initial_local_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer assert_ok!(XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), - Box::new(dest.into()), - Box::new(beneficiary.into()), + Box::new(dest.clone().into()), + Box::new(beneficiary.clone().into()), Box::new(assets.into()), fee_index as u32, Unlimited, @@ -1219,13 +1219,13 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_teleported_fee_wor let mut last_events = last_events(3).into_iter(); assert_eq!( last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete(weight) }) + RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete { used: weight } }) ); assert_eq!( last_events.next().unwrap(), RuntimeEvent::XcmPallet(crate::Event::FeesPaid { - paying: beneficiary, - fees: MultiAssets::new(), + paying: beneficiary.clone(), + fees: Assets::new(), }) ); assert!(matches!( @@ -1236,29 +1236,29 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_teleported_fee_wor assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // Alice spent USDT for fees assert_eq!( - Assets::balance(usdt_id_multilocation, ALICE), + AssetsPallet::balance(usdt_id_location.clone(), ALICE), usdt_initial_local_amount - FEE_AMOUNT ); // Alice transferred BLA assert_eq!( - Assets::balance(foreign_asset_id_multilocation, ALICE), + AssetsPallet::balance(foreign_asset_id_location.clone(), ALICE), foreign_initial_amount - SEND_AMOUNT ); // Verify balances of USDT reserve parachain assert_eq!(Balances::free_balance(usdt_chain_sovereign_account.clone()), 0); - assert_eq!(Assets::balance(usdt_id_multilocation, usdt_chain_sovereign_account), 0); + assert_eq!(AssetsPallet::balance(usdt_id_location.clone(), usdt_chain_sovereign_account), 0); // Verify balances of transferred-asset reserve parachain assert_eq!(Balances::free_balance(dest_sovereign_account.clone()), 0); - assert_eq!(Assets::balance(foreign_asset_id_multilocation, dest_sovereign_account), 0); + assert_eq!(AssetsPallet::balance(foreign_asset_id_location.clone(), dest_sovereign_account), 0); // Verify total and active issuance of USDT have decreased (teleported) let expected_usdt_issuance = usdt_initial_local_amount - FEE_AMOUNT; - assert_eq!(Assets::total_issuance(usdt_id_multilocation), expected_usdt_issuance); - assert_eq!(Assets::active_issuance(usdt_id_multilocation), expected_usdt_issuance); + assert_eq!(AssetsPallet::total_issuance(usdt_id_location.clone()), expected_usdt_issuance); + assert_eq!(AssetsPallet::active_issuance(usdt_id_location.clone()), expected_usdt_issuance); // Verify total and active issuance of foreign BLA asset have decreased (burned on // reserve-withdraw) let expected_bla_issuance = foreign_initial_amount - SEND_AMOUNT; - assert_eq!(Assets::total_issuance(foreign_asset_id_multilocation), expected_bla_issuance); - assert_eq!(Assets::active_issuance(foreign_asset_id_multilocation), expected_bla_issuance); + assert_eq!(AssetsPallet::total_issuance(foreign_asset_id_location.clone()), expected_bla_issuance); + assert_eq!(AssetsPallet::active_issuance(foreign_asset_id_location), expected_bla_issuance); // Verify sent XCM program assert_eq!( @@ -1286,17 +1286,17 @@ fn reserve_transfer_assets_with_destination_asset_reserve_and_teleported_fee_wor #[test] fn reserve_transfer_assets_with_remote_asset_reserve_and_teleported_fee_disallowed() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = + let beneficiary: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { // create sufficient foreign asset USDT (0 total issuance) let usdt_initial_local_amount = 42; - let (usdt_chain, usdt_chain_sovereign_account, usdt_id_multilocation) = + let (usdt_chain, usdt_chain_sovereign_account, usdt_id_location) = set_up_foreign_asset(USDT_PARA_ID, None, usdt_initial_local_amount, true); // create non-sufficient foreign asset BLA (0 total issuance) let foreign_initial_amount = 142; - let (_, reserve_sovereign_account, foreign_asset_id_multilocation) = set_up_foreign_asset( + let (_, reserve_sovereign_account, foreign_asset_id_location) = set_up_foreign_asset( FOREIGN_ASSET_RESERVE_PARA_ID, Some(FOREIGN_ASSET_INNER_JUNCTION), foreign_initial_amount, @@ -1306,15 +1306,15 @@ fn reserve_transfer_assets_with_remote_asset_reserve_and_teleported_fee_disallow // transfer destination is USDT chain (foreign asset needs to go through its reserve chain) let dest = usdt_chain; - let (assets, fee_index, _, _) = into_multiassets_checked( + let (assets, fee_index, _, _) = into_assets_checked( // USDT for fees (is sufficient on local chain too) - teleported - (usdt_id_multilocation, FEE_AMOUNT).into(), + (usdt_id_location.clone(), FEE_AMOUNT).into(), // foreign asset to transfer (not used for fees) - remote reserve - (foreign_asset_id_multilocation, SEND_AMOUNT).into(), + (foreign_asset_id_location.clone(), SEND_AMOUNT).into(), ); // balances checks before - assert_eq!(Assets::balance(usdt_id_multilocation, ALICE), usdt_initial_local_amount); + assert_eq!(AssetsPallet::balance(usdt_id_location.clone(), ALICE), usdt_initial_local_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer @@ -1336,18 +1336,18 @@ fn reserve_transfer_assets_with_remote_asset_reserve_and_teleported_fee_disallow ); // Alice native asset untouched assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); - assert_eq!(Assets::balance(usdt_id_multilocation, ALICE), usdt_initial_local_amount); - assert_eq!(Assets::balance(foreign_asset_id_multilocation, ALICE), foreign_initial_amount); + assert_eq!(AssetsPallet::balance(usdt_id_location.clone(), ALICE), usdt_initial_local_amount); + assert_eq!(AssetsPallet::balance(foreign_asset_id_location.clone(), ALICE), foreign_initial_amount); assert_eq!(Balances::free_balance(usdt_chain_sovereign_account.clone()), 0); - assert_eq!(Assets::balance(usdt_id_multilocation, usdt_chain_sovereign_account), 0); + assert_eq!(AssetsPallet::balance(usdt_id_location.clone(), usdt_chain_sovereign_account), 0); assert_eq!(Balances::free_balance(reserve_sovereign_account.clone()), 0); - assert_eq!(Assets::balance(foreign_asset_id_multilocation, reserve_sovereign_account), 0); + assert_eq!(AssetsPallet::balance(foreign_asset_id_location.clone(), reserve_sovereign_account), 0); let expected_usdt_issuance = usdt_initial_local_amount; - assert_eq!(Assets::total_issuance(usdt_id_multilocation), expected_usdt_issuance); - assert_eq!(Assets::active_issuance(usdt_id_multilocation), expected_usdt_issuance); + assert_eq!(AssetsPallet::total_issuance(usdt_id_location.clone()), expected_usdt_issuance); + assert_eq!(AssetsPallet::active_issuance(usdt_id_location.clone()), expected_usdt_issuance); let expected_bla_issuance = foreign_initial_amount; - assert_eq!(Assets::total_issuance(foreign_asset_id_multilocation), expected_bla_issuance); - assert_eq!(Assets::active_issuance(foreign_asset_id_multilocation), expected_bla_issuance); + assert_eq!(AssetsPallet::total_issuance(foreign_asset_id_location.clone()), expected_bla_issuance); + assert_eq!(AssetsPallet::active_issuance(foreign_asset_id_location), expected_bla_issuance); }); } @@ -1357,22 +1357,22 @@ fn reserve_transfer_assets_with_remote_asset_reserve_and_teleported_fee_disallow #[test] fn reserve_transfer_assets_with_teleportable_asset_fails() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = + let beneficiary: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { // create sufficient foreign asset USDT (0 total issuance) let usdt_initial_local_amount = 42; - let (usdt_chain, usdt_chain_sovereign_account, usdt_id_multilocation) = + let (usdt_chain, usdt_chain_sovereign_account, usdt_id_location) = set_up_foreign_asset(USDT_PARA_ID, None, usdt_initial_local_amount, true); // transfer destination is USDT chain (foreign asset needs to go through its reserve chain) let dest = usdt_chain; - let assets: MultiAssets = vec![(usdt_id_multilocation, FEE_AMOUNT).into()].into(); + let assets: Assets = vec![(usdt_id_location.clone(), FEE_AMOUNT).into()].into(); let fee_index = 0; // balances checks before - assert_eq!(Assets::balance(usdt_id_multilocation, ALICE), usdt_initial_local_amount); + assert_eq!(AssetsPallet::balance(usdt_id_location.clone(), ALICE), usdt_initial_local_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer @@ -1395,11 +1395,11 @@ fn reserve_transfer_assets_with_teleportable_asset_fails() { // Alice native asset is still same assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // Alice USDT balance is still same - assert_eq!(Assets::balance(usdt_id_multilocation, ALICE), usdt_initial_local_amount); + assert_eq!(AssetsPallet::balance(usdt_id_location.clone(), ALICE), usdt_initial_local_amount); // No USDT moved to sovereign account of reserve parachain - assert_eq!(Assets::balance(usdt_id_multilocation, usdt_chain_sovereign_account), 0); + assert_eq!(AssetsPallet::balance(usdt_id_location.clone(), usdt_chain_sovereign_account), 0); // Verify total and active issuance of USDT are still the same - assert_eq!(Assets::total_issuance(usdt_id_multilocation), usdt_initial_local_amount); - assert_eq!(Assets::active_issuance(usdt_id_multilocation), usdt_initial_local_amount); + assert_eq!(AssetsPallet::total_issuance(usdt_id_location.clone()), usdt_initial_local_amount); + assert_eq!(AssetsPallet::active_issuance(usdt_id_location), usdt_initial_local_amount); }); } diff --git a/polkadot/xcm/pallet-xcm/src/tests/mod.rs b/polkadot/xcm/pallet-xcm/src/tests/mod.rs index 72814e507f2a..068ddfa39ad6 100644 --- a/polkadot/xcm/pallet-xcm/src/tests/mod.rs +++ b/polkadot/xcm/pallet-xcm/src/tests/mod.rs @@ -19,9 +19,8 @@ mod assets_transfer; use crate::{ - mock::*, AssetTraps, CurrentMigration, Error, LatestVersionedMultiLocation, Queries, - QueryStatus, VersionDiscoveryQueue, VersionMigrationStage, VersionNotifiers, - VersionNotifyTargets, + mock::*, AssetTraps, CurrentMigration, Error, LatestVersionedLocation, Queries, QueryStatus, + VersionDiscoveryQueue, VersionMigrationStage, VersionNotifiers, VersionNotifyTargets, }; use frame_support::{ assert_noop, assert_ok, @@ -49,9 +48,11 @@ fn report_outcome_notify_works() { (ALICE, INITIAL_BALANCE), (ParaId::from(OTHER_PARA_ID).into_account_truncating(), INITIAL_BALANCE), ]; - let sender: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); - let mut message = - Xcm(vec![TransferAsset { assets: (Here, SEND_AMOUNT).into(), beneficiary: sender }]); + let sender: Location = AccountId32 { network: None, id: ALICE.into() }.into(); + let mut message = Xcm(vec![TransferAsset { + assets: (Here, SEND_AMOUNT).into(), + beneficiary: sender.clone(), + }]); let call = pallet_test_notifier::Call::notification_received { query_id: 0, response: Default::default(), @@ -76,12 +77,12 @@ fn report_outcome_notify_works() { TransferAsset { assets: (Here, SEND_AMOUNT).into(), beneficiary: sender }, ]) ); - let querier: MultiLocation = Here.into(); + let querier: Location = Here.into(); let status = QueryStatus::Pending { - responder: MultiLocation::from(Parachain(OTHER_PARA_ID)).into(), + responder: Location::from(Parachain(OTHER_PARA_ID)).into(), maybe_notify: Some((5, 2)), timeout: 100, - maybe_match_querier: Some(querier.into()), + maybe_match_querier: Some(querier.clone().into()), }; assert_eq!(crate::Queries::::iter().collect::>(), vec![(0, status)]); @@ -91,14 +92,15 @@ fn report_outcome_notify_works() { max_weight: Weight::from_parts(1_000_000, 1_000_000), querier: Some(querier), }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(OTHER_PARA_ID), message, - hash, + &mut hash, Weight::from_parts(1_000_000_000, 1_000_000_000), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(1_000, 1_000))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(1_000, 1_000) }); assert_eq!( last_events(2), vec![ @@ -124,9 +126,11 @@ fn report_outcome_works() { (ALICE, INITIAL_BALANCE), (ParaId::from(OTHER_PARA_ID).into_account_truncating(), INITIAL_BALANCE), ]; - let sender: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); - let mut message = - Xcm(vec![TransferAsset { assets: (Here, SEND_AMOUNT).into(), beneficiary: sender }]); + let sender: Location = AccountId32 { network: None, id: ALICE.into() }.into(); + let mut message = Xcm(vec![TransferAsset { + assets: (Here, SEND_AMOUNT).into(), + beneficiary: sender.clone(), + }]); new_test_ext_with_balances(balances).execute_with(|| { XcmPallet::report_outcome(&mut message, Parachain(OTHER_PARA_ID).into_location(), 100) .unwrap(); @@ -141,12 +145,12 @@ fn report_outcome_works() { TransferAsset { assets: (Here, SEND_AMOUNT).into(), beneficiary: sender }, ]) ); - let querier: MultiLocation = Here.into(); + let querier: Location = Here.into(); let status = QueryStatus::Pending { - responder: MultiLocation::from(Parachain(OTHER_PARA_ID)).into(), + responder: Location::from(Parachain(OTHER_PARA_ID)).into(), maybe_notify: None, timeout: 100, - maybe_match_querier: Some(querier.into()), + maybe_match_querier: Some(querier.clone().into()), }; assert_eq!(crate::Queries::::iter().collect::>(), vec![(0, status)]); @@ -156,14 +160,15 @@ fn report_outcome_works() { max_weight: Weight::zero(), querier: Some(querier), }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(OTHER_PARA_ID), message, - hash, + &mut hash, Weight::from_parts(1_000_000_000, 1_000_000_000), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(1_000, 1_000))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(1_000, 1_000) }); assert_eq!( last_event(), RuntimeEvent::XcmPallet(crate::Event::ResponseReady { @@ -185,16 +190,15 @@ fn custom_querier_works() { (ParaId::from(OTHER_PARA_ID).into_account_truncating(), INITIAL_BALANCE), ]; new_test_ext_with_balances(balances).execute_with(|| { - let querier: MultiLocation = - (Parent, AccountId32 { network: None, id: ALICE.into() }).into(); + let querier: Location = (Parent, AccountId32 { network: None, id: ALICE.into() }).into(); - let r = TestNotifier::prepare_new_query(RuntimeOrigin::signed(ALICE), querier); + let r = TestNotifier::prepare_new_query(RuntimeOrigin::signed(ALICE), querier.clone()); assert_eq!(r, Ok(())); let status = QueryStatus::Pending { - responder: MultiLocation::from(AccountId32 { network: None, id: ALICE.into() }).into(), + responder: Location::from(AccountId32 { network: None, id: ALICE.into() }).into(), maybe_notify: None, timeout: 100, - maybe_match_querier: Some(querier.into()), + maybe_match_querier: Some(querier.clone().into()), }; assert_eq!(crate::Queries::::iter().collect::>(), vec![(0, status)]); @@ -205,21 +209,21 @@ fn custom_querier_works() { max_weight: Weight::zero(), querier: None, }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm_in_credit( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( AccountId32 { network: None, id: ALICE.into() }, message, - hash, + &mut hash, Weight::from_parts(1_000_000_000, 1_000_000_000), Weight::from_parts(1_000, 1_000), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(1_000, 1_000))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(1_000, 1_000) }); assert_eq!( last_event(), RuntimeEvent::XcmPallet(crate::Event::InvalidQuerier { origin: AccountId32 { network: None, id: ALICE.into() }.into(), query_id: 0, - expected_querier: querier, + expected_querier: querier.clone(), maybe_actual_querier: None, }), ); @@ -229,24 +233,24 @@ fn custom_querier_works() { query_id: 0, response: Response::ExecutionResult(None), max_weight: Weight::zero(), - querier: Some(MultiLocation::here()), + querier: Some(Location::here()), }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm_in_credit( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( AccountId32 { network: None, id: ALICE.into() }, message, - hash, + &mut hash, Weight::from_parts(1_000_000_000, 1_000_000_000), Weight::from_parts(1_000, 1_000), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(1_000, 1_000))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(1_000, 1_000) }); assert_eq!( last_event(), RuntimeEvent::XcmPallet(crate::Event::InvalidQuerier { origin: AccountId32 { network: None, id: ALICE.into() }.into(), query_id: 0, - expected_querier: querier, - maybe_actual_querier: Some(MultiLocation::here()), + expected_querier: querier.clone(), + maybe_actual_querier: Some(Location::here()), }), ); @@ -257,14 +261,15 @@ fn custom_querier_works() { max_weight: Weight::zero(), querier: Some(querier), }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( AccountId32 { network: None, id: ALICE.into() }, message, - hash, + &mut hash, Weight::from_parts(1_000_000_000, 1_000_000_000), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(1_000, 1_000))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(1_000, 1_000) }); assert_eq!( last_event(), RuntimeEvent::XcmPallet(crate::Event::ResponseReady { @@ -289,12 +294,12 @@ fn send_works() { (ParaId::from(OTHER_PARA_ID).into_account_truncating(), INITIAL_BALANCE), ]; new_test_ext_with_balances(balances).execute_with(|| { - let sender: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + let sender: Location = AccountId32 { network: None, id: ALICE.into() }.into(); let message = Xcm(vec![ ReserveAssetDeposited((Parent, SEND_AMOUNT).into()), ClearOrigin, buy_execution((Parent, SEND_AMOUNT)), - DepositAsset { assets: AllCounted(1).into(), beneficiary: sender }, + DepositAsset { assets: AllCounted(1).into(), beneficiary: sender.clone() }, ]); let versioned_dest = Box::new(RelayLocation::get().into()); @@ -304,7 +309,7 @@ fn send_works() { versioned_dest, versioned_message )); - let sent_message = Xcm(Some(DescendOrigin(sender.try_into().unwrap())) + let sent_message = Xcm(Some(DescendOrigin(sender.clone().try_into().unwrap())) .into_iter() .chain(message.0.clone().into_iter()) .collect()); @@ -333,8 +338,7 @@ fn send_fails_when_xcm_router_blocks() { (ParaId::from(OTHER_PARA_ID).into_account_truncating(), INITIAL_BALANCE), ]; new_test_ext_with_balances(balances).execute_with(|| { - let sender: MultiLocation = - Junction::AccountId32 { network: None, id: ALICE.into() }.into(); + let sender: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); let message = Xcm(vec![ ReserveAssetDeposited((Parent, SEND_AMOUNT).into()), buy_execution((Parent, SEND_AMOUNT)), @@ -343,7 +347,7 @@ fn send_fails_when_xcm_router_blocks() { assert_noop!( XcmPallet::send( RuntimeOrigin::signed(ALICE), - Box::new(MultiLocation::ancestor(8).into()), + Box::new(Location::ancestor(8).into()), Box::new(VersionedXcm::from(message.clone())), ), crate::Error::::SendFailure @@ -363,7 +367,7 @@ fn execute_withdraw_to_deposit_works() { ]; new_test_ext_with_balances(balances).execute_with(|| { let weight = BaseXcmWeight::get() * 3; - let dest: MultiLocation = Junction::AccountId32 { network: None, id: BOB.into() }.into(); + let dest: Location = Junction::AccountId32 { network: None, id: BOB.into() }.into(); assert_eq!(Balances::total_balance(&ALICE), INITIAL_BALANCE); assert_ok!(XcmPallet::execute( RuntimeOrigin::signed(ALICE), @@ -378,7 +382,7 @@ fn execute_withdraw_to_deposit_works() { assert_eq!(Balances::total_balance(&BOB), SEND_AMOUNT); assert_eq!( last_event(), - RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete(weight) }) + RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete { used: weight } }) ); }); } @@ -389,7 +393,7 @@ fn trapped_assets_can_be_claimed() { let balances = vec![(ALICE, INITIAL_BALANCE), (BOB, INITIAL_BALANCE)]; new_test_ext_with_balances(balances).execute_with(|| { let weight = BaseXcmWeight::get() * 6; - let dest: MultiLocation = Junction::AccountId32 { network: None, id: BOB.into() }.into(); + let dest: Location = Junction::AccountId32 { network: None, id: BOB.into() }.into(); assert_ok!(XcmPallet::execute( RuntimeOrigin::signed(ALICE), @@ -401,15 +405,14 @@ fn trapped_assets_can_be_claimed() { // This will make an error. Trap(0), // This would succeed, but we never get to it. - DepositAsset { assets: AllCounted(1).into(), beneficiary: dest }, + DepositAsset { assets: AllCounted(1).into(), beneficiary: dest.clone() }, ]))), weight )); - let source: MultiLocation = - Junction::AccountId32 { network: None, id: ALICE.into() }.into(); + let source: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); let trapped = AssetTraps::::iter().collect::>(); - let vma = VersionedMultiAssets::from(MultiAssets::from((Here, SEND_AMOUNT))); - let hash = BlakeTwo256::hash_of(&(source, vma.clone())); + let vma = VersionedAssets::from(Assets::from((Here, SEND_AMOUNT))); + let hash = BlakeTwo256::hash_of(&(source.clone(), vma.clone())); assert_eq!( last_events(2), vec![ @@ -419,7 +422,7 @@ fn trapped_assets_can_be_claimed() { assets: vma }), RuntimeEvent::XcmPallet(crate::Event::Attempted { - outcome: Outcome::Complete(BaseXcmWeight::get() * 5) + outcome: Outcome::Complete { used: BaseXcmWeight::get() * 5 } }), ] ); @@ -435,7 +438,7 @@ fn trapped_assets_can_be_claimed() { Box::new(VersionedXcm::from(Xcm(vec![ ClaimAsset { assets: (Here, SEND_AMOUNT).into(), ticket: Here.into() }, buy_execution((Here, SEND_AMOUNT)), - DepositAsset { assets: AllCounted(1).into(), beneficiary: dest }, + DepositAsset { assets: AllCounted(1).into(), beneficiary: dest.clone() }, ]))), weight )); @@ -454,41 +457,44 @@ fn trapped_assets_can_be_claimed() { ]))), weight )); - let outcome = Outcome::Incomplete(BaseXcmWeight::get(), XcmError::UnknownClaim); + let outcome = Outcome::Incomplete { used: BaseXcmWeight::get(), error: XcmError::UnknownClaim }; assert_eq!(last_event(), RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome })); }); } #[test] -fn fake_latest_versioned_multilocation_works() { +fn fake_latest_versioned_location_works() { use codec::Encode; - let remote: MultiLocation = Parachain(1000).into(); - let versioned_remote = LatestVersionedMultiLocation(&remote); + let remote: Location = Parachain(1000).into(); + let versioned_remote = LatestVersionedLocation(&remote); assert_eq!(versioned_remote.encode(), remote.into_versioned().encode()); } #[test] fn basic_subscription_works() { new_test_ext_with_balances(vec![]).execute_with(|| { - let remote: MultiLocation = Parachain(1000).into(); + let remote: Location = Parachain(1000).into(); assert_ok!(XcmPallet::force_subscribe_version_notify( RuntimeOrigin::root(), - Box::new(remote.into()), + Box::new(remote.clone().into()), )); assert_eq!( Queries::::iter().collect::>(), - vec![(0, QueryStatus::VersionNotifier { origin: remote.into(), is_active: false })] + vec![( + 0, + QueryStatus::VersionNotifier { origin: remote.clone().into(), is_active: false } + )] ); assert_eq!( VersionNotifiers::::iter().collect::>(), - vec![(XCM_VERSION, remote.into(), 0)] + vec![(XCM_VERSION, remote.clone().into(), 0)] ); assert_eq!( take_sent_xcm(), vec![( - remote, + remote.clone(), Xcm(vec![SubscribeVersion { query_id: 0, max_response_weight: Weight::zero() }]), ),] ); @@ -515,16 +521,16 @@ fn basic_subscription_works() { #[test] fn subscriptions_increment_id() { new_test_ext_with_balances(vec![]).execute_with(|| { - let remote: MultiLocation = Parachain(1000).into(); + let remote: Location = Parachain(1000).into(); assert_ok!(XcmPallet::force_subscribe_version_notify( RuntimeOrigin::root(), - Box::new(remote.into()), + Box::new(remote.clone().into()), )); - let remote2: MultiLocation = Parachain(1001).into(); + let remote2: Location = Parachain(1001).into(); assert_ok!(XcmPallet::force_subscribe_version_notify( RuntimeOrigin::root(), - Box::new(remote2.into()), + Box::new(remote2.clone().into()), )); assert_eq!( @@ -552,10 +558,10 @@ fn subscriptions_increment_id() { #[test] fn double_subscription_fails() { new_test_ext_with_balances(vec![]).execute_with(|| { - let remote: MultiLocation = Parachain(1000).into(); + let remote: Location = Parachain(1000).into(); assert_ok!(XcmPallet::force_subscribe_version_notify( RuntimeOrigin::root(), - Box::new(remote.into()), + Box::new(remote.clone().into()), )); assert_noop!( XcmPallet::force_subscribe_version_notify( @@ -570,19 +576,19 @@ fn double_subscription_fails() { #[test] fn unsubscribe_works() { new_test_ext_with_balances(vec![]).execute_with(|| { - let remote: MultiLocation = Parachain(1000).into(); + let remote: Location = Parachain(1000).into(); assert_ok!(XcmPallet::force_subscribe_version_notify( RuntimeOrigin::root(), - Box::new(remote.into()), + Box::new(remote.clone().into()), )); assert_ok!(XcmPallet::force_unsubscribe_version_notify( RuntimeOrigin::root(), - Box::new(remote.into()) + Box::new(remote.clone().into()) )); assert_noop!( XcmPallet::force_unsubscribe_version_notify( RuntimeOrigin::root(), - Box::new(remote.into()) + Box::new(remote.clone().into()) ), Error::::NoSubscription, ); @@ -591,13 +597,13 @@ fn unsubscribe_works() { take_sent_xcm(), vec![ ( - remote, + remote.clone(), Xcm(vec![SubscribeVersion { query_id: 0, max_response_weight: Weight::zero() }]), ), - (remote, Xcm(vec![UnsubscribeVersion]),), + (remote.clone(), Xcm(vec![UnsubscribeVersion]),), ] ); }); @@ -609,13 +615,13 @@ fn subscription_side_works() { new_test_ext_with_balances(vec![]).execute_with(|| { AdvertisedXcmVersion::set(1); - let remote: MultiLocation = Parachain(1000).into(); + let remote: Location = Parachain(1000).into(); let weight = BaseXcmWeight::get(); let message = Xcm(vec![SubscribeVersion { query_id: 0, max_response_weight: Weight::zero() }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm(remote, message, hash, weight); - assert_eq!(r, Outcome::Complete(weight)); + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute(remote.clone(), message, &mut hash, weight, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: weight }); let instr = QueryResponse { query_id: 0, @@ -623,7 +629,7 @@ fn subscription_side_works() { response: Response::Version(1), querier: None, }; - assert_eq!(take_sent_xcm(), vec![(remote, Xcm(vec![instr]))]); + assert_eq!(take_sent_xcm(), vec![(remote.clone(), Xcm(vec![instr]))]); // A runtime upgrade which doesn't alter the version sends no notifications. CurrentMigration::::put(VersionMigrationStage::default()); @@ -652,7 +658,7 @@ fn subscription_side_upgrades_work_with_notify() { AdvertisedXcmVersion::set(1); // An entry from a previous runtime with v2 XCM. - let v2_location = VersionedMultiLocation::V2(xcm::v2::Junction::Parachain(1001).into()); + let v2_location = VersionedLocation::V2(xcm::v2::Junction::Parachain(1001).into()); VersionNotifyTargets::::insert(1, v2_location, (70, Weight::zero(), 2)); let v3_location = Parachain(1003).into_versioned(); VersionNotifyTargets::::insert(3, v3_location, (72, Weight::zero(), 2)); @@ -705,7 +711,7 @@ fn subscription_side_upgrades_work_with_notify() { fn subscription_side_upgrades_work_without_notify() { new_test_ext_with_balances(vec![]).execute_with(|| { // An entry from a previous runtime with v2 XCM. - let v2_location = VersionedMultiLocation::V2(xcm::v2::Junction::Parachain(1001).into()); + let v2_location = VersionedLocation::V2(xcm::v2::Junction::Parachain(1001).into()); VersionNotifyTargets::::insert(1, v2_location, (70, Weight::zero(), 2)); let v3_location = Parachain(1003).into_versioned(); VersionNotifyTargets::::insert(3, v3_location, (72, Weight::zero(), 2)); @@ -719,8 +725,8 @@ fn subscription_side_upgrades_work_without_notify() { assert_eq!( contents, vec![ - (XCM_VERSION, Parachain(1001).into_versioned(), (70, Weight::zero(), 3)), - (XCM_VERSION, Parachain(1003).into_versioned(), (72, Weight::zero(), 3)), + (XCM_VERSION, Parachain(1001).into_versioned(), (70, Weight::zero(), 4)), + (XCM_VERSION, Parachain(1003).into_versioned(), (72, Weight::zero(), 4)), ] ); }); @@ -729,10 +735,10 @@ fn subscription_side_upgrades_work_without_notify() { #[test] fn subscriber_side_subscription_works() { new_test_ext_with_balances(vec![]).execute_with(|| { - let remote: MultiLocation = Parachain(1000).into(); + let remote: Location = Parachain(1000).into(); assert_ok!(XcmPallet::force_subscribe_version_notify( RuntimeOrigin::root(), - Box::new(remote.into()), + Box::new(remote.clone().into()), )); take_sent_xcm(); @@ -748,9 +754,9 @@ fn subscriber_side_subscription_works() { querier: None, }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm(remote, message, hash, weight); - assert_eq!(r, Outcome::Complete(weight)); + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute(remote.clone(), message, &mut hash, weight, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: weight }); assert_eq!(take_sent_xcm(), vec![]); // This message cannot be sent to a v2 remote. @@ -766,9 +772,9 @@ fn subscriber_side_subscription_works() { querier: None, }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm(remote, message, hash, weight); - assert_eq!(r, Outcome::Complete(weight)); + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute(remote.clone(), message, &mut hash, weight, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: weight }); // This message can now be sent to remote as it's v2. assert_eq!( @@ -782,73 +788,73 @@ fn subscriber_side_subscription_works() { #[test] fn auto_subscription_works() { new_test_ext_with_balances(vec![]).execute_with(|| { - let remote_v2: MultiLocation = Parachain(1000).into(); - let remote_v3: MultiLocation = Parachain(1001).into(); + let remote_v2: Location = Parachain(1000).into(); + let remote_v4: Location = Parachain(1001).into(); assert_ok!(XcmPallet::force_default_xcm_version(RuntimeOrigin::root(), Some(2))); // Wrapping a version for a destination we don't know elicits a subscription. let msg_v2 = xcm::v2::Xcm::<()>(vec![xcm::v2::Instruction::Trap(0)]); - let msg_v3 = xcm::v3::Xcm::<()>(vec![xcm::v3::Instruction::ClearTopic]); + let msg_v4 = xcm::v4::Xcm::<()>(vec![xcm::v4::Instruction::ClearTopic]); assert_eq!( XcmPallet::wrap_version(&remote_v2, msg_v2.clone()), Ok(VersionedXcm::from(msg_v2.clone())), ); - assert_eq!(XcmPallet::wrap_version(&remote_v2, msg_v3.clone()), Err(())); + assert_eq!(XcmPallet::wrap_version(&remote_v2, msg_v4.clone()), Err(())); - let expected = vec![(remote_v2.into(), 2)]; + let expected = vec![(remote_v2.clone().into(), 2)]; assert_eq!(VersionDiscoveryQueue::::get().into_inner(), expected); assert_eq!( - XcmPallet::wrap_version(&remote_v3, msg_v2.clone()), + XcmPallet::wrap_version(&remote_v4, msg_v2.clone()), Ok(VersionedXcm::from(msg_v2.clone())), ); - assert_eq!(XcmPallet::wrap_version(&remote_v3, msg_v3.clone()), Err(())); + assert_eq!(XcmPallet::wrap_version(&remote_v4, msg_v4.clone()), Err(())); - let expected = vec![(remote_v2.into(), 2), (remote_v3.into(), 2)]; + let expected = vec![(remote_v2.clone().into(), 2), (remote_v4.clone().into(), 2)]; assert_eq!(VersionDiscoveryQueue::::get().into_inner(), expected); XcmPallet::on_initialize(1); assert_eq!( take_sent_xcm(), vec![( - remote_v3, + remote_v4.clone(), Xcm(vec![SubscribeVersion { query_id: 0, max_response_weight: Weight::zero() }]), )] ); - // Assume remote_v3 is working ok and XCM version 3. + // Assume remote_v4 is working ok and XCM version 4. let weight = BaseXcmWeight::get(); let message = Xcm(vec![ - // Remote supports XCM v3 + // Remote supports XCM v4 QueryResponse { query_id: 0, max_weight: Weight::zero(), - response: Response::Version(3), + response: Response::Version(4), querier: None, }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm(remote_v3, message, hash, weight); - assert_eq!(r, Outcome::Complete(weight)); + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute(remote_v4.clone(), message, &mut hash, weight, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: weight }); - // V2 messages can be sent to remote_v3 under XCM v3. + // V2 messages can be sent to remote_v4 under XCM v4. assert_eq!( - XcmPallet::wrap_version(&remote_v3, msg_v2.clone()), - Ok(VersionedXcm::from(msg_v2.clone()).into_version(3).unwrap()), + XcmPallet::wrap_version(&remote_v4, msg_v2.clone()), + Ok(VersionedXcm::from(msg_v2.clone()).into_version(4).unwrap()), ); - // This message can now be sent to remote_v3 as it's v3. + // This message can now be sent to remote_v4 as it's v4. assert_eq!( - XcmPallet::wrap_version(&remote_v3, msg_v3.clone()), - Ok(VersionedXcm::from(msg_v3.clone())) + XcmPallet::wrap_version(&remote_v4, msg_v4.clone()), + Ok(VersionedXcm::from(msg_v4.clone())) ); XcmPallet::on_initialize(2); assert_eq!( take_sent_xcm(), vec![( - remote_v2, + remote_v2.clone(), Xcm(vec![SubscribeVersion { query_id: 1, max_response_weight: Weight::zero() }]), )] ); @@ -865,16 +871,16 @@ fn auto_subscription_works() { querier: None, }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm(remote_v2, message, hash, weight); - assert_eq!(r, Outcome::Complete(weight)); + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute(remote_v2.clone(), message, &mut hash, weight, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: weight }); - // v3 messages cannot be sent to remote_v2... + // v4 messages cannot be sent to remote_v2... assert_eq!( XcmPallet::wrap_version(&remote_v2, msg_v2.clone()), Ok(VersionedXcm::V2(msg_v2)) ); - assert_eq!(XcmPallet::wrap_version(&remote_v2, msg_v3.clone()), Err(())); + assert_eq!(XcmPallet::wrap_version(&remote_v2, msg_v4.clone()), Err(())); }) } @@ -884,9 +890,9 @@ fn subscription_side_upgrades_work_with_multistage_notify() { AdvertisedXcmVersion::set(1); // An entry from a previous runtime with v0 XCM. - let v2_location = VersionedMultiLocation::V2(xcm::v2::Junction::Parachain(1001).into()); + let v2_location = VersionedLocation::V2(xcm::v2::Junction::Parachain(1001).into()); VersionNotifyTargets::::insert(1, v2_location, (70, Weight::zero(), 1)); - let v2_location = VersionedMultiLocation::V2(xcm::v2::Junction::Parachain(1002).into()); + let v2_location = VersionedLocation::V2(xcm::v2::Junction::Parachain(1002).into()); VersionNotifyTargets::::insert(2, v2_location, (71, Weight::zero(), 1)); let v3_location = Parachain(1003).into_versioned(); VersionNotifyTargets::::insert(3, v3_location, (72, Weight::zero(), 1)); diff --git a/polkadot/xcm/procedural/Cargo.toml b/polkadot/xcm/procedural/Cargo.toml index 33c2a94be0e4..f8b4d01c9551 100644 --- a/polkadot/xcm/procedural/Cargo.toml +++ b/polkadot/xcm/procedural/Cargo.toml @@ -17,4 +17,5 @@ syn = "2.0.38" Inflector = "0.11.4" [dev-dependencies] +xcm = { package = "staging-xcm", path = ".." } trybuild = { version = "1.0.74", features = ["diff"] } diff --git a/polkadot/xcm/procedural/src/lib.rs b/polkadot/xcm/procedural/src/lib.rs index 83cc6cdf98ff..bbc40a13c4c1 100644 --- a/polkadot/xcm/procedural/src/lib.rs +++ b/polkadot/xcm/procedural/src/lib.rs @@ -21,6 +21,7 @@ use proc_macro::TokenStream; mod builder_pattern; mod v2; mod v3; +mod v4; mod weight_info; #[proc_macro] @@ -30,6 +31,13 @@ pub fn impl_conversion_functions_for_multilocation_v2(input: TokenStream) -> Tok .into() } +#[proc_macro] +pub fn impl_conversion_functions_for_junctions_v2(input: TokenStream) -> TokenStream { + v2::junctions::generate_conversion_functions(input) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + #[proc_macro_derive(XcmWeightInfoTrait)] pub fn derive_xcm_weight_info(item: TokenStream) -> TokenStream { weight_info::derive(item) @@ -49,6 +57,20 @@ pub fn impl_conversion_functions_for_junctions_v3(input: TokenStream) -> TokenSt .into() } +#[proc_macro] +pub fn impl_conversion_functions_for_location_v4(input: TokenStream) -> TokenStream { + v4::location::generate_conversion_functions(input) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + +#[proc_macro] +pub fn impl_conversion_functions_for_junctions_v4(input: TokenStream) -> TokenStream { + v4::junctions::generate_conversion_functions(input) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + /// This is called on the `Instruction` enum, not on the `Xcm` struct, /// and allows for the following syntax for building XCMs: /// let message = Xcm::builder() diff --git a/polkadot/xcm/procedural/src/v2.rs b/polkadot/xcm/procedural/src/v2.rs index dc2694a666f0..1a2f281a4982 100644 --- a/polkadot/xcm/procedural/src/v2.rs +++ b/polkadot/xcm/procedural/src/v2.rs @@ -14,10 +14,12 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . +use proc_macro2::{Span, TokenStream}; +use quote::{format_ident, quote}; +use syn::{Result, Token}; + pub mod multilocation { - use proc_macro2::{Span, TokenStream}; - use quote::{format_ident, quote}; - use syn::{Result, Token}; + use super::*; pub fn generate_conversion_functions(input: proc_macro::TokenStream) -> Result { if !input.is_empty() { @@ -181,3 +183,44 @@ pub mod multilocation { } } } + +pub mod junctions { + use super::*; + + pub fn generate_conversion_functions(input: proc_macro::TokenStream) -> Result { + if !input.is_empty() { + return Err(syn::Error::new(Span::call_site(), "No arguments expected")); + } + + let from_slice_syntax = generate_conversion_from_slice_syntax(); + + Ok(quote! { + #from_slice_syntax + }) + } + + fn generate_conversion_from_slice_syntax() -> TokenStream { + quote! { + macro_rules! impl_junction { + ($count:expr, $variant:ident, ($($index:literal),+)) => { + /// Additional helper for building junctions + /// Useful for converting to future XCM versions + impl From<[Junction; $count]> for Junctions { + fn from(junctions: [Junction; $count]) -> Self { + Self::$variant($(junctions[$index].clone()),*) + } + } + }; + } + + impl_junction!(1, X1, (0)); + impl_junction!(2, X2, (0, 1)); + impl_junction!(3, X3, (0, 1, 2)); + impl_junction!(4, X4, (0, 1, 2, 3)); + impl_junction!(5, X5, (0, 1, 2, 3, 4)); + impl_junction!(6, X6, (0, 1, 2, 3, 4, 5)); + impl_junction!(7, X7, (0, 1, 2, 3, 4, 5, 6)); + impl_junction!(8, X8, (0, 1, 2, 3, 4, 5, 6, 7)); + } + } +} diff --git a/polkadot/xcm/procedural/src/v3.rs b/polkadot/xcm/procedural/src/v3.rs index 246f90a46a3e..f0556d5a8d44 100644 --- a/polkadot/xcm/procedural/src/v3.rs +++ b/polkadot/xcm/procedural/src/v3.rs @@ -45,9 +45,8 @@ pub mod multilocation { let interior = if num_junctions == 0 { quote!(Junctions::Here) } else { - let variant = format_ident!("X{}", num_junctions); quote! { - Junctions::#variant( #(#idents .into()),* ) + [#(#idents .into()),*].into() } }; @@ -110,7 +109,7 @@ pub mod multilocation { impl From for MultiLocation { fn from(x: Junction) -> Self { - MultiLocation { parents: 0, interior: Junctions::X1(x) } + MultiLocation { parents: 0, interior: [x].into() } } } @@ -129,10 +128,12 @@ pub mod junctions { // Support up to 8 Parents in a tuple, assuming that most use cases don't go past 8 parents. let from_v2 = generate_conversion_from_v2(MAX_JUNCTIONS); + let from_v4 = generate_conversion_from_v4(); let from_tuples = generate_conversion_from_tuples(MAX_JUNCTIONS); Ok(quote! { #from_v2 + #from_v4 #from_tuples }) } @@ -143,12 +144,11 @@ pub mod junctions { let idents = (0..num_junctions).map(|i| format_ident!("j{}", i)).collect::>(); let types = (0..num_junctions).map(|i| format_ident!("J{}", i)).collect::>(); - let variant = &format_ident!("X{}", num_junctions); quote! { impl<#(#types : Into,)*> From<( #(#types,)* )> for Junctions { fn from( ( #(#idents,)* ): ( #(#types,)* ) ) -> Self { - Self::#variant( #(#idents .into()),* ) + [#(#idents .into()),*].into() } } } @@ -156,6 +156,45 @@ pub mod junctions { .collect() } + fn generate_conversion_from_v4() -> TokenStream { + let match_variants = (0..8u8) + .map(|current_number| { + let number_ancestors = current_number + 1; + let variant = format_ident!("X{}", number_ancestors); + let idents = + (0..=current_number).map(|i| format_ident!("j{}", i)).collect::>(); + let convert = idents + .iter() + .map(|ident| { + quote! { let #ident = core::convert::TryInto::try_into(#ident.clone())?; } + }) + .collect::>(); + + quote! { + crate::v4::Junctions::#variant( junctions ) => { + let [#(#idents),*] = &*junctions; + #(#convert);* + [#(#idents),*].into() + }, + } + }) + .collect::(); + + quote! { + impl core::convert::TryFrom for Junctions { + type Error = (); + + fn try_from(mut new: crate::v4::Junctions) -> core::result::Result { + use Junctions::*; + Ok(match new { + crate::v4::Junctions::Here => Here, + #match_variants + }) + } + } + } + } + fn generate_conversion_from_v2(max_junctions: usize) -> TokenStream { let match_variants = (0..max_junctions) .map(|cur_num| { diff --git a/polkadot/xcm/procedural/src/v4.rs b/polkadot/xcm/procedural/src/v4.rs new file mode 100644 index 000000000000..5f5e10d3081b --- /dev/null +++ b/polkadot/xcm/procedural/src/v4.rs @@ -0,0 +1,196 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +use proc_macro2::{Span, TokenStream}; +use quote::{format_ident, quote}; +use syn::{Result, Token}; + +const MAX_JUNCTIONS: usize = 8; + +pub mod location { + use super::*; + + /// Generates conversion functions from other types to the `Location` type: + /// - [PalletInstance(50), GeneralIndex(1984)].into() + /// - (Parent, Parachain(1000), AccountId32 { .. }).into() + pub fn generate_conversion_functions(input: proc_macro::TokenStream) -> Result { + if !input.is_empty() { + return Err(syn::Error::new(Span::call_site(), "No arguments expected")) + } + + let from_tuples = generate_conversion_from_tuples(8, 8); + + Ok(quote! { + #from_tuples + }) + } + + fn generate_conversion_from_tuples(max_junctions: usize, max_parents: usize) -> TokenStream { + let mut from_tuples = (0..=max_junctions) + .map(|num_junctions| { + let types = (0..num_junctions).map(|i| format_ident!("J{}", i)).collect::>(); + let idents = + (0..num_junctions).map(|i| format_ident!("j{}", i)).collect::>(); + let array_size = num_junctions; + let interior = if num_junctions == 0 { + quote!(Junctions::Here) + } else { + let variant = format_ident!("X{}", num_junctions); + quote! { + Junctions::#variant( alloc::sync::Arc::new( [#(#idents .into()),*] ) ) + } + }; + + let mut from_tuple = quote! { + impl< #(#types : Into,)* > From<( Ancestor, #( #types ),* )> for Location { + fn from( ( Ancestor(parents), #(#idents),* ): ( Ancestor, #( #types ),* ) ) -> Self { + Location { parents, interior: #interior } + } + } + + impl From<[Junction; #array_size]> for Location { + fn from(j: [Junction; #array_size]) -> Self { + let [#(#idents),*] = j; + Location { parents: 0, interior: #interior } + } + } + }; + + let from_parent_tuples = (0..=max_parents).map(|cur_parents| { + let parents = + (0..cur_parents).map(|_| format_ident!("Parent")).collect::>(); + let underscores = + (0..cur_parents).map(|_| Token![_](Span::call_site())).collect::>(); + + quote! { + impl< #(#types : Into,)* > From<( #( #parents , )* #( #types , )* )> for Location { + fn from( ( #(#underscores,)* #(#idents,)* ): ( #(#parents,)* #(#types,)* ) ) -> Self { + Self { parents: #cur_parents as u8, interior: #interior } + } + } + } + }); + + from_tuple.extend(from_parent_tuples); + from_tuple + }) + .collect::(); + + let from_parent_junctions_tuples = (0..=max_parents).map(|cur_parents| { + let parents = (0..cur_parents).map(|_| format_ident!("Parent")).collect::>(); + let underscores = + (0..cur_parents).map(|_| Token![_](Span::call_site())).collect::>(); + + quote! { + impl From<( #(#parents,)* Junctions )> for Location { + fn from( (#(#underscores,)* junctions): ( #(#parents,)* Junctions ) ) -> Self { + Location { parents: #cur_parents as u8, interior: junctions } + } + } + } + }); + from_tuples.extend(from_parent_junctions_tuples); + + quote! { + impl From<(Ancestor, Junctions)> for Location { + fn from((Ancestor(parents), interior): (Ancestor, Junctions)) -> Self { + Location { parents, interior } + } + } + + impl From for Location { + fn from(x: Junction) -> Self { + Location { parents: 0, interior: [x].into() } + } + } + + #from_tuples + } + } +} + +pub mod junctions { + use super::*; + + pub fn generate_conversion_functions(input: proc_macro::TokenStream) -> Result { + if !input.is_empty() { + return Err(syn::Error::new(Span::call_site(), "No arguments expected")) + } + + // Support up to 8 Parents in a tuple, assuming that most use cases don't go past 8 parents. + let from_v3 = generate_conversion_from_v3(MAX_JUNCTIONS); + let from_tuples = generate_conversion_from_tuples(MAX_JUNCTIONS); + + Ok(quote! { + #from_v3 + #from_tuples + }) + } + + fn generate_conversion_from_tuples(max_junctions: usize) -> TokenStream { + (1..=max_junctions) + .map(|num_junctions| { + let idents = + (0..num_junctions).map(|i| format_ident!("j{}", i)).collect::>(); + let types = (0..num_junctions).map(|i| format_ident!("J{}", i)).collect::>(); + + quote! { + impl<#(#types : Into,)*> From<( #(#types,)* )> for Junctions { + fn from( ( #(#idents,)* ): ( #(#types,)* ) ) -> Self { + [#(#idents .into()),*].into() + } + } + } + }) + .collect() + } + + fn generate_conversion_from_v3(max_junctions: usize) -> TokenStream { + let match_variants = (0..max_junctions) + .map(|cur_num| { + let num_ancestors = cur_num + 1; + let variant = format_ident!("X{}", num_ancestors); + let idents = (0..=cur_num).map(|i| format_ident!("j{}", i)).collect::>(); + let convert = idents + .iter() + .map(|ident| { + quote! { let #ident = core::convert::TryInto::try_into(#ident.clone())?; } + }) + .collect::>(); + + quote! { + crate::v3::Junctions::#variant( #(#idents),* ) => { + #(#convert);*; + let junctions: Junctions = [#(#idents),*].into(); + junctions + }, + } + }) + .collect::(); + + quote! { + impl core::convert::TryFrom for Junctions { + type Error = (); + fn try_from(mut old: crate::v3::Junctions) -> core::result::Result { + Ok(match old { + crate::v3::Junctions::Here => Junctions::Here, + #match_variants + }) + } + } + } + } +} diff --git a/polkadot/xcm/procedural/tests/conversion_functions.rs b/polkadot/xcm/procedural/tests/conversion_functions.rs new file mode 100644 index 000000000000..94566539ff4f --- /dev/null +++ b/polkadot/xcm/procedural/tests/conversion_functions.rs @@ -0,0 +1,8 @@ +use xcm::v2::prelude::*; + +#[test] +fn slice_syntax_in_v2_works() { + let old_junctions = Junctions::X2(Parachain(1), PalletInstance(1)); + let new_junctions = Junctions::from([Parachain(1), PalletInstance(1)]); + assert_eq!(old_junctions, new_junctions); +} diff --git a/polkadot/xcm/src/lib.rs b/polkadot/xcm/src/lib.rs index d804e4bf7351..b5c6b2adbf45 100644 --- a/polkadot/xcm/src/lib.rs +++ b/polkadot/xcm/src/lib.rs @@ -30,13 +30,14 @@ use scale_info::TypeInfo; pub mod v2; pub mod v3; +pub mod v4; pub mod lts { - pub use super::v3::*; + pub use super::v4::*; } pub mod latest { - pub use super::v3::*; + pub use super::v4::*; } mod double_encoded; @@ -79,6 +80,8 @@ macro_rules! versioned_type { ($(#[$attr:meta])* pub enum $n:ident { $(#[$index3:meta])+ V3($v3:ty), + $(#[$index4:meta])+ + V4($v4:ty), }) => { #[derive(Derivative, Encode, Decode, TypeInfo)] #[derivative( @@ -89,11 +92,12 @@ macro_rules! versioned_type { )] #[codec(encode_bound())] #[codec(decode_bound())] - #[scale_info(replace_segment("staging_xcm", "xcm"))] $(#[$attr])* pub enum $n { $(#[$index3])* V3($v3), + $(#[$index4])* + V4($v4), } impl $n { pub fn try_as(&self) -> Result<&T, ()> where Self: TryAs { @@ -104,6 +108,15 @@ macro_rules! versioned_type { fn try_as(&self) -> Result<&$v3, ()> { match &self { Self::V3(ref x) => Ok(x), + _ => Err(()), + } + } + } + impl TryAs<$v4> for $n { + fn try_as(&self) -> Result<&$v4, ()> { + match &self { + Self::V4(ref x) => Ok(x), + _ => Err(()), } } } @@ -111,21 +124,38 @@ macro_rules! versioned_type { fn into_version(self, n: Version) -> Result { Ok(match n { 3 => Self::V3(self.try_into()?), + 4 => Self::V4(self.try_into()?), _ => return Err(()), }) } } - impl> From for $n { - fn from(x: T) -> Self { + impl From<$v3> for $n { + fn from(x: $v3) -> Self { $n::V3(x.into()) } } + impl> From for $n { + fn from(x: T) -> Self { + $n::V4(x.into()) + } + } impl TryFrom<$n> for $v3 { type Error = (); fn try_from(x: $n) -> Result { use $n::*; match x { V3(x) => Ok(x), + V4(x) => x.try_into(), + } + } + } + impl TryFrom<$n> for $v4 { + type Error = (); + fn try_from(x: $n) -> Result { + use $n::*; + match x { + V3(x) => x.try_into().map_err(|_| ()), + V4(x) => Ok(x), } } } @@ -141,6 +171,8 @@ macro_rules! versioned_type { V2($v2:ty), $(#[$index3:meta])+ V3($v3:ty), + $(#[$index4:meta])+ + V4($v4:ty), }) => { #[derive(Derivative, Encode, Decode, TypeInfo)] #[derivative( @@ -158,6 +190,8 @@ macro_rules! versioned_type { V2($v2), $(#[$index3])* V3($v3), + $(#[$index4])* + V4($v4), } impl $n { pub fn try_as(&self) -> Result<&T, ()> where Self: TryAs { @@ -180,11 +214,20 @@ macro_rules! versioned_type { } } } + impl TryAs<$v4> for $n { + fn try_as(&self) -> Result<&$v4, ()> { + match &self { + Self::V4(ref x) => Ok(x), + _ => Err(()), + } + } + } impl IntoVersion for $n { fn into_version(self, n: Version) -> Result { Ok(match n { 1 | 2 => Self::V2(self.try_into()?), 3 => Self::V3(self.try_into()?), + 4 => Self::V4(self.try_into()?), _ => return Err(()), }) } @@ -194,9 +237,9 @@ macro_rules! versioned_type { $n::V2(x) } } - impl> From for $n { + impl> From for $n { fn from(x: T) -> Self { - $n::V3(x.into()) + $n::V4(x.into()) } } impl TryFrom<$n> for $v2 { @@ -206,6 +249,10 @@ macro_rules! versioned_type { match x { V2(x) => Ok(x), V3(x) => x.try_into(), + V4(x) => { + let v3: $v3 = x.try_into().map_err(|_| ())?; + v3.try_into() + }, } } } @@ -216,6 +263,21 @@ macro_rules! versioned_type { match x { V2(x) => x.try_into(), V3(x) => Ok(x), + V4(x) => x.try_into().map_err(|_| ()), + } + } + } + impl TryFrom<$n> for $v4 { + type Error = (); + fn try_from(x: $n) -> Result { + use $n::*; + match x { + V2(x) => { + let v3: $v3 = x.try_into().map_err(|_| ())?; + v3.try_into().map_err(|_| ()) + }, + V3(x) => x.try_into().map_err(|_| ()), + V4(x) => Ok(x), } } } @@ -228,10 +290,12 @@ macro_rules! versioned_type { } versioned_type! { - /// A single version's `Response` value, together with its version code. + /// A single version's `AssetId` value, together with its version code. pub enum VersionedAssetId { #[codec(index = 3)] V3(v3::AssetId), + #[codec(index = 4)] + V4(v4::AssetId), } } @@ -242,6 +306,8 @@ versioned_type! { V2(v2::Response), #[codec(index = 3)] V3(v3::Response), + #[codec(index = 4)] + V4(v4::Response), } } @@ -252,6 +318,8 @@ versioned_type! { V2(v2::NetworkId), #[codec(index = 3)] V3(v3::NetworkId), + #[codec(index = 4)] + V4(v4::NetworkId), } } @@ -262,50 +330,72 @@ versioned_type! { V2(v2::Junction), #[codec(index = 3)] V3(v3::Junction), + #[codec(index = 4)] + V4(v4::Junction), } } versioned_type! { - /// A single `MultiLocation` value, together with its version code. + /// A single `Location` value, together with its version code. #[derive(Ord, PartialOrd)] - pub enum VersionedMultiLocation { + pub enum VersionedLocation { #[codec(index = 1)] // v2 is same as v1 and therefore re-using the v1 index V2(v2::MultiLocation), #[codec(index = 3)] V3(v3::MultiLocation), + #[codec(index = 4)] + V4(v4::Location), } } +#[deprecated(note = "Use `VersionedLocation` instead")] +pub type VersionedMultiLocation = VersionedLocation; + versioned_type! { - /// A single `InteriorMultiLocation` value, together with its version code. - pub enum VersionedInteriorMultiLocation { - #[codec(index = 2)] // while this is same as v1::Junctions, VersionedInteriorMultiLocation is introduced in v3 + /// A single `InteriorLocation` value, together with its version code. + pub enum VersionedInteriorLocation { + #[codec(index = 2)] // while this is same as v1::Junctions, VersionedInteriorLocation is introduced in v3 V2(v2::InteriorMultiLocation), #[codec(index = 3)] V3(v3::InteriorMultiLocation), + #[codec(index = 4)] + V4(v4::InteriorLocation), } } +#[deprecated(note = "Use `VersionedInteriorLocation` instead")] +pub type VersionedInteriorMultiLocation = VersionedInteriorLocation; + versioned_type! { - /// A single `MultiAsset` value, together with its version code. - pub enum VersionedMultiAsset { + /// A single `Asset` value, together with its version code. + pub enum VersionedAsset { #[codec(index = 1)] // v2 is same as v1 and therefore re-using the v1 index V2(v2::MultiAsset), #[codec(index = 3)] V3(v3::MultiAsset), + #[codec(index = 4)] + V4(v4::Asset), } } +#[deprecated(note = "Use `VersionedAsset` instead")] +pub type VersionedMultiAsset = VersionedAsset; + versioned_type! { /// A single `MultiAssets` value, together with its version code. - pub enum VersionedMultiAssets { + pub enum VersionedAssets { #[codec(index = 1)] // v2 is same as v1 and therefore re-using the v1 index V2(v2::MultiAssets), #[codec(index = 3)] V3(v3::MultiAssets), + #[codec(index = 4)] + V4(v4::Assets), } } +#[deprecated(note = "Use `VersionedAssets` instead")] +pub type VersionedMultiAssets = VersionedAssets; + /// A single XCM message, together with its version code. #[derive(Derivative, Encode, Decode, TypeInfo)] #[derivative(Clone(bound = ""), Eq(bound = ""), PartialEq(bound = ""), Debug(bound = ""))] @@ -318,6 +408,8 @@ pub enum VersionedXcm { V2(v2::Xcm), #[codec(index = 3)] V3(v3::Xcm), + #[codec(index = 4)] + V4(v4::Xcm), } impl IntoVersion for VersionedXcm { @@ -325,6 +417,7 @@ impl IntoVersion for VersionedXcm { Ok(match n { 2 => Self::V2(self.try_into()?), 3 => Self::V3(self.try_into()?), + 4 => Self::V4(self.try_into()?), _ => return Err(()), }) } @@ -342,6 +435,12 @@ impl From> for VersionedXcm { } } +impl From> for VersionedXcm { + fn from(x: v4::Xcm) -> Self { + VersionedXcm::V4(x) + } +} + impl TryFrom> for v2::Xcm { type Error = (); fn try_from(x: VersionedXcm) -> Result { @@ -349,6 +448,10 @@ impl TryFrom> for v2::Xcm { match x { V2(x) => Ok(x), V3(x) => x.try_into(), + V4(x) => { + let v3: v3::Xcm = x.try_into()?; + v3.try_into() + }, } } } @@ -360,15 +463,31 @@ impl TryFrom> for v3::Xcm { match x { V2(x) => x.try_into(), V3(x) => Ok(x), + V4(x) => x.try_into(), + } + } +} + +impl TryFrom> for v4::Xcm { + type Error = (); + fn try_from(x: VersionedXcm) -> Result { + use VersionedXcm::*; + match x { + V2(x) => { + let v3: v3::Xcm = x.try_into()?; + v3.try_into() + }, + V3(x) => x.try_into(), + V4(x) => Ok(x), } } } -/// Convert an `Xcm` datum into a `VersionedXcm`, based on a destination `MultiLocation` which will +/// Convert an `Xcm` datum into a `VersionedXcm`, based on a destination `Location` which will /// interpret it. pub trait WrapVersion { fn wrap_version( - dest: &latest::MultiLocation, + dest: &latest::Location, xcm: impl Into>, ) -> Result, ()>; } @@ -377,7 +496,7 @@ pub trait WrapVersion { /// authored as. impl WrapVersion for () { fn wrap_version( - _: &latest::MultiLocation, + _: &latest::Location, xcm: impl Into>, ) -> Result, ()> { Ok(xcm.into()) @@ -389,7 +508,7 @@ impl WrapVersion for () { pub struct AlwaysV2; impl WrapVersion for AlwaysV2 { fn wrap_version( - _: &latest::MultiLocation, + _: &latest::Location, xcm: impl Into>, ) -> Result, ()> { Ok(VersionedXcm::::V2(xcm.into().try_into()?)) @@ -401,27 +520,38 @@ impl WrapVersion for AlwaysV2 { pub struct AlwaysV3; impl WrapVersion for AlwaysV3 { fn wrap_version( - _: &latest::MultiLocation, + _: &latest::Location, xcm: impl Into>, ) -> Result, ()> { Ok(VersionedXcm::::V3(xcm.into().try_into()?)) } } +/// `WrapVersion` implementation which attempts to always convert the XCM to version 3 before +/// wrapping it. +pub struct AlwaysV4; +impl WrapVersion for AlwaysV4 { + fn wrap_version( + _: &latest::Location, + xcm: impl Into>, + ) -> Result, ()> { + Ok(VersionedXcm::::V4(xcm.into().try_into()?)) + } +} + /// `WrapVersion` implementation which attempts to always convert the XCM to the latest version /// before wrapping it. -pub type AlwaysLatest = AlwaysV3; +pub type AlwaysLatest = AlwaysV4; /// `WrapVersion` implementation which attempts to always convert the XCM to the most recent Long- /// Term-Support version before wrapping it. -pub type AlwaysLts = AlwaysV3; +pub type AlwaysLts = AlwaysV4; pub mod prelude { pub use super::{ - latest::prelude::*, AlwaysLatest, AlwaysLts, AlwaysV2, AlwaysV3, IntoVersion, Unsupported, - Version as XcmVersion, VersionedAssetId, VersionedInteriorMultiLocation, - VersionedMultiAsset, VersionedMultiAssets, VersionedMultiLocation, VersionedResponse, - VersionedXcm, WrapVersion, + latest::prelude::*, AlwaysLatest, AlwaysLts, AlwaysV2, AlwaysV3, AlwaysV4, IntoVersion, + Unsupported, Version as XcmVersion, VersionedAsset, VersionedAssetId, VersionedAssets, + VersionedInteriorLocation, VersionedLocation, VersionedResponse, VersionedXcm, WrapVersion, }; } @@ -438,13 +568,19 @@ pub mod opaque { // Then override with the opaque types in v3 pub use crate::v3::opaque::{Instruction, Xcm}; } + pub mod v4 { + // Everything from v4 + pub use crate::v4::*; + // Then override with the opaque types in v4 + pub use crate::v4::opaque::{Instruction, Xcm}; + } pub mod latest { - pub use super::v3::*; + pub use super::v4::*; } pub mod lts { - pub use super::v3::*; + pub use super::v4::*; } /// The basic `VersionedXcm` type which just uses the `Vec` as an encoded call. @@ -454,5 +590,56 @@ pub mod opaque { #[test] fn conversion_works() { use latest::prelude::*; - let _: VersionedMultiAssets = (Here, 1u128).into(); + let assets: Assets = (Here, 1u128).into(); + let _: VersionedAssets = assets.into(); +} + +#[test] +fn size_limits() { + extern crate std; + + let mut test_failed = false; + macro_rules! check_sizes { + ($(($kind:ty, $expected:expr),)+) => { + $({ + let s = core::mem::size_of::<$kind>(); + // Since the types often affect the size of other types in which they're included + // it is more convenient to check multiple types at the same time and only fail + // the test at the end. For debugging it's also useful to print out all of the sizes, + // even if they're within the expected range. + if s > $expected { + test_failed = true; + std::eprintln!( + "assertion failed: size of '{}' is {} (which is more than the expected {})", + stringify!($kind), + s, + $expected + ); + } else { + std::println!( + "type '{}' is of size {} which is within the expected {}", + stringify!($kind), + s, + $expected + ); + } + })+ + } + } + + check_sizes! { + (crate::latest::Instruction<()>, 112), + (crate::latest::Asset, 80), + (crate::latest::Location, 24), + (crate::latest::AssetId, 40), + (crate::latest::Junctions, 16), + (crate::latest::Junction, 88), + (crate::latest::Response, 40), + (crate::latest::AssetInstance, 40), + (crate::latest::NetworkId, 48), + (crate::latest::BodyId, 32), + (crate::latest::Assets, 24), + (crate::latest::BodyPart, 12), + } + assert!(!test_failed); } diff --git a/polkadot/xcm/src/tests.rs b/polkadot/xcm/src/tests.rs index a3a60f6477c7..135229ff23d0 100644 --- a/polkadot/xcm/src/tests.rs +++ b/polkadot/xcm/src/tests.rs @@ -59,79 +59,79 @@ fn encode_decode_versioned_response_v3() { #[test] fn encode_decode_versioned_multi_location_v2() { - let location = VersionedMultiLocation::V2(v2::MultiLocation::new(0, v2::Junctions::Here)); + let location = VersionedLocation::V2(v2::MultiLocation::new(0, v2::Junctions::Here)); let encoded = location.encode(); assert_eq!(encoded, hex_literal::hex!("010000"), "encode format changed"); assert_eq!(encoded[0], 1, "bad version number"); // this is introduced in v1 - let decoded = VersionedMultiLocation::decode(&mut &encoded[..]).unwrap(); + let decoded = VersionedLocation::decode(&mut &encoded[..]).unwrap(); assert_eq!(location, decoded); } #[test] fn encode_decode_versioned_multi_location_v3() { - let location = VersionedMultiLocation::V3(v3::MultiLocation::new(0, v3::Junctions::Here)); + let location = VersionedLocation::V3(v3::MultiLocation::new(0, v3::Junctions::Here)); let encoded = location.encode(); assert_eq!(encoded, hex_literal::hex!("030000"), "encode format changed"); assert_eq!(encoded[0], 3, "bad version number"); - let decoded = VersionedMultiLocation::decode(&mut &encoded[..]).unwrap(); + let decoded = VersionedLocation::decode(&mut &encoded[..]).unwrap(); assert_eq!(location, decoded); } #[test] fn encode_decode_versioned_interior_multi_location_v2() { - let location = VersionedInteriorMultiLocation::V2(v2::InteriorMultiLocation::Here); + let location = VersionedInteriorLocation::V2(v2::InteriorMultiLocation::Here); let encoded = location.encode(); assert_eq!(encoded, hex_literal::hex!("0200"), "encode format changed"); assert_eq!(encoded[0], 2, "bad version number"); - let decoded = VersionedInteriorMultiLocation::decode(&mut &encoded[..]).unwrap(); + let decoded = VersionedInteriorLocation::decode(&mut &encoded[..]).unwrap(); assert_eq!(location, decoded); } #[test] fn encode_decode_versioned_interior_multi_location_v3() { - let location = VersionedInteriorMultiLocation::V3(v3::InteriorMultiLocation::Here); + let location = VersionedInteriorLocation::V3(v3::InteriorMultiLocation::Here); let encoded = location.encode(); assert_eq!(encoded, hex_literal::hex!("0300"), "encode format changed"); assert_eq!(encoded[0], 3, "bad version number"); - let decoded = VersionedInteriorMultiLocation::decode(&mut &encoded[..]).unwrap(); + let decoded = VersionedInteriorLocation::decode(&mut &encoded[..]).unwrap(); assert_eq!(location, decoded); } #[test] fn encode_decode_versioned_multi_asset_v2() { - let asset = VersionedMultiAsset::V2(v2::MultiAsset::from(((0, v2::Junctions::Here), 1))); + let asset = VersionedAsset::V2(v2::MultiAsset::from(((0, v2::Junctions::Here), 1))); let encoded = asset.encode(); assert_eq!(encoded, hex_literal::hex!("010000000004"), "encode format changed"); assert_eq!(encoded[0], 1, "bad version number"); - let decoded = VersionedMultiAsset::decode(&mut &encoded[..]).unwrap(); + let decoded = VersionedAsset::decode(&mut &encoded[..]).unwrap(); assert_eq!(asset, decoded); } #[test] fn encode_decode_versioned_multi_asset_v3() { - let asset = VersionedMultiAsset::V3(v3::MultiAsset::from((v3::MultiLocation::default(), 1))); + let asset = VersionedAsset::V3(v3::MultiAsset::from((v3::MultiLocation::default(), 1))); let encoded = asset.encode(); assert_eq!(encoded, hex_literal::hex!("030000000004"), "encode format changed"); assert_eq!(encoded[0], 3, "bad version number"); - let decoded = VersionedMultiAsset::decode(&mut &encoded[..]).unwrap(); + let decoded = VersionedAsset::decode(&mut &encoded[..]).unwrap(); assert_eq!(asset, decoded); } #[test] fn encode_decode_versioned_multi_assets_v2() { - let assets = VersionedMultiAssets::V2(v2::MultiAssets::from(vec![v2::MultiAsset::from(( + let assets = VersionedAssets::V2(v2::MultiAssets::from(vec![v2::MultiAsset::from(( (0, v2::Junctions::Here), 1, ))])); @@ -140,13 +140,13 @@ fn encode_decode_versioned_multi_assets_v2() { assert_eq!(encoded, hex_literal::hex!("01040000000004"), "encode format changed"); assert_eq!(encoded[0], 1, "bad version number"); - let decoded = VersionedMultiAssets::decode(&mut &encoded[..]).unwrap(); + let decoded = VersionedAssets::decode(&mut &encoded[..]).unwrap(); assert_eq!(assets, decoded); } #[test] fn encode_decode_versioned_multi_assets_v3() { - let assets = VersionedMultiAssets::V3(v3::MultiAssets::from(vec![ + let assets = VersionedAssets::V3(v3::MultiAssets::from(vec![ (v3::MultiAsset::from((v3::MultiLocation::default(), 1))), ])); let encoded = assets.encode(); @@ -154,7 +154,7 @@ fn encode_decode_versioned_multi_assets_v3() { assert_eq!(encoded, hex_literal::hex!("03040000000004"), "encode format changed"); assert_eq!(encoded[0], 3, "bad version number"); - let decoded = VersionedMultiAssets::decode(&mut &encoded[..]).unwrap(); + let decoded = VersionedAssets::decode(&mut &encoded[..]).unwrap(); assert_eq!(assets, decoded); } diff --git a/polkadot/xcm/src/v2/multilocation.rs b/polkadot/xcm/src/v2/multilocation.rs index 81b67eee9744..60aa1f6ceadf 100644 --- a/polkadot/xcm/src/v2/multilocation.rs +++ b/polkadot/xcm/src/v2/multilocation.rs @@ -75,8 +75,8 @@ impl MultiLocation { MultiLocation { parents, interior: junctions } } - /// Consume `self` and return the equivalent `VersionedMultiLocation` value. - pub fn versioned(self) -> crate::VersionedMultiLocation { + /// Consume `self` and return the equivalent `VersionedLocation` value. + pub fn versioned(self) -> crate::VersionedLocation { self.into() } @@ -240,9 +240,9 @@ impl MultiLocation { /// # Example /// ```rust /// # use staging_xcm::v2::{Junctions::*, Junction::*, MultiLocation}; - /// let mut m = MultiLocation::new(1, X2(PalletInstance(3), OnlyChild)); + /// let mut m = MultiLocation::new(1, [PalletInstance(3), OnlyChild].into()); /// assert_eq!( - /// m.match_and_split(&MultiLocation::new(1, X1(PalletInstance(3)))), + /// m.match_and_split(&MultiLocation::new(1, [PalletInstance(3)].into())), /// Some(&OnlyChild), /// ); /// assert_eq!(m.match_and_split(&MultiLocation::new(1, Here)), None); @@ -260,10 +260,10 @@ impl MultiLocation { /// # Example /// ```rust /// # use staging_xcm::v2::{Junctions::*, Junction::*, MultiLocation}; - /// let m = MultiLocation::new(1, X3(PalletInstance(3), OnlyChild, OnlyChild)); - /// assert!(m.starts_with(&MultiLocation::new(1, X1(PalletInstance(3))))); - /// assert!(!m.starts_with(&MultiLocation::new(1, X1(GeneralIndex(99))))); - /// assert!(!m.starts_with(&MultiLocation::new(0, X1(PalletInstance(3))))); + /// let m = MultiLocation::new(1, [PalletInstance(3), OnlyChild, OnlyChild].into()); + /// assert!(m.starts_with(&MultiLocation::new(1, [PalletInstance(3)].into()))); + /// assert!(!m.starts_with(&MultiLocation::new(1, [GeneralIndex(99)].into()))); + /// assert!(!m.starts_with(&MultiLocation::new(0, [PalletInstance(3)].into()))); /// ``` pub fn starts_with(&self, prefix: &MultiLocation) -> bool { if self.parents != prefix.parents { @@ -279,9 +279,9 @@ impl MultiLocation { /// # Example /// ```rust /// # use staging_xcm::v2::{Junctions::*, Junction::*, MultiLocation}; - /// let mut m = MultiLocation::new(1, X1(Parachain(21))); - /// assert_eq!(m.append_with(X1(PalletInstance(3))), Ok(())); - /// assert_eq!(m, MultiLocation::new(1, X2(Parachain(21), PalletInstance(3)))); + /// let mut m = MultiLocation::new(1, [Parachain(21)].into()); + /// assert_eq!(m.append_with([PalletInstance(3)].into()), Ok(())); + /// assert_eq!(m, MultiLocation::new(1, [Parachain(21), PalletInstance(3)].into())); /// ``` pub fn append_with(&mut self, suffix: Junctions) -> Result<(), Junctions> { if self.interior.len().saturating_add(suffix.len()) > MAX_JUNCTIONS { @@ -300,9 +300,9 @@ impl MultiLocation { /// # Example /// ```rust /// # use staging_xcm::v2::{Junctions::*, Junction::*, MultiLocation}; - /// let mut m = MultiLocation::new(2, X1(PalletInstance(3))); - /// assert_eq!(m.prepend_with(MultiLocation::new(1, X2(Parachain(21), OnlyChild))), Ok(())); - /// assert_eq!(m, MultiLocation::new(1, X1(PalletInstance(3)))); + /// let mut m = MultiLocation::new(2, [PalletInstance(3)].into()); + /// assert_eq!(m.prepend_with(MultiLocation::new(1, [Parachain(21), OnlyChild].into())), Ok(())); + /// assert_eq!(m, MultiLocation::new(1, [PalletInstance(3)].into())); /// ``` pub fn prepend_with(&mut self, mut prefix: MultiLocation) -> Result<(), MultiLocation> { // prefix self (suffix) @@ -455,6 +455,7 @@ impl> From> for MultiLocation { } xcm_procedural::impl_conversion_functions_for_multilocation_v2!(); +xcm_procedural::impl_conversion_functions_for_junctions_v2!(); /// Maximum number of `Junction`s that a `Junctions` can contain. const MAX_JUNCTIONS: usize = 8; diff --git a/polkadot/xcm/src/v2/traits.rs b/polkadot/xcm/src/v2/traits.rs index 6453f91a1f1e..9cfb9b051ab2 100644 --- a/polkadot/xcm/src/v2/traits.rs +++ b/polkadot/xcm/src/v2/traits.rs @@ -292,11 +292,12 @@ pub type SendResult = result::Result<(), SendError>; /// } /// } /// -/// /// A sender that accepts a message that has an X2 junction, otherwise stops the routing. +/// /// A sender that accepts a message that has two junctions, otherwise stops the routing. /// struct Sender2; /// impl SendXcm for Sender2 { /// fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { -/// if let MultiLocation { parents: 0, interior: X2(j1, j2) } = destination.into() { +/// let destination = destination.into(); +/// if destination.parents == 0 && destination.interior.len() == 2 { /// Ok(()) /// } else { /// Err(SendError::Unroutable) diff --git a/polkadot/xcm/src/v3/junction.rs b/polkadot/xcm/src/v3/junction.rs index 47429a8c36e9..eae00c716d60 100644 --- a/polkadot/xcm/src/v3/junction.rs +++ b/polkadot/xcm/src/v3/junction.rs @@ -22,7 +22,8 @@ use crate::{ BodyId as OldBodyId, BodyPart as OldBodyPart, Junction as OldJunction, NetworkId as OldNetworkId, }, - VersionedMultiLocation, + v4::{Junction as NewJunction, NetworkId as NewNetworkId}, + VersionedLocation, }; use bounded_collections::{BoundedSlice, BoundedVec, ConstU32}; use core::convert::{TryFrom, TryInto}; @@ -101,6 +102,30 @@ impl TryFrom for NetworkId { } } +impl From for Option { + fn from(new: NewNetworkId) -> Self { + Some(NetworkId::from(new)) + } +} + +impl From for NetworkId { + fn from(new: NewNetworkId) -> Self { + use NewNetworkId::*; + match new { + ByGenesis(hash) => Self::ByGenesis(hash), + ByFork { block_number, block_hash } => Self::ByFork { block_number, block_hash }, + Polkadot => Self::Polkadot, + Kusama => Self::Kusama, + Westend => Self::Westend, + Rococo => Self::Rococo, + Wococo => Self::Wococo, + Ethereum { chain_id } => Self::Ethereum { chain_id }, + BitcoinCore => Self::BitcoinCore, + BitcoinCash => Self::BitcoinCash, + } + } +} + /// An identifier of a pluralistic body. #[derive( Copy, @@ -408,6 +433,29 @@ impl TryFrom for Junction { } } +impl TryFrom for Junction { + type Error = (); + + fn try_from(value: NewJunction) -> Result { + use NewJunction::*; + Ok(match value { + Parachain(id) => Self::Parachain(id), + AccountId32 { network: maybe_network, id } => + Self::AccountId32 { network: maybe_network.map(|network| network.into()), id }, + AccountIndex64 { network: maybe_network, index } => + Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index }, + AccountKey20 { network: maybe_network, key } => + Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key }, + PalletInstance(index) => Self::PalletInstance(index), + GeneralIndex(id) => Self::GeneralIndex(id), + GeneralKey { length, data } => Self::GeneralKey { length, data }, + OnlyChild => Self::OnlyChild, + Plurality { id, part } => Self::Plurality { id, part }, + GlobalConsensus(network) => Self::GlobalConsensus(network.into()), + }) + } +} + impl Junction { /// Convert `self` into a `MultiLocation` containing 0 parents. /// @@ -424,10 +472,10 @@ impl Junction { MultiLocation { parents: n, interior: Junctions::X1(self) } } - /// Convert `self` into a `VersionedMultiLocation` containing 0 parents. + /// Convert `self` into a `VersionedLocation` containing 0 parents. /// /// Similar to `Into::into`, except that this method can be used in a const evaluation context. - pub const fn into_versioned(self) -> VersionedMultiLocation { + pub const fn into_versioned(self) -> VersionedLocation { self.into_location().into_versioned() } diff --git a/polkadot/xcm/src/v3/junctions.rs b/polkadot/xcm/src/v3/junctions.rs index d1cbc2dbed42..b90c9fdecd82 100644 --- a/polkadot/xcm/src/v3/junctions.rs +++ b/polkadot/xcm/src/v3/junctions.rs @@ -66,6 +66,27 @@ pub enum Junctions { X8(Junction, Junction, Junction, Junction, Junction, Junction, Junction, Junction), } +macro_rules! impl_junction { + ($count:expr, $variant:ident, ($($index:literal),+)) => { + /// Additional helper for building junctions + /// Useful for converting to future XCM versions + impl From<[Junction; $count]> for Junctions { + fn from(junctions: [Junction; $count]) -> Self { + Self::$variant($(junctions[$index]),*) + } + } + }; +} + +impl_junction!(1, X1, (0)); +impl_junction!(2, X2, (0, 1)); +impl_junction!(3, X3, (0, 1, 2)); +impl_junction!(4, X4, (0, 1, 2, 3)); +impl_junction!(5, X5, (0, 1, 2, 3, 4)); +impl_junction!(6, X6, (0, 1, 2, 3, 4, 5)); +impl_junction!(7, X7, (0, 1, 2, 3, 4, 5, 6)); +impl_junction!(8, X8, (0, 1, 2, 3, 4, 5, 6, 7)); + pub struct JunctionsIterator(Junctions); impl Iterator for JunctionsIterator { type Item = Junction; diff --git a/polkadot/xcm/src/v3/mod.rs b/polkadot/xcm/src/v3/mod.rs index 4217528f2273..f03ea721a5de 100644 --- a/polkadot/xcm/src/v3/mod.rs +++ b/polkadot/xcm/src/v3/mod.rs @@ -16,9 +16,15 @@ //! Version 3 of the Cross-Consensus Message format data structures. -use super::v2::{ - Instruction as OldInstruction, Response as OldResponse, WeightLimit as OldWeightLimit, - Xcm as OldXcm, +use super::{ + v2::{ + Instruction as OldInstruction, Response as OldResponse, WeightLimit as OldWeightLimit, + Xcm as OldXcm, + }, + v4::{ + Instruction as NewInstruction, PalletInfo as NewPalletInfo, + QueryResponseInfo as NewQueryResponseInfo, Response as NewResponse, Xcm as NewXcm, + }, }; use crate::DoubleEncoded; use alloc::{vec, vec::Vec}; @@ -48,7 +54,7 @@ pub use multiasset::{ WildFungibility, WildMultiAsset, MAX_ITEMS_IN_MULTIASSETS, }; pub use multilocation::{ - Ancestor, AncestorThen, InteriorMultiLocation, MultiLocation, Parent, ParentThen, + Ancestor, AncestorThen, InteriorMultiLocation, Location, MultiLocation, Parent, ParentThen, }; pub use traits::{ send_xcm, validate_send, Error, ExecuteXcm, Outcome, PreparedMessage, Result, SendError, @@ -270,6 +276,22 @@ impl PalletInfo { } } +impl TryInto for PalletInfo { + type Error = (); + + fn try_into(self) -> result::Result { + NewPalletInfo::new( + self.index, + self.name.into_inner(), + self.module_name.into_inner(), + self.major, + self.minor, + self.patch, + ) + .map_err(|_| ()) + } +} + #[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub enum MaybeErrorCode { @@ -317,6 +339,32 @@ impl Default for Response { } } +impl TryFrom for Response { + type Error = (); + + fn try_from(new: NewResponse) -> result::Result { + use NewResponse::*; + Ok(match new { + Null => Self::Null, + Assets(assets) => Self::Assets(assets.try_into()?), + ExecutionResult(result) => + Self::ExecutionResult(result.map(|(num, old_error)| (num, old_error.into()))), + Version(version) => Self::Version(version), + PalletsInfo(pallet_info) => { + let inner = pallet_info + .into_iter() + .map(TryInto::try_into) + .collect::, _>>()?; + Self::PalletsInfo( + BoundedVec::::try_from(inner).map_err(|_| ())?, + ) + }, + DispatchResult(maybe_error) => + Self::DispatchResult(maybe_error.try_into().map_err(|_| ())?), + }) + } +} + /// Information regarding the composition of a query response. #[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)] #[scale_info(replace_segment("staging_xcm", "xcm"))] @@ -330,6 +378,18 @@ pub struct QueryResponseInfo { pub max_weight: Weight, } +impl TryFrom for QueryResponseInfo { + type Error = (); + + fn try_from(new: NewQueryResponseInfo) -> result::Result { + Ok(Self { + destination: new.destination.try_into()?, + query_id: new.query_id, + max_weight: new.max_weight, + }) + } +} + /// An optional weight limit. #[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)] #[scale_info(replace_segment("staging_xcm", "xcm"))] @@ -358,13 +418,12 @@ impl From for Option { } } -impl TryFrom for WeightLimit { - type Error = (); - fn try_from(x: OldWeightLimit) -> result::Result { +impl From for WeightLimit { + fn from(x: OldWeightLimit) -> Self { use OldWeightLimit::*; match x { - Limited(w) => Ok(Self::Limited(Weight::from_parts(w, DEFAULT_PROOF_SIZE))), - Unlimited => Ok(Self::Unlimited), + Limited(w) => Self::Limited(Weight::from_parts(w, DEFAULT_PROOF_SIZE)), + Unlimited => Self::Unlimited, } } } @@ -1249,6 +1308,155 @@ impl TryFrom> for Xcm { } } +// Convert from a v4 XCM to a v3 XCM. +impl TryFrom> for Xcm { + type Error = (); + fn try_from(new_xcm: NewXcm) -> result::Result { + Ok(Xcm(new_xcm.0.into_iter().map(TryInto::try_into).collect::>()?)) + } +} + +// Convert from a v4 instruction to a v3 instruction. +impl TryFrom> for Instruction { + type Error = (); + fn try_from(new_instruction: NewInstruction) -> result::Result { + use NewInstruction::*; + Ok(match new_instruction { + WithdrawAsset(assets) => Self::WithdrawAsset(assets.try_into()?), + ReserveAssetDeposited(assets) => Self::ReserveAssetDeposited(assets.try_into()?), + ReceiveTeleportedAsset(assets) => Self::ReceiveTeleportedAsset(assets.try_into()?), + QueryResponse { query_id, response, max_weight, querier: Some(querier) } => + Self::QueryResponse { + query_id, + querier: querier.try_into()?, + response: response.try_into()?, + max_weight, + }, + QueryResponse { query_id, response, max_weight, querier: None } => + Self::QueryResponse { + query_id, + querier: None, + response: response.try_into()?, + max_weight, + }, + TransferAsset { assets, beneficiary } => Self::TransferAsset { + assets: assets.try_into()?, + beneficiary: beneficiary.try_into()?, + }, + TransferReserveAsset { assets, dest, xcm } => Self::TransferReserveAsset { + assets: assets.try_into()?, + dest: dest.try_into()?, + xcm: xcm.try_into()?, + }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => + Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, + HrmpChannelAccepted { recipient } => Self::HrmpChannelAccepted { recipient }, + HrmpChannelClosing { initiator, sender, recipient } => + Self::HrmpChannelClosing { initiator, sender, recipient }, + Transact { origin_kind, require_weight_at_most, call } => + Self::Transact { origin_kind, require_weight_at_most, call: call.into() }, + ReportError(response_info) => Self::ReportError(QueryResponseInfo { + query_id: response_info.query_id, + destination: response_info.destination.try_into().map_err(|_| ())?, + max_weight: response_info.max_weight, + }), + DepositAsset { assets, beneficiary } => { + let beneficiary = beneficiary.try_into()?; + let assets = assets.try_into()?; + Self::DepositAsset { assets, beneficiary } + }, + DepositReserveAsset { assets, dest, xcm } => { + let dest = dest.try_into()?; + let xcm = xcm.try_into()?; + let assets = assets.try_into()?; + Self::DepositReserveAsset { assets, dest, xcm } + }, + ExchangeAsset { give, want, maximal } => { + let give = give.try_into()?; + let want = want.try_into()?; + Self::ExchangeAsset { give, want, maximal } + }, + InitiateReserveWithdraw { assets, reserve, xcm } => { + // No `max_assets` here, so if there's a connt, then we cannot translate. + let assets = assets.try_into()?; + let reserve = reserve.try_into()?; + let xcm = xcm.try_into()?; + Self::InitiateReserveWithdraw { assets, reserve, xcm } + }, + InitiateTeleport { assets, dest, xcm } => { + // No `max_assets` here, so if there's a connt, then we cannot translate. + let assets = assets.try_into()?; + let dest = dest.try_into()?; + let xcm = xcm.try_into()?; + Self::InitiateTeleport { assets, dest, xcm } + }, + ReportHolding { response_info, assets } => { + let response_info = QueryResponseInfo { + destination: response_info.destination.try_into().map_err(|_| ())?, + query_id: response_info.query_id, + max_weight: response_info.max_weight, + }; + Self::ReportHolding { response_info, assets: assets.try_into()? } + }, + BuyExecution { fees, weight_limit } => { + let fees = fees.try_into()?; + let weight_limit = weight_limit.into(); + Self::BuyExecution { fees, weight_limit } + }, + ClearOrigin => Self::ClearOrigin, + DescendOrigin(who) => Self::DescendOrigin(who.try_into()?), + RefundSurplus => Self::RefundSurplus, + SetErrorHandler(xcm) => Self::SetErrorHandler(xcm.try_into()?), + SetAppendix(xcm) => Self::SetAppendix(xcm.try_into()?), + ClearError => Self::ClearError, + ClaimAsset { assets, ticket } => { + let assets = assets.try_into()?; + let ticket = ticket.try_into()?; + Self::ClaimAsset { assets, ticket } + }, + Trap(code) => Self::Trap(code), + SubscribeVersion { query_id, max_response_weight } => + Self::SubscribeVersion { query_id, max_response_weight }, + UnsubscribeVersion => Self::UnsubscribeVersion, + BurnAsset(assets) => Self::BurnAsset(assets.try_into()?), + ExpectAsset(assets) => Self::ExpectAsset(assets.try_into()?), + ExpectOrigin(maybe_origin) => + Self::ExpectOrigin(maybe_origin.map(|origin| origin.try_into()).transpose()?), + ExpectError(maybe_error) => Self::ExpectError(maybe_error), + ExpectTransactStatus(maybe_error_code) => Self::ExpectTransactStatus(maybe_error_code), + QueryPallet { module_name, response_info } => + Self::QueryPallet { module_name, response_info: response_info.try_into()? }, + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => + Self::ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, + ReportTransactStatus(response_info) => + Self::ReportTransactStatus(response_info.try_into()?), + ClearTransactStatus => Self::ClearTransactStatus, + UniversalOrigin(junction) => Self::UniversalOrigin(junction.try_into()?), + ExportMessage { network, destination, xcm } => Self::ExportMessage { + network: network.into(), + destination: destination.try_into()?, + xcm: xcm.try_into()?, + }, + LockAsset { asset, unlocker } => + Self::LockAsset { asset: asset.try_into()?, unlocker: unlocker.try_into()? }, + UnlockAsset { asset, target } => + Self::UnlockAsset { asset: asset.try_into()?, target: target.try_into()? }, + NoteUnlockable { asset, owner } => + Self::NoteUnlockable { asset: asset.try_into()?, owner: owner.try_into()? }, + RequestUnlock { asset, locker } => + Self::RequestUnlock { asset: asset.try_into()?, locker: locker.try_into()? }, + SetFeesMode { jit_withdraw } => Self::SetFeesMode { jit_withdraw }, + SetTopic(topic) => Self::SetTopic(topic), + ClearTopic => Self::ClearTopic, + AliasOrigin(location) => Self::AliasOrigin(location.try_into()?), + UnpaidExecution { weight_limit, check_origin } => Self::UnpaidExecution { + weight_limit, + check_origin: check_origin.map(|origin| origin.try_into()).transpose()?, + }, + }) + } +} + /// Default value for the proof size weight component when converting from V2. Set at 64 KB. /// NOTE: Make sure this is removed after we properly account for PoV weights. const DEFAULT_PROOF_SIZE: u64 = 64 * 1024; @@ -1329,10 +1537,8 @@ impl TryFrom> for Instruction { }; Self::ReportHolding { response_info, assets: assets.try_into()? } }, - BuyExecution { fees, weight_limit } => Self::BuyExecution { - fees: fees.try_into()?, - weight_limit: weight_limit.try_into()?, - }, + BuyExecution { fees, weight_limit } => + Self::BuyExecution { fees: fees.try_into()?, weight_limit: weight_limit.into() }, ClearOrigin => Self::ClearOrigin, DescendOrigin(who) => Self::DescendOrigin(who.try_into()?), RefundSurplus => Self::RefundSurplus, diff --git a/polkadot/xcm/src/v3/multiasset.rs b/polkadot/xcm/src/v3/multiasset.rs index 454120a1a7b9..160f923157f8 100644 --- a/polkadot/xcm/src/v3/multiasset.rs +++ b/polkadot/xcm/src/v3/multiasset.rs @@ -27,11 +27,18 @@ //! filtering an XCM holding account. use super::{InteriorMultiLocation, MultiLocation}; -use crate::v2::{ - AssetId as OldAssetId, AssetInstance as OldAssetInstance, Fungibility as OldFungibility, - MultiAsset as OldMultiAsset, MultiAssetFilter as OldMultiAssetFilter, - MultiAssets as OldMultiAssets, WildFungibility as OldWildFungibility, - WildMultiAsset as OldWildMultiAsset, +use crate::{ + v2::{ + AssetId as OldAssetId, AssetInstance as OldAssetInstance, Fungibility as OldFungibility, + MultiAsset as OldMultiAsset, MultiAssetFilter as OldMultiAssetFilter, + MultiAssets as OldMultiAssets, WildFungibility as OldWildFungibility, + WildMultiAsset as OldWildMultiAsset, + }, + v4::{ + Asset as NewMultiAsset, AssetFilter as NewMultiAssetFilter, AssetId as NewAssetId, + AssetInstance as NewAssetInstance, Assets as NewMultiAssets, Fungibility as NewFungibility, + WildAsset as NewWildMultiAsset, WildFungibility as NewWildFungibility, + }, }; use alloc::{vec, vec::Vec}; use bounded_collections::{BoundedVec, ConstU32}; @@ -85,6 +92,21 @@ impl TryFrom for AssetInstance { } } +impl TryFrom for AssetInstance { + type Error = (); + fn try_from(value: NewAssetInstance) -> Result { + use NewAssetInstance::*; + Ok(match value { + Undefined => Self::Undefined, + Index(n) => Self::Index(n), + Array4(n) => Self::Array4(n), + Array8(n) => Self::Array8(n), + Array16(n) => Self::Array16(n), + Array32(n) => Self::Array32(n), + }) + } +} + impl From<()> for AssetInstance { fn from(_: ()) -> Self { Self::Undefined @@ -308,6 +330,17 @@ impl TryFrom for Fungibility { } } +impl TryFrom for Fungibility { + type Error = (); + fn try_from(value: NewFungibility) -> Result { + use NewFungibility::*; + Ok(match value { + Fungible(n) => Self::Fungible(n), + NonFungible(i) => Self::NonFungible(i.try_into()?), + }) + } +} + /// Classification of whether an asset is fungible or not. #[derive( Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo, MaxEncodedLen, @@ -332,6 +365,17 @@ impl TryFrom for WildFungibility { } } +impl TryFrom for WildFungibility { + type Error = (); + fn try_from(value: NewWildFungibility) -> Result { + use NewWildFungibility::*; + Ok(match value { + Fungible => Self::Fungible, + NonFungible => Self::NonFungible, + }) + } +} + /// Classification of an asset being concrete or abstract. #[derive( Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo, MaxEncodedLen, @@ -374,6 +418,13 @@ impl TryFrom for AssetId { } } +impl TryFrom for AssetId { + type Error = (); + fn try_from(new: NewAssetId) -> Result { + Ok(Self::Concrete(new.0.try_into()?)) + } +} + impl AssetId { /// Prepend a `MultiLocation` to a concrete asset, giving it a new root location. pub fn prepend_with(&mut self, prepend: &MultiLocation) -> Result<(), ()> { @@ -501,6 +552,13 @@ impl TryFrom for MultiAsset { } } +impl TryFrom for MultiAsset { + type Error = (); + fn try_from(new: NewMultiAsset) -> Result { + Ok(Self { id: new.id.try_into()?, fun: new.fun.try_into()? }) + } +} + /// A `Vec` of `MultiAsset`s. /// /// There are a number of invariants which the construction and mutation functions must ensure are @@ -543,6 +601,18 @@ impl TryFrom for MultiAssets { } } +impl TryFrom for MultiAssets { + type Error = (); + fn try_from(new: NewMultiAssets) -> Result { + let v = new + .into_inner() + .into_iter() + .map(MultiAsset::try_from) + .collect::, ()>>()?; + Ok(MultiAssets(v)) + } +} + impl From> for MultiAssets { fn from(mut assets: Vec) -> Self { let mut res = Vec::with_capacity(assets.len()); @@ -740,6 +810,20 @@ impl TryFrom for WildMultiAsset { } } +impl TryFrom for WildMultiAsset { + type Error = (); + fn try_from(new: NewWildMultiAsset) -> Result { + use NewWildMultiAsset::*; + Ok(match new { + AllOf { id, fun } => Self::AllOf { id: id.try_into()?, fun: fun.try_into()? }, + AllOfCounted { id, fun, count } => + Self::AllOfCounted { id: id.try_into()?, fun: fun.try_into()?, count }, + All => Self::All, + AllCounted(count) => Self::AllCounted(count), + }) + } +} + impl TryFrom<(OldWildMultiAsset, u32)> for WildMultiAsset { type Error = (); fn try_from(old: (OldWildMultiAsset, u32)) -> Result { @@ -909,6 +993,17 @@ impl TryFrom for MultiAssetFilter { } } +impl TryFrom for MultiAssetFilter { + type Error = (); + fn try_from(new: NewMultiAssetFilter) -> Result { + use NewMultiAssetFilter::*; + Ok(match new { + Definite(x) => Self::Definite(x.try_into()?), + Wild(x) => Self::Wild(x.try_into()?), + }) + } +} + impl TryFrom<(OldMultiAssetFilter, u32)> for MultiAssetFilter { type Error = (); fn try_from(old: (OldMultiAssetFilter, u32)) -> Result { diff --git a/polkadot/xcm/src/v3/multilocation.rs b/polkadot/xcm/src/v3/multilocation.rs index 89e259844438..5101fde0c096 100644 --- a/polkadot/xcm/src/v3/multilocation.rs +++ b/polkadot/xcm/src/v3/multilocation.rs @@ -17,7 +17,9 @@ //! XCM `MultiLocation` datatype. use super::{Junction, Junctions}; -use crate::{v2::MultiLocation as OldMultiLocation, VersionedMultiLocation}; +use crate::{ + v2::MultiLocation as OldMultiLocation, v4::Location as NewMultiLocation, VersionedLocation, +}; use core::{ convert::{TryFrom, TryInto}, result, @@ -73,6 +75,8 @@ pub struct MultiLocation { pub interior: Junctions, } +pub type Location = MultiLocation; + impl Default for MultiLocation { fn default() -> Self { Self { parents: 0, interior: Junctions::Here } @@ -90,9 +94,9 @@ impl MultiLocation { MultiLocation { parents, interior: interior.into() } } - /// Consume `self` and return the equivalent `VersionedMultiLocation` value. - pub const fn into_versioned(self) -> VersionedMultiLocation { - VersionedMultiLocation::V3(self) + /// Consume `self` and return the equivalent `VersionedLocation` value. + pub const fn into_versioned(self) -> VersionedLocation { + VersionedLocation::V3(self) } /// Creates a new `MultiLocation` with 0 parents and a `Here` interior. @@ -468,6 +472,20 @@ impl TryFrom for MultiLocation { } } +impl TryFrom for Option { + type Error = (); + fn try_from(new: NewMultiLocation) -> result::Result { + Ok(Some(MultiLocation::try_from(new)?)) + } +} + +impl TryFrom for MultiLocation { + type Error = (); + fn try_from(new: NewMultiLocation) -> result::Result { + Ok(MultiLocation { parents: new.parent_count(), interior: new.interior().clone().try_into()? }) + } +} + /// A unit struct which can be converted into a `MultiLocation` of `parents` value 1. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct Parent; diff --git a/polkadot/xcm/src/v3/traits.rs b/polkadot/xcm/src/v3/traits.rs index 1043d17b7106..9dfb96d753fd 100644 --- a/polkadot/xcm/src/v3/traits.rs +++ b/polkadot/xcm/src/v3/traits.rs @@ -215,52 +215,6 @@ impl From for Error { pub type Result = result::Result<(), Error>; -/* -TODO: XCMv4 -/// Outcome of an XCM execution. -#[derive(Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)] -pub enum Outcome { - /// Execution completed successfully; given weight was used. - Complete { used: Weight }, - /// Execution started, but did not complete successfully due to the given error; given weight - /// was used. - Incomplete { used: Weight, error: Error }, - /// Execution did not start due to the given error. - Error { error: Error }, -} - -impl Outcome { - pub fn ensure_complete(self) -> Result { - match self { - Outcome::Complete { .. } => Ok(()), - Outcome::Incomplete { error, .. } => Err(error), - Outcome::Error { error, .. } => Err(error), - } - } - pub fn ensure_execution(self) -> result::Result { - match self { - Outcome::Complete { used, .. } => Ok(used), - Outcome::Incomplete { used, .. } => Ok(used), - Outcome::Error { error, .. } => Err(error), - } - } - /// How much weight was used by the XCM execution attempt. - pub fn weight_used(&self) -> Weight { - match self { - Outcome::Complete { used, .. } => *used, - Outcome::Incomplete { used, .. } => *used, - Outcome::Error { .. } => Weight::zero(), - } - } -} - -impl From for Outcome { - fn from(error: Error) -> Self { - Self::Error { error, maybe_id: None } - } -} -*/ - /// Outcome of an XCM execution. #[derive(Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)] #[scale_info(replace_segment("staging_xcm", "xcm"))] @@ -336,8 +290,6 @@ pub trait ExecuteXcm { /// /// The weight limit is a basic hard-limit and the implementation may place further /// restrictions or requirements on weight and other aspects. - // TODO: XCMv4 - // #[deprecated = "Use `prepare_and_execute` instead"] fn execute_xcm( origin: impl Into, message: Xcm, @@ -360,8 +312,6 @@ pub trait ExecuteXcm { /// /// Some amount of `weight_credit` may be provided which, depending on the implementation, may /// allow execution without associated payment. - // TODO: XCMv4 - // #[deprecated = "Use `prepare_and_execute` instead"] fn execute_xcm_in_credit( origin: impl Into, message: Xcm, diff --git a/polkadot/xcm/src/v4/asset.rs b/polkadot/xcm/src/v4/asset.rs new file mode 100644 index 000000000000..0362a26ec0e7 --- /dev/null +++ b/polkadot/xcm/src/v4/asset.rs @@ -0,0 +1,923 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Substrate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Substrate is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! Cross-Consensus Message format asset data structures. +//! +//! This encompasses four types for representing assets: +//! - `Asset`: A description of a single asset, either an instance of a non-fungible or some amount +//! of a fungible. +//! - `Assets`: A collection of `Asset`s. These are stored in a `Vec` and sorted with fungibles +//! first. +//! - `Wild`: A single asset wildcard, this can either be "all" assets, or all assets of a specific +//! kind. +//! - `AssetFilter`: A combination of `Wild` and `Assets` designed for efficiently filtering an XCM +//! holding account. + +use super::{InteriorLocation, Location, Reanchorable}; +use crate::v3::{ + AssetId as OldAssetId, AssetInstance as OldAssetInstance, Fungibility as OldFungibility, + MultiAsset as OldAsset, MultiAssetFilter as OldAssetFilter, MultiAssets as OldAssets, + WildFungibility as OldWildFungibility, WildMultiAsset as OldWildAsset, +}; +use alloc::{vec, vec::Vec}; +use core::{ + cmp::Ordering, + convert::{TryFrom, TryInto}, +}; +use parity_scale_codec::{self as codec, Decode, Encode, MaxEncodedLen}; +use scale_info::TypeInfo; + +/// A general identifier for an instance of a non-fungible asset class. +#[derive( + Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, TypeInfo, MaxEncodedLen, +)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub enum AssetInstance { + /// Undefined - used if the non-fungible asset class has only one instance. + Undefined, + + /// A compact index. Technically this could be greater than `u128`, but this implementation + /// supports only values up to `2**128 - 1`. + Index(#[codec(compact)] u128), + + /// A 4-byte fixed-length datum. + Array4([u8; 4]), + + /// An 8-byte fixed-length datum. + Array8([u8; 8]), + + /// A 16-byte fixed-length datum. + Array16([u8; 16]), + + /// A 32-byte fixed-length datum. + Array32([u8; 32]), +} + +impl TryFrom for AssetInstance { + type Error = (); + fn try_from(value: OldAssetInstance) -> Result { + use OldAssetInstance::*; + Ok(match value { + Undefined => Self::Undefined, + Index(n) => Self::Index(n), + Array4(n) => Self::Array4(n), + Array8(n) => Self::Array8(n), + Array16(n) => Self::Array16(n), + Array32(n) => Self::Array32(n), + }) + } +} + +impl From<()> for AssetInstance { + fn from(_: ()) -> Self { + Self::Undefined + } +} + +impl From<[u8; 4]> for AssetInstance { + fn from(x: [u8; 4]) -> Self { + Self::Array4(x) + } +} + +impl From<[u8; 8]> for AssetInstance { + fn from(x: [u8; 8]) -> Self { + Self::Array8(x) + } +} + +impl From<[u8; 16]> for AssetInstance { + fn from(x: [u8; 16]) -> Self { + Self::Array16(x) + } +} + +impl From<[u8; 32]> for AssetInstance { + fn from(x: [u8; 32]) -> Self { + Self::Array32(x) + } +} + +impl From for AssetInstance { + fn from(x: u8) -> Self { + Self::Index(x as u128) + } +} + +impl From for AssetInstance { + fn from(x: u16) -> Self { + Self::Index(x as u128) + } +} + +impl From for AssetInstance { + fn from(x: u32) -> Self { + Self::Index(x as u128) + } +} + +impl From for AssetInstance { + fn from(x: u64) -> Self { + Self::Index(x as u128) + } +} + +impl TryFrom for () { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Undefined => Ok(()), + _ => Err(()), + } + } +} + +impl TryFrom for [u8; 4] { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Array4(x) => Ok(x), + _ => Err(()), + } + } +} + +impl TryFrom for [u8; 8] { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Array8(x) => Ok(x), + _ => Err(()), + } + } +} + +impl TryFrom for [u8; 16] { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Array16(x) => Ok(x), + _ => Err(()), + } + } +} + +impl TryFrom for [u8; 32] { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Array32(x) => Ok(x), + _ => Err(()), + } + } +} + +impl TryFrom for u8 { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Index(x) => x.try_into().map_err(|_| ()), + _ => Err(()), + } + } +} + +impl TryFrom for u16 { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Index(x) => x.try_into().map_err(|_| ()), + _ => Err(()), + } + } +} + +impl TryFrom for u32 { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Index(x) => x.try_into().map_err(|_| ()), + _ => Err(()), + } + } +} + +impl TryFrom for u64 { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Index(x) => x.try_into().map_err(|_| ()), + _ => Err(()), + } + } +} + +impl TryFrom for u128 { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Index(x) => Ok(x), + _ => Err(()), + } + } +} + +/// Classification of whether an asset is fungible or not, along with a mandatory amount or +/// instance. +#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, TypeInfo, MaxEncodedLen)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub enum Fungibility { + /// A fungible asset; we record a number of units, as a `u128` in the inner item. + Fungible(#[codec(compact)] u128), + /// A non-fungible asset. We record the instance identifier in the inner item. Only one asset + /// of each instance identifier may ever be in existence at once. + NonFungible(AssetInstance), +} + +#[derive(Decode)] +enum UncheckedFungibility { + Fungible(#[codec(compact)] u128), + NonFungible(AssetInstance), +} + +impl Decode for Fungibility { + fn decode(input: &mut I) -> Result { + match UncheckedFungibility::decode(input)? { + UncheckedFungibility::Fungible(a) if a != 0 => Ok(Self::Fungible(a)), + UncheckedFungibility::NonFungible(i) => Ok(Self::NonFungible(i)), + UncheckedFungibility::Fungible(_) => + Err("Fungible asset of zero amount is not allowed".into()), + } + } +} + +impl Fungibility { + pub fn is_kind(&self, w: WildFungibility) -> bool { + use Fungibility::*; + use WildFungibility::{Fungible as WildFungible, NonFungible as WildNonFungible}; + matches!((self, w), (Fungible(_), WildFungible) | (NonFungible(_), WildNonFungible)) + } +} + +impl From for Fungibility { + fn from(amount: i32) -> Fungibility { + debug_assert_ne!(amount, 0); + Fungibility::Fungible(amount as u128) + } +} + +impl From for Fungibility { + fn from(amount: u128) -> Fungibility { + debug_assert_ne!(amount, 0); + Fungibility::Fungible(amount) + } +} + +impl> From for Fungibility { + fn from(instance: T) -> Fungibility { + Fungibility::NonFungible(instance.into()) + } +} + +impl TryFrom for Fungibility { + type Error = (); + fn try_from(value: OldFungibility) -> Result { + use OldFungibility::*; + Ok(match value { + Fungible(n) => Self::Fungible(n), + NonFungible(i) => Self::NonFungible(i.try_into()?), + }) + } +} + +/// Classification of whether an asset is fungible or not. +#[derive( + Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo, MaxEncodedLen, +)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub enum WildFungibility { + /// The asset is fungible. + Fungible, + /// The asset is not fungible. + NonFungible, +} + +impl TryFrom for WildFungibility { + type Error = (); + fn try_from(value: OldWildFungibility) -> Result { + use OldWildFungibility::*; + Ok(match value { + Fungible => Self::Fungible, + NonFungible => Self::NonFungible, + }) + } +} + +/// Location to identify an asset. +#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub struct AssetId(pub Location); + +impl> From for AssetId { + fn from(x: T) -> Self { + Self(x.into()) + } +} + +impl TryFrom for AssetId { + type Error = (); + fn try_from(old: OldAssetId) -> Result { + use OldAssetId::*; + Ok(match old { + Concrete(l) => Self(l.try_into()?), + Abstract(_) => return Err(()), + }) + } +} + +impl AssetId { + /// Prepend a `Location` to an asset id, giving it a new root location. + pub fn prepend_with(&mut self, prepend: &Location) -> Result<(), ()> { + self.0.prepend_with(prepend.clone()).map_err(|_| ())?; + Ok(()) + } + + /// Use the value of `self` along with a `fun` fungibility specifier to create the corresponding + /// `Asset` value. + pub fn into_asset(self, fun: Fungibility) -> Asset { + Asset { fun, id: self } + } + + /// Use the value of `self` along with a `fun` fungibility specifier to create the corresponding + /// `WildAsset` wildcard (`AllOf`) value. + pub fn into_wild(self, fun: WildFungibility) -> WildAsset { + WildAsset::AllOf { fun, id: self } + } +} + +impl Reanchorable for AssetId { + type Error = (); + + /// Mutate the asset to represent the same value from the perspective of a new `target` + /// location. The local chain's location is provided in `context`. + fn reanchor(&mut self, target: &Location, context: &InteriorLocation) -> Result<(), ()> { + self.0.reanchor(target, context)?; + Ok(()) + } + + fn reanchored( + mut self, + target: &Location, + context: &InteriorLocation, + ) -> Result { + match self.reanchor(target, context) { + Ok(()) => Ok(self), + Err(()) => Err(()), + } + } +} + +/// Either an amount of a single fungible asset, or a single well-identified non-fungible asset. +#[derive(Clone, Eq, PartialEq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub struct Asset { + /// The overall asset identity (aka *class*, in the case of a non-fungible). + pub id: AssetId, + /// The fungibility of the asset, which contains either the amount (in the case of a fungible + /// asset) or the *instance ID*, the secondary asset identifier. + pub fun: Fungibility, +} + +impl PartialOrd for Asset { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Asset { + fn cmp(&self, other: &Self) -> Ordering { + match (&self.fun, &other.fun) { + (Fungibility::Fungible(..), Fungibility::NonFungible(..)) => Ordering::Less, + (Fungibility::NonFungible(..), Fungibility::Fungible(..)) => Ordering::Greater, + _ => (&self.id, &self.fun).cmp(&(&other.id, &other.fun)), + } + } +} + +impl, B: Into> From<(A, B)> for Asset { + fn from((id, fun): (A, B)) -> Asset { + Asset { fun: fun.into(), id: id.into() } + } +} + +impl Asset { + pub fn is_fungible(&self, maybe_id: Option) -> bool { + use Fungibility::*; + matches!(self.fun, Fungible(..)) && maybe_id.map_or(true, |i| i == self.id) + } + + pub fn is_non_fungible(&self, maybe_id: Option) -> bool { + use Fungibility::*; + matches!(self.fun, NonFungible(..)) && maybe_id.map_or(true, |i| i == self.id) + } + + /// Prepend a `Location` to a concrete asset, giving it a new root location. + pub fn prepend_with(&mut self, prepend: &Location) -> Result<(), ()> { + self.id.prepend_with(prepend) + } + + /// Returns true if `self` is a super-set of the given `inner` asset. + pub fn contains(&self, inner: &Asset) -> bool { + use Fungibility::*; + if self.id == inner.id { + match (&self.fun, &inner.fun) { + (Fungible(a), Fungible(i)) if a >= i => return true, + (NonFungible(a), NonFungible(i)) if a == i => return true, + _ => (), + } + } + false + } +} + +impl Reanchorable for Asset { + type Error = (); + + /// Mutate the location of the asset identifier if concrete, giving it the same location + /// relative to a `target` context. The local context is provided as `context`. + fn reanchor(&mut self, target: &Location, context: &InteriorLocation) -> Result<(), ()> { + self.id.reanchor(target, context) + } + + /// Mutate the location of the asset identifier if concrete, giving it the same location + /// relative to a `target` context. The local context is provided as `context`. + fn reanchored(mut self, target: &Location, context: &InteriorLocation) -> Result { + self.id.reanchor(target, context)?; + Ok(self) + } +} + +impl TryFrom for Asset { + type Error = (); + fn try_from(old: OldAsset) -> Result { + Ok(Self { id: old.id.try_into()?, fun: old.fun.try_into()? }) + } +} + +/// A `Vec` of `Asset`s. +/// +/// There are a number of invariants which the construction and mutation functions must ensure are +/// maintained: +/// - It may contain no items of duplicate asset class; +/// - All items must be ordered; +/// - The number of items should grow no larger than `MAX_ITEMS_IN_ASSETS`. +#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, TypeInfo, Default)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub struct Assets(Vec); + +/// Maximum number of items we expect in a single `Assets` value. Note this is not (yet) +/// enforced, and just serves to provide a sensible `max_encoded_len` for `Assets`. +pub const MAX_ITEMS_IN_ASSETS: usize = 20; + +impl MaxEncodedLen for Assets { + fn max_encoded_len() -> usize { + Asset::max_encoded_len() * MAX_ITEMS_IN_ASSETS + } +} + +impl Decode for Assets { + fn decode(input: &mut I) -> Result { + Self::from_sorted_and_deduplicated(Vec::::decode(input)?) + .map_err(|()| "Out of order".into()) + } +} + +impl TryFrom for Assets { + type Error = (); + fn try_from(old: OldAssets) -> Result { + let v = old + .into_inner() + .into_iter() + .map(Asset::try_from) + .collect::, ()>>()?; + Ok(Assets(v)) + } +} + +impl From> for Assets { + fn from(mut assets: Vec) -> Self { + let mut res = Vec::with_capacity(assets.len()); + if !assets.is_empty() { + assets.sort(); + let mut iter = assets.into_iter(); + if let Some(first) = iter.next() { + let last = iter.fold(first, |a, b| -> Asset { + match (a, b) { + ( + Asset { fun: Fungibility::Fungible(a_amount), id: a_id }, + Asset { fun: Fungibility::Fungible(b_amount), id: b_id }, + ) if a_id == b_id => Asset { + id: a_id, + fun: Fungibility::Fungible(a_amount.saturating_add(b_amount)), + }, + ( + Asset { fun: Fungibility::NonFungible(a_instance), id: a_id }, + Asset { fun: Fungibility::NonFungible(b_instance), id: b_id }, + ) if a_id == b_id && a_instance == b_instance => + Asset { fun: Fungibility::NonFungible(a_instance), id: a_id }, + (to_push, to_remember) => { + res.push(to_push); + to_remember + }, + } + }); + res.push(last); + } + } + Self(res) + } +} + +impl> From for Assets { + fn from(x: T) -> Self { + Self(vec![x.into()]) + } +} + +impl Assets { + /// A new (empty) value. + pub fn new() -> Self { + Self(Vec::new()) + } + + /// Create a new instance of `Assets` from a `Vec` whose contents are sorted + /// and which contain no duplicates. + /// + /// Returns `Ok` if the operation succeeds and `Err` if `r` is out of order or had duplicates. + /// If you can't guarantee that `r` is sorted and deduplicated, then use + /// `From::>::from` which is infallible. + pub fn from_sorted_and_deduplicated(r: Vec) -> Result { + if r.is_empty() { + return Ok(Self(Vec::new())) + } + r.iter().skip(1).try_fold(&r[0], |a, b| -> Result<&Asset, ()> { + if a.id < b.id || a < b && (a.is_non_fungible(None) || b.is_non_fungible(None)) { + Ok(b) + } else { + Err(()) + } + })?; + Ok(Self(r)) + } + + /// Create a new instance of `Assets` from a `Vec` whose contents are sorted + /// and which contain no duplicates. + /// + /// In release mode, this skips any checks to ensure that `r` is correct, making it a + /// negligible-cost operation. Generally though you should avoid using it unless you have a + /// strict proof that `r` is valid. + #[cfg(test)] + pub fn from_sorted_and_deduplicated_skip_checks(r: Vec) -> Self { + Self::from_sorted_and_deduplicated(r).expect("Invalid input r is not sorted/deduped") + } + /// Create a new instance of `Assets` from a `Vec` whose contents are sorted + /// and which contain no duplicates. + /// + /// In release mode, this skips any checks to ensure that `r` is correct, making it a + /// negligible-cost operation. Generally though you should avoid using it unless you have a + /// strict proof that `r` is valid. + /// + /// In test mode, this checks anyway and panics on fail. + #[cfg(not(test))] + pub fn from_sorted_and_deduplicated_skip_checks(r: Vec) -> Self { + Self(r) + } + + /// Add some asset onto the list, saturating. This is quite a laborious operation since it + /// maintains the ordering. + pub fn push(&mut self, a: Asset) { + for asset in self.0.iter_mut().filter(|x| x.id == a.id) { + match (&a.fun, &mut asset.fun) { + (Fungibility::Fungible(amount), Fungibility::Fungible(balance)) => { + *balance = balance.saturating_add(*amount); + return + }, + (Fungibility::NonFungible(inst1), Fungibility::NonFungible(inst2)) + if inst1 == inst2 => + return, + _ => (), + } + } + self.0.push(a); + self.0.sort(); + } + + /// Returns `true` if this definitely represents no asset. + pub fn is_none(&self) -> bool { + self.0.is_empty() + } + + /// Returns true if `self` is a super-set of the given `inner` asset. + pub fn contains(&self, inner: &Asset) -> bool { + self.0.iter().any(|i| i.contains(inner)) + } + + /// Consume `self` and return the inner vec. + #[deprecated = "Use `into_inner()` instead"] + pub fn drain(self) -> Vec { + self.0 + } + + /// Consume `self` and return the inner vec. + pub fn into_inner(self) -> Vec { + self.0 + } + + /// Return a reference to the inner vec. + pub fn inner(&self) -> &Vec { + &self.0 + } + + /// Return the number of distinct asset instances contained. + pub fn len(&self) -> usize { + self.0.len() + } + + /// Prepend a `Location` to any concrete asset items, giving it a new root location. + pub fn prepend_with(&mut self, prefix: &Location) -> Result<(), ()> { + self.0.iter_mut().try_for_each(|i| i.prepend_with(prefix)) + } + + /// Return a reference to an item at a specific index or `None` if it doesn't exist. + pub fn get(&self, index: usize) -> Option<&Asset> { + self.0.get(index) + } +} + +impl Reanchorable for Assets { + type Error = (); + + fn reanchor(&mut self, target: &Location, context: &InteriorLocation) -> Result<(), ()> { + self.0.iter_mut().try_for_each(|i| i.reanchor(target, context))?; + self.0.sort(); + Ok(()) + } + + fn reanchored( + mut self, + target: &Location, + context: &InteriorLocation, + ) -> Result { + match self.reanchor(target, context) { + Ok(()) => Ok(self), + Err(()) => Err(()), + } + } +} + +/// A wildcard representing a set of assets. +#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub enum WildAsset { + /// All assets in Holding. + All, + /// All assets in Holding of a given fungibility and ID. + AllOf { id: AssetId, fun: WildFungibility }, + /// All assets in Holding, up to `u32` individual assets (different instances of non-fungibles + /// are separate assets). + AllCounted(#[codec(compact)] u32), + /// All assets in Holding of a given fungibility and ID up to `count` individual assets + /// (different instances of non-fungibles are separate assets). + AllOfCounted { + id: AssetId, + fun: WildFungibility, + #[codec(compact)] + count: u32, + }, +} + +impl TryFrom for WildAsset { + type Error = (); + fn try_from(old: OldWildAsset) -> Result { + use OldWildAsset::*; + Ok(match old { + AllOf { id, fun } => Self::AllOf { id: id.try_into()?, fun: fun.try_into()? }, + All => Self::All, + AllOfCounted { id, fun, count } => + Self::AllOfCounted { id: id.try_into()?, fun: fun.try_into()?, count }, + AllCounted(count) => Self::AllCounted(count), + }) + } +} + +impl WildAsset { + /// Returns true if `self` is a super-set of the given `inner` asset. + pub fn contains(&self, inner: &Asset) -> bool { + use WildAsset::*; + match self { + AllOfCounted { count: 0, .. } | AllCounted(0) => false, + AllOf { fun, id } | AllOfCounted { id, fun, .. } => + inner.fun.is_kind(*fun) && &inner.id == id, + All | AllCounted(_) => true, + } + } + + /// Returns true if the wild element of `self` matches `inner`. + /// + /// Note that for `Counted` variants of wildcards, then it will disregard the count except for + /// always returning `false` when equal to 0. + #[deprecated = "Use `contains` instead"] + pub fn matches(&self, inner: &Asset) -> bool { + self.contains(inner) + } + + /// Mutate the asset to represent the same value from the perspective of a new `target` + /// location. The local chain's location is provided in `context`. + pub fn reanchor(&mut self, target: &Location, context: &InteriorLocation) -> Result<(), ()> { + use WildAsset::*; + match self { + AllOf { ref mut id, .. } | AllOfCounted { ref mut id, .. } => + id.reanchor(target, context), + All | AllCounted(_) => Ok(()), + } + } + + /// Maximum count of assets allowed to match, if any. + pub fn count(&self) -> Option { + use WildAsset::*; + match self { + AllOfCounted { count, .. } | AllCounted(count) => Some(*count), + All | AllOf { .. } => None, + } + } + + /// Explicit limit on number of assets allowed to match, if any. + pub fn limit(&self) -> Option { + self.count() + } + + /// Consume self and return the equivalent version but counted and with the `count` set to the + /// given parameter. + pub fn counted(self, count: u32) -> Self { + use WildAsset::*; + match self { + AllOfCounted { fun, id, .. } | AllOf { fun, id } => AllOfCounted { fun, id, count }, + All | AllCounted(_) => AllCounted(count), + } + } +} + +impl, B: Into> From<(A, B)> for WildAsset { + fn from((id, fun): (A, B)) -> WildAsset { + WildAsset::AllOf { fun: fun.into(), id: id.into() } + } +} + +/// `Asset` collection, defined either by a number of `Assets` or a single wildcard. +#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub enum AssetFilter { + /// Specify the filter as being everything contained by the given `Assets` inner. + Definite(Assets), + /// Specify the filter as the given `WildAsset` wildcard. + Wild(WildAsset), +} + +impl> From for AssetFilter { + fn from(x: T) -> Self { + Self::Wild(x.into()) + } +} + +impl From for AssetFilter { + fn from(x: Asset) -> Self { + Self::Definite(vec![x].into()) + } +} + +impl From> for AssetFilter { + fn from(x: Vec) -> Self { + Self::Definite(x.into()) + } +} + +impl From for AssetFilter { + fn from(x: Assets) -> Self { + Self::Definite(x) + } +} + +impl AssetFilter { + /// Returns true if `inner` would be matched by `self`. + /// + /// Note that for `Counted` variants of wildcards, then it will disregard the count except for + /// always returning `false` when equal to 0. + pub fn matches(&self, inner: &Asset) -> bool { + match self { + AssetFilter::Definite(ref assets) => assets.contains(inner), + AssetFilter::Wild(ref wild) => wild.contains(inner), + } + } + + /// Mutate the location of the asset identifier if concrete, giving it the same location + /// relative to a `target` context. The local context is provided as `context`. + pub fn reanchor(&mut self, target: &Location, context: &InteriorLocation) -> Result<(), ()> { + match self { + AssetFilter::Definite(ref mut assets) => assets.reanchor(target, context), + AssetFilter::Wild(ref mut wild) => wild.reanchor(target, context), + } + } + + /// Maximum count of assets it is possible to match, if known. + pub fn count(&self) -> Option { + use AssetFilter::*; + match self { + Definite(x) => Some(x.len() as u32), + Wild(x) => x.count(), + } + } + + /// Explicit limit placed on the number of items, if any. + pub fn limit(&self) -> Option { + use AssetFilter::*; + match self { + Definite(_) => None, + Wild(x) => x.limit(), + } + } +} + +impl TryFrom for AssetFilter { + type Error = (); + fn try_from(old: OldAssetFilter) -> Result { + Ok(match old { + OldAssetFilter::Definite(x) => Self::Definite(x.try_into()?), + OldAssetFilter::Wild(x) => Self::Wild(x.try_into()?), + }) + } +} + +#[cfg(test)] +mod tests { + use super::super::prelude::*; + + #[test] + fn conversion_works() { + let _: Assets = (Here, 1u128).into(); + } + + #[test] + fn from_sorted_and_deduplicated_works() { + use super::*; + use alloc::vec; + + let empty = vec![]; + let r = Assets::from_sorted_and_deduplicated(empty); + assert_eq!(r, Ok(Assets(vec![]))); + + let dup_fun = vec![(Here, 100).into(), (Here, 10).into()]; + let r = Assets::from_sorted_and_deduplicated(dup_fun); + assert!(r.is_err()); + + let dup_nft = vec![(Here, *b"notgood!").into(), (Here, *b"notgood!").into()]; + let r = Assets::from_sorted_and_deduplicated(dup_nft); + assert!(r.is_err()); + + let good_fun = vec![(Here, 10).into(), (Parent, 10).into()]; + let r = Assets::from_sorted_and_deduplicated(good_fun.clone()); + assert_eq!(r, Ok(Assets(good_fun))); + + let bad_fun = vec![(Parent, 10).into(), (Here, 10).into()]; + let r = Assets::from_sorted_and_deduplicated(bad_fun); + assert!(r.is_err()); + + let good_nft = vec![(Here, ()).into(), (Here, *b"good").into()]; + let r = Assets::from_sorted_and_deduplicated(good_nft.clone()); + assert_eq!(r, Ok(Assets(good_nft))); + + let bad_nft = vec![(Here, *b"bad!").into(), (Here, ()).into()]; + let r = Assets::from_sorted_and_deduplicated(bad_nft); + assert!(r.is_err()); + + let mixed_good = vec![(Here, 10).into(), (Here, *b"good").into()]; + let r = Assets::from_sorted_and_deduplicated(mixed_good.clone()); + assert_eq!(r, Ok(Assets(mixed_good))); + + let mixed_bad = vec![(Here, *b"bad!").into(), (Here, 10).into()]; + let r = Assets::from_sorted_and_deduplicated(mixed_bad); + assert!(r.is_err()); + } +} diff --git a/polkadot/xcm/src/v4/junction.rs b/polkadot/xcm/src/v4/junction.rs new file mode 100644 index 000000000000..e54e79dc3693 --- /dev/null +++ b/polkadot/xcm/src/v4/junction.rs @@ -0,0 +1,314 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! Support data structures for `Location`, primarily the `Junction` datatype. + +use super::Location; +pub use crate::v3::{BodyId, BodyPart}; +use crate::{ + v3::{Junction as OldJunction, NetworkId as OldNetworkId}, + VersionedLocation, +}; +use bounded_collections::{BoundedSlice, BoundedVec, ConstU32}; +use core::convert::TryFrom; +use parity_scale_codec::{self, Decode, Encode, MaxEncodedLen}; +use scale_info::TypeInfo; +use serde::{Deserialize, Serialize}; + +/// A single item in a path to describe the relative location of a consensus system. +/// +/// Each item assumes a pre-existing location as its context and is defined in terms of it. +#[derive( + Copy, + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Encode, + Decode, + Debug, + TypeInfo, + MaxEncodedLen, + Serialize, + Deserialize, +)] +pub enum Junction { + /// An indexed parachain belonging to and operated by the context. + /// + /// Generally used when the context is a Polkadot Relay-chain. + Parachain(#[codec(compact)] u32), + /// A 32-byte identifier for an account of a specific network that is respected as a sovereign + /// endpoint within the context. + /// + /// Generally used when the context is a Substrate-based chain. + AccountId32 { network: Option, id: [u8; 32] }, + /// An 8-byte index for an account of a specific network that is respected as a sovereign + /// endpoint within the context. + /// + /// May be used when the context is a Frame-based chain and includes e.g. an indices pallet. + AccountIndex64 { + network: Option, + #[codec(compact)] + index: u64, + }, + /// A 20-byte identifier for an account of a specific network that is respected as a sovereign + /// endpoint within the context. + /// + /// May be used when the context is an Ethereum or Bitcoin chain or smart-contract. + AccountKey20 { network: Option, key: [u8; 20] }, + /// An instanced, indexed pallet that forms a constituent part of the context. + /// + /// Generally used when the context is a Frame-based chain. + // TODO XCMv4 inner should be `Compact`. + PalletInstance(u8), + /// A non-descript index within the context location. + /// + /// Usage will vary widely owing to its generality. + /// + /// NOTE: Try to avoid using this and instead use a more specific item. + GeneralIndex(#[codec(compact)] u128), + /// A nondescript array datum, 32 bytes, acting as a key within the context + /// location. + /// + /// Usage will vary widely owing to its generality. + /// + /// NOTE: Try to avoid using this and instead use a more specific item. + // Note this is implemented as an array with a length rather than using `BoundedVec` owing to + // the bound for `Copy`. + GeneralKey { length: u8, data: [u8; 32] }, + /// The unambiguous child. + /// + /// Not currently used except as a fallback when deriving context. + OnlyChild, + /// A pluralistic body existing within consensus. + /// + /// Typical to be used to represent a governance origin of a chain, but could in principle be + /// used to represent things such as multisigs also. + Plurality { id: BodyId, part: BodyPart }, + /// A global network capable of externalizing its own consensus. This is not generally + /// meaningful outside of the universal level. + GlobalConsensus(NetworkId), +} + +/// A global identifier of a data structure existing within consensus. +/// +/// Maintenance note: Networks with global consensus and which are practically bridgeable within the +/// Polkadot ecosystem are given preference over explicit naming in this enumeration. +#[derive( + Copy, + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Encode, + Decode, + Debug, + TypeInfo, + MaxEncodedLen, + Serialize, + Deserialize, +)] +pub enum NetworkId { + /// Network specified by the first 32 bytes of its genesis block. + ByGenesis([u8; 32]), + /// Network defined by the first 32-bytes of the hash and number of some block it contains. + ByFork { block_number: u64, block_hash: [u8; 32] }, + /// The Polkadot mainnet Relay-chain. + Polkadot, + /// The Kusama canary-net Relay-chain. + Kusama, + /// The Westend testnet Relay-chain. + Westend, + /// The Rococo testnet Relay-chain. + Rococo, + /// The Wococo testnet Relay-chain. + Wococo, + /// An Ethereum network specified by its chain ID. + Ethereum { + /// The EIP-155 chain ID. + #[codec(compact)] + chain_id: u64, + }, + /// The Bitcoin network, including hard-forks supported by Bitcoin Core development team. + BitcoinCore, + /// The Bitcoin network, including hard-forks supported by Bitcoin Cash developers. + BitcoinCash, +} + +impl From for Option { + fn from(old: OldNetworkId) -> Self { + Some(NetworkId::from(old)) + } +} + +impl From for NetworkId { + fn from(old: OldNetworkId) -> Self { + use OldNetworkId::*; + match old { + ByGenesis(hash) => Self::ByGenesis(hash), + ByFork { block_number, block_hash } => Self::ByFork { block_number, block_hash }, + Polkadot => Self::Polkadot, + Kusama => Self::Kusama, + Westend => Self::Westend, + Rococo => Self::Rococo, + Wococo => Self::Wococo, + Ethereum { chain_id } => Self::Ethereum { chain_id }, + BitcoinCore => Self::BitcoinCore, + BitcoinCash => Self::BitcoinCash, + } + } +} + +impl From for Junction { + fn from(n: NetworkId) -> Self { + Self::GlobalConsensus(n) + } +} + +impl From<[u8; 32]> for Junction { + fn from(id: [u8; 32]) -> Self { + Self::AccountId32 { network: None, id } + } +} + +impl From>> for Junction { + fn from(key: BoundedVec>) -> Self { + key.as_bounded_slice().into() + } +} + +impl<'a> From>> for Junction { + fn from(key: BoundedSlice<'a, u8, ConstU32<32>>) -> Self { + let mut data = [0u8; 32]; + data[..key.len()].copy_from_slice(&key[..]); + Self::GeneralKey { length: key.len() as u8, data } + } +} + +impl<'a> TryFrom<&'a Junction> for BoundedSlice<'a, u8, ConstU32<32>> { + type Error = (); + fn try_from(key: &'a Junction) -> Result { + match key { + Junction::GeneralKey { length, data } => + BoundedSlice::try_from(&data[..data.len().min(*length as usize)]).map_err(|_| ()), + _ => Err(()), + } + } +} + +impl From<[u8; 20]> for Junction { + fn from(key: [u8; 20]) -> Self { + Self::AccountKey20 { network: None, key } + } +} + +impl From for Junction { + fn from(index: u64) -> Self { + Self::AccountIndex64 { network: None, index } + } +} + +impl From for Junction { + fn from(id: u128) -> Self { + Self::GeneralIndex(id) + } +} + +impl TryFrom for Junction { + type Error = (); + fn try_from(value: OldJunction) -> Result { + use OldJunction::*; + Ok(match value { + Parachain(id) => Self::Parachain(id), + AccountId32 { network: maybe_network, id } => + Self::AccountId32 { network: maybe_network.map(|network| network.into()), id }, + AccountIndex64 { network: maybe_network, index } => + Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index }, + AccountKey20 { network: maybe_network, key } => + Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key }, + PalletInstance(index) => Self::PalletInstance(index), + GeneralIndex(id) => Self::GeneralIndex(id), + GeneralKey { length, data } => Self::GeneralKey { length, data }, + OnlyChild => Self::OnlyChild, + Plurality { id, part } => Self::Plurality { id, part }, + GlobalConsensus(network) => Self::GlobalConsensus(network.into()), + }) + } +} + +impl Junction { + /// Convert `self` into a `Location` containing 0 parents. + /// + /// Similar to `Into::into`, except that this method can be used in a const evaluation context. + pub fn into_location(self) -> Location { + Location::new(0, [self]) + } + + /// Convert `self` into a `Location` containing `n` parents. + /// + /// Similar to `Self::into_location`, with the added ability to specify the number of parent + /// junctions. + pub fn into_exterior(self, n: u8) -> Location { + Location::new(n, [self]) + } + + /// Convert `self` into a `VersionedLocation` containing 0 parents. + /// + /// Similar to `Into::into`, except that this method can be used in a const evaluation context. + pub fn into_versioned(self) -> VersionedLocation { + self.into_location().into_versioned() + } + + /// Remove the `NetworkId` value. + pub fn remove_network_id(&mut self) { + use Junction::*; + match self { + AccountId32 { ref mut network, .. } | + AccountIndex64 { ref mut network, .. } | + AccountKey20 { ref mut network, .. } => *network = None, + _ => {}, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::vec; + + #[test] + fn junction_round_trip_works() { + let j = Junction::GeneralKey { length: 32, data: [1u8; 32] }; + let k = Junction::try_from(OldJunction::try_from(j).unwrap()).unwrap(); + assert_eq!(j, k); + + let j = OldJunction::GeneralKey { length: 32, data: [1u8; 32] }; + let k = OldJunction::try_from(Junction::try_from(j).unwrap()).unwrap(); + assert_eq!(j, k); + + let j = Junction::from(BoundedVec::try_from(vec![1u8, 2, 3, 4]).unwrap()); + let k = Junction::try_from(OldJunction::try_from(j).unwrap()).unwrap(); + assert_eq!(j, k); + let s: BoundedSlice<_, _> = (&k).try_into().unwrap(); + assert_eq!(s, &[1u8, 2, 3, 4][..]); + + let j = OldJunction::GeneralKey { length: 32, data: [1u8; 32] }; + let k = OldJunction::try_from(Junction::try_from(j).unwrap()).unwrap(); + assert_eq!(j, k); + } +} diff --git a/polkadot/xcm/src/v4/junctions.rs b/polkadot/xcm/src/v4/junctions.rs new file mode 100644 index 000000000000..58b9933463cb --- /dev/null +++ b/polkadot/xcm/src/v4/junctions.rs @@ -0,0 +1,728 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! XCM `Junctions`/`InteriorLocation` datatype. + +use super::{Junction, Location, NetworkId}; +use alloc::sync::Arc; +use core::{convert::TryFrom, mem, ops::Range, result}; +use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; +use scale_info::TypeInfo; + +/// Maximum number of `Junction`s that a `Junctions` can contain. +pub(crate) const MAX_JUNCTIONS: usize = 8; + +/// A lack of junctions means we are here. +/// This is used when unpacking a location, since junctions are turned +/// into a slice, and the [`Junctions::Here`] variant turns into the empty slice. +pub const HERE: &'static [Junction] = &[]; + +/// Non-parent junctions that can be constructed, up to the length of 8. This specific `Junctions` +/// implementation uses a Rust `enum` in order to make pattern matching easier. +/// +/// Parent junctions cannot be constructed with this type. Refer to `Location` for +/// instructions on constructing parent junctions. +#[derive( + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Encode, + Decode, + Debug, + TypeInfo, + MaxEncodedLen, + serde::Serialize, + serde::Deserialize, +)] +pub enum Junctions { + /// The interpreting consensus system. + Here, + /// A relative path comprising 1 junction. + X1(Arc<[Junction; 1]>), + /// A relative path comprising 2 junctions. + X2(Arc<[Junction; 2]>), + /// A relative path comprising 3 junctions. + X3(Arc<[Junction; 3]>), + /// A relative path comprising 4 junctions. + X4(Arc<[Junction; 4]>), + /// A relative path comprising 5 junctions. + X5(Arc<[Junction; 5]>), + /// A relative path comprising 6 junctions. + X6(Arc<[Junction; 6]>), + /// A relative path comprising 7 junctions. + X7(Arc<[Junction; 7]>), + /// A relative path comprising 8 junctions. + X8(Arc<[Junction; 8]>), +} + +macro_rules! impl_junctions { + ($count:expr, $variant:ident) => { + impl From<[Junction; $count]> for Junctions { + fn from(junctions: [Junction; $count]) -> Self { + Self::$variant(Arc::new(junctions)) + } + } + impl PartialEq<[Junction; $count]> for Junctions { + fn eq(&self, rhs: &[Junction; $count]) -> bool { + self.as_slice() == rhs + } + } + }; +} + +impl_junctions!(1, X1); +impl_junctions!(2, X2); +impl_junctions!(3, X3); +impl_junctions!(4, X4); +impl_junctions!(5, X5); +impl_junctions!(6, X6); +impl_junctions!(7, X7); +impl_junctions!(8, X8); + +pub struct JunctionsIterator { + junctions: Junctions, + range: Range, +} + +impl Iterator for JunctionsIterator { + type Item = Junction; + fn next(&mut self) -> Option { + self.junctions.at(self.range.next()?).cloned() + } +} + +impl DoubleEndedIterator for JunctionsIterator { + fn next_back(&mut self) -> Option { + self.junctions.at(self.range.next_back()?).cloned() + } +} + +pub struct JunctionsRefIterator<'a> { + junctions: &'a Junctions, + range: Range, +} + +impl<'a> Iterator for JunctionsRefIterator<'a> { + type Item = &'a Junction; + fn next(&mut self) -> Option<&'a Junction> { + self.junctions.at(self.range.next()?) + } +} + +impl<'a> DoubleEndedIterator for JunctionsRefIterator<'a> { + fn next_back(&mut self) -> Option<&'a Junction> { + self.junctions.at(self.range.next_back()?) + } +} +impl<'a> IntoIterator for &'a Junctions { + type Item = &'a Junction; + type IntoIter = JunctionsRefIterator<'a>; + fn into_iter(self) -> Self::IntoIter { + JunctionsRefIterator { junctions: self, range: 0..self.len() } + } +} + +impl IntoIterator for Junctions { + type Item = Junction; + type IntoIter = JunctionsIterator; + fn into_iter(self) -> Self::IntoIter { + JunctionsIterator { range: 0..self.len(), junctions: self } + } +} + +impl Junctions { + /// Convert `self` into a `Location` containing 0 parents. + /// + /// Similar to `Into::into`, except that this method can be used in a const evaluation context. + pub const fn into_location(self) -> Location { + Location { parents: 0, interior: self } + } + + /// Convert `self` into a `Location` containing `n` parents. + /// + /// Similar to `Self::into_location`, with the added ability to specify the number of parent + /// junctions. + pub const fn into_exterior(self, n: u8) -> Location { + Location { parents: n, interior: self } + } + + /// Casts `self` into a slice containing `Junction`s. + pub fn as_slice(&self) -> &[Junction] { + match self { + Junctions::Here => &[], + Junctions::X1(ref a) => &a[..], + Junctions::X2(ref a) => &a[..], + Junctions::X3(ref a) => &a[..], + Junctions::X4(ref a) => &a[..], + Junctions::X5(ref a) => &a[..], + Junctions::X6(ref a) => &a[..], + Junctions::X7(ref a) => &a[..], + Junctions::X8(ref a) => &a[..], + } + } + + /// Casts `self` into a mutable slice containing `Junction`s. + pub fn as_slice_mut(&mut self) -> &mut [Junction] { + match self { + Junctions::Here => &mut [], + Junctions::X1(ref mut a) => &mut Arc::make_mut(a)[..], + Junctions::X2(ref mut a) => &mut Arc::make_mut(a)[..], + Junctions::X3(ref mut a) => &mut Arc::make_mut(a)[..], + Junctions::X4(ref mut a) => &mut Arc::make_mut(a)[..], + Junctions::X5(ref mut a) => &mut Arc::make_mut(a)[..], + Junctions::X6(ref mut a) => &mut Arc::make_mut(a)[..], + Junctions::X7(ref mut a) => &mut Arc::make_mut(a)[..], + Junctions::X8(ref mut a) => &mut Arc::make_mut(a)[..], + } + } + + /// Remove the `NetworkId` value in any `Junction`s. + pub fn remove_network_id(&mut self) { + self.for_each_mut(Junction::remove_network_id); + } + + /// Treating `self` as the universal context, return the location of the local consensus system + /// from the point of view of the given `target`. + pub fn invert_target(&self, target: &Location) -> Result { + let mut itself = self.clone(); + let mut junctions = Self::Here; + for _ in 0..target.parent_count() { + junctions = junctions + .pushed_front_with(itself.take_last().unwrap_or(Junction::OnlyChild)) + .map_err(|_| ())?; + } + let parents = target.interior().len() as u8; + Ok(Location::new(parents, junctions)) + } + + /// Execute a function `f` on every junction. We use this since we cannot implement a mutable + /// `Iterator` without unsafe code. + pub fn for_each_mut(&mut self, x: impl FnMut(&mut Junction)) { + self.as_slice_mut().iter_mut().for_each(x) + } + + /// Extract the network ID treating this value as a universal location. + /// + /// This will return an `Err` if the first item is not a `GlobalConsensus`, which would indicate + /// that this value is not a universal location. + pub fn global_consensus(&self) -> Result { + if let Some(Junction::GlobalConsensus(network)) = self.first() { + Ok(*network) + } else { + Err(()) + } + } + + /// Extract the network ID and the interior consensus location, treating this value as a + /// universal location. + /// + /// This will return an `Err` if the first item is not a `GlobalConsensus`, which would indicate + /// that this value is not a universal location. + pub fn split_global(self) -> Result<(NetworkId, Junctions), ()> { + match self.split_first() { + (location, Some(Junction::GlobalConsensus(network))) => Ok((network, location)), + _ => return Err(()), + } + } + + /// Treat `self` as a universal location and the context of `relative`, returning the universal + /// location of relative. + /// + /// This will return an error if `relative` has as many (or more) parents than there are + /// junctions in `self`, implying that relative refers into a different global consensus. + pub fn within_global(mut self, relative: Location) -> Result { + if self.len() <= relative.parent_count() as usize { + return Err(()) + } + for _ in 0..relative.parent_count() { + self.take_last(); + } + for j in relative.interior() { + self.push(*j).map_err(|_| ())?; + } + Ok(self) + } + + /// Consumes `self` and returns how `viewer` would address it locally. + pub fn relative_to(mut self, viewer: &Junctions) -> Location { + let mut i = 0; + while match (self.first(), viewer.at(i)) { + (Some(x), Some(y)) => x == y, + _ => false, + } { + self = self.split_first().0; + // NOTE: Cannot overflow as loop can only iterate at most `MAX_JUNCTIONS` times. + i += 1; + } + // AUDIT NOTES: + // - above loop ensures that `i <= viewer.len()`. + // - `viewer.len()` is at most `MAX_JUNCTIONS`, so won't overflow a `u8`. + Location::new((viewer.len() - i) as u8, self) + } + + /// Returns first junction, or `None` if the location is empty. + pub fn first(&self) -> Option<&Junction> { + self.as_slice().first() + } + + /// Returns last junction, or `None` if the location is empty. + pub fn last(&self) -> Option<&Junction> { + self.as_slice().last() + } + + /// Splits off the first junction, returning the remaining suffix (first item in tuple) and the + /// first element (second item in tuple) or `None` if it was empty. + pub fn split_first(self) -> (Junctions, Option) { + match self { + Junctions::Here => (Junctions::Here, None), + Junctions::X1(xs) => { + let [a] = *xs; + (Junctions::Here, Some(a)) + }, + Junctions::X2(xs) => { + let [a, b] = *xs; + ([b].into(), Some(a)) + }, + Junctions::X3(xs) => { + let [a, b, c] = *xs; + ([b, c].into(), Some(a)) + }, + Junctions::X4(xs) => { + let [a, b, c, d] = *xs; + ([b, c, d].into(), Some(a)) + }, + Junctions::X5(xs) => { + let [a, b, c, d, e] = *xs; + ([b, c, d, e].into(), Some(a)) + }, + Junctions::X6(xs) => { + let [a, b, c, d, e, f] = *xs; + ([b, c, d, e, f].into(), Some(a)) + }, + Junctions::X7(xs) => { + let [a, b, c, d, e, f, g] = *xs; + ([b, c, d, e, f, g].into(), Some(a)) + }, + Junctions::X8(xs) => { + let [a, b, c, d, e, f, g, h] = *xs; + ([b, c, d, e, f, g, h].into(), Some(a)) + }, + } + } + + /// Splits off the last junction, returning the remaining prefix (first item in tuple) and the + /// last element (second item in tuple) or `None` if it was empty. + pub fn split_last(self) -> (Junctions, Option) { + match self { + Junctions::Here => (Junctions::Here, None), + Junctions::X1(xs) => { + let [a] = *xs; + (Junctions::Here, Some(a)) + }, + Junctions::X2(xs) => { + let [a, b] = *xs; + ([a].into(), Some(b)) + }, + Junctions::X3(xs) => { + let [a, b, c] = *xs; + ([a, b].into(), Some(c)) + }, + Junctions::X4(xs) => { + let [a, b, c, d] = *xs; + ([a, b, c].into(), Some(d)) + }, + Junctions::X5(xs) => { + let [a, b, c, d, e] = *xs; + ([a, b, c, d].into(), Some(e)) + }, + Junctions::X6(xs) => { + let [a, b, c, d, e, f] = *xs; + ([a, b, c, d, e].into(), Some(f)) + }, + Junctions::X7(xs) => { + let [a, b, c, d, e, f, g] = *xs; + ([a, b, c, d, e, f].into(), Some(g)) + }, + Junctions::X8(xs) => { + let [a, b, c, d, e, f, g, h] = *xs; + ([a, b, c, d, e, f, g].into(), Some(h)) + }, + } + } + + /// Removes the first element from `self`, returning it (or `None` if it was empty). + pub fn take_first(&mut self) -> Option { + let mut d = Junctions::Here; + mem::swap(&mut *self, &mut d); + let (tail, head) = d.split_first(); + *self = tail; + head + } + + /// Removes the last element from `self`, returning it (or `None` if it was empty). + pub fn take_last(&mut self) -> Option { + let mut d = Junctions::Here; + mem::swap(&mut *self, &mut d); + let (head, tail) = d.split_last(); + *self = head; + tail + } + + /// Mutates `self` to be appended with `new` or returns an `Err` with `new` if would overflow. + pub fn push(&mut self, new: impl Into) -> result::Result<(), Junction> { + let new = new.into(); + let mut dummy = Junctions::Here; + mem::swap(self, &mut dummy); + match dummy.pushed_with(new) { + Ok(s) => { + *self = s; + Ok(()) + }, + Err((s, j)) => { + *self = s; + Err(j) + }, + } + } + + /// Mutates `self` to be prepended with `new` or returns an `Err` with `new` if would overflow. + pub fn push_front(&mut self, new: impl Into) -> result::Result<(), Junction> { + let new = new.into(); + let mut dummy = Junctions::Here; + mem::swap(self, &mut dummy); + match dummy.pushed_front_with(new) { + Ok(s) => { + *self = s; + Ok(()) + }, + Err((s, j)) => { + *self = s; + Err(j) + }, + } + } + + /// Consumes `self` and returns a `Junctions` suffixed with `new`, or an `Err` with the + /// original value of `self` and `new` in case of overflow. + pub fn pushed_with(self, new: impl Into) -> result::Result { + let new = new.into(); + Ok(match self { + Junctions::Here => [new].into(), + Junctions::X1(xs) => { + let [a] = *xs; + [a, new].into() + }, + Junctions::X2(xs) => { + let [a, b] = *xs; + [a, b, new].into() + }, + Junctions::X3(xs) => { + let [a, b, c] = *xs; + [a, b, c, new].into() + }, + Junctions::X4(xs) => { + let [a, b, c, d] = *xs; + [a, b, c, d, new].into() + }, + Junctions::X5(xs) => { + let [a, b, c, d, e] = *xs; + [a, b, c, d, e, new].into() + }, + Junctions::X6(xs) => { + let [a, b, c, d, e, f] = *xs; + [a, b, c, d, e, f, new].into() + }, + Junctions::X7(xs) => { + let [a, b, c, d, e, f, g] = *xs; + [a, b, c, d, e, f, g, new].into() + }, + s => Err((s, new))?, + }) + } + + /// Consumes `self` and returns a `Junctions` prefixed with `new`, or an `Err` with the + /// original value of `self` and `new` in case of overflow. + pub fn pushed_front_with( + self, + new: impl Into, + ) -> result::Result { + let new = new.into(); + Ok(match self { + Junctions::Here => [new].into(), + Junctions::X1(xs) => { + let [a] = *xs; + [new, a].into() + }, + Junctions::X2(xs) => { + let [a, b] = *xs; + [new, a, b].into() + }, + Junctions::X3(xs) => { + let [a, b, c] = *xs; + [new, a, b, c].into() + }, + Junctions::X4(xs) => { + let [a, b, c, d] = *xs; + [new, a, b, c, d].into() + }, + Junctions::X5(xs) => { + let [a, b, c, d, e] = *xs; + [new, a, b, c, d, e].into() + }, + Junctions::X6(xs) => { + let [a, b, c, d, e, f] = *xs; + [new, a, b, c, d, e, f].into() + }, + Junctions::X7(xs) => { + let [a, b, c, d, e, f, g] = *xs; + [new, a, b, c, d, e, f, g].into() + }, + s => Err((s, new))?, + }) + } + + /// Mutate `self` so that it is suffixed with `suffix`. + /// + /// Does not modify `self` and returns `Err` with `suffix` in case of overflow. + /// + /// # Example + /// ```rust + /// # use staging_xcm::v4::{Junctions, Junction::*, Location}; + /// # fn main() { + /// let mut m = Junctions::from([Parachain(21)]); + /// assert_eq!(m.append_with([PalletInstance(3)]), Ok(())); + /// assert_eq!(m, [Parachain(21), PalletInstance(3)]); + /// # } + /// ``` + pub fn append_with(&mut self, suffix: impl Into) -> Result<(), Junctions> { + let suffix = suffix.into(); + if self.len().saturating_add(suffix.len()) > MAX_JUNCTIONS { + return Err(suffix) + } + for j in suffix.into_iter() { + self.push(j).expect("Already checked the sum of the len()s; qed") + } + Ok(()) + } + + /// Returns the number of junctions in `self`. + pub fn len(&self) -> usize { + self.as_slice().len() + } + + /// Returns the junction at index `i`, or `None` if the location doesn't contain that many + /// elements. + pub fn at(&self, i: usize) -> Option<&Junction> { + self.as_slice().get(i) + } + + /// Returns a mutable reference to the junction at index `i`, or `None` if the location doesn't + /// contain that many elements. + pub fn at_mut(&mut self, i: usize) -> Option<&mut Junction> { + self.as_slice_mut().get_mut(i) + } + + /// Returns a reference iterator over the junctions. + pub fn iter(&self) -> JunctionsRefIterator { + JunctionsRefIterator { junctions: self, range: 0..self.len() } + } + + /// Ensures that self begins with `prefix` and that it has a single `Junction` item following. + /// If so, returns a reference to this `Junction` item. + /// + /// # Example + /// ```rust + /// # use staging_xcm::v4::{Junctions, Junction::*}; + /// # fn main() { + /// let mut m = Junctions::from([Parachain(2), PalletInstance(3), OnlyChild]); + /// assert_eq!(m.match_and_split(&[Parachain(2), PalletInstance(3)].into()), Some(&OnlyChild)); + /// assert_eq!(m.match_and_split(&[Parachain(2)].into()), None); + /// # } + /// ``` + pub fn match_and_split(&self, prefix: &Junctions) -> Option<&Junction> { + if prefix.len() + 1 != self.len() { + return None + } + for i in 0..prefix.len() { + if prefix.at(i) != self.at(i) { + return None + } + } + return self.at(prefix.len()) + } + + pub fn starts_with(&self, prefix: &Junctions) -> bool { + prefix.len() <= self.len() && prefix.iter().zip(self.iter()).all(|(x, y)| x == y) + } +} + +impl TryFrom for Junctions { + type Error = Location; + fn try_from(x: Location) -> result::Result { + if x.parent_count() > 0 { + Err(x) + } else { + Ok(x.interior().clone()) + } + } +} + +impl> From for Junctions { + fn from(x: T) -> Self { + [x.into()].into() + } +} + +impl From<[Junction; 0]> for Junctions { + fn from(_: [Junction; 0]) -> Self { + Self::Here + } +} + +impl From<()> for Junctions { + fn from(_: ()) -> Self { + Self::Here + } +} + +xcm_procedural::impl_conversion_functions_for_junctions_v4!(); + +#[cfg(test)] +mod tests { + use super::{super::prelude::*, *}; + + #[test] + fn inverting_works() { + let context: InteriorLocation = (Parachain(1000), PalletInstance(42)).into(); + let target = (Parent, PalletInstance(69)).into(); + let expected = (Parent, PalletInstance(42)).into(); + let inverted = context.invert_target(&target).unwrap(); + assert_eq!(inverted, expected); + + let context: InteriorLocation = + (Parachain(1000), PalletInstance(42), GeneralIndex(1)).into(); + let target = (Parent, Parent, PalletInstance(69), GeneralIndex(2)).into(); + let expected = (Parent, Parent, PalletInstance(42), GeneralIndex(1)).into(); + let inverted = context.invert_target(&target).unwrap(); + assert_eq!(inverted, expected); + } + + #[test] + fn relative_to_works() { + use NetworkId::*; + assert_eq!( + Junctions::from([Polkadot.into()]).relative_to(&Junctions::from([Kusama.into()])), + (Parent, Polkadot).into() + ); + let base = Junctions::from([Kusama.into(), Parachain(1), PalletInstance(1)]); + + // Ancestors. + assert_eq!(Here.relative_to(&base), (Parent, Parent, Parent).into()); + assert_eq!(Junctions::from([Kusama.into()]).relative_to(&base), (Parent, Parent).into()); + assert_eq!( + Junctions::from([Kusama.into(), Parachain(1)]).relative_to(&base), + (Parent,).into() + ); + assert_eq!( + Junctions::from([Kusama.into(), Parachain(1), PalletInstance(1)]).relative_to(&base), + Here.into() + ); + + // Ancestors with one child. + assert_eq!( + Junctions::from([Polkadot.into()]).relative_to(&base), + (Parent, Parent, Parent, Polkadot).into() + ); + assert_eq!( + Junctions::from([Kusama.into(), Parachain(2)]).relative_to(&base), + (Parent, Parent, Parachain(2)).into() + ); + assert_eq!( + Junctions::from([Kusama.into(), Parachain(1), PalletInstance(2)]).relative_to(&base), + (Parent, PalletInstance(2)).into() + ); + assert_eq!( + Junctions::from([Kusama.into(), Parachain(1), PalletInstance(1), [1u8; 32].into()]) + .relative_to(&base), + ([1u8; 32],).into() + ); + + // Ancestors with grandchildren. + assert_eq!( + Junctions::from([Polkadot.into(), Parachain(1)]).relative_to(&base), + (Parent, Parent, Parent, Polkadot, Parachain(1)).into() + ); + assert_eq!( + Junctions::from([Kusama.into(), Parachain(2), PalletInstance(1)]).relative_to(&base), + (Parent, Parent, Parachain(2), PalletInstance(1)).into() + ); + assert_eq!( + Junctions::from([Kusama.into(), Parachain(1), PalletInstance(2), [1u8; 32].into()]) + .relative_to(&base), + (Parent, PalletInstance(2), [1u8; 32]).into() + ); + assert_eq!( + Junctions::from([ + Kusama.into(), + Parachain(1), + PalletInstance(1), + [1u8; 32].into(), + 1u128.into() + ]) + .relative_to(&base), + ([1u8; 32], 1u128).into() + ); + } + + #[test] + fn global_consensus_works() { + use NetworkId::*; + assert_eq!(Junctions::from([Polkadot.into()]).global_consensus(), Ok(Polkadot)); + assert_eq!(Junctions::from([Kusama.into(), 1u64.into()]).global_consensus(), Ok(Kusama)); + assert_eq!(Here.global_consensus(), Err(())); + assert_eq!(Junctions::from([1u64.into()]).global_consensus(), Err(())); + assert_eq!(Junctions::from([1u64.into(), Kusama.into()]).global_consensus(), Err(())); + } + + #[test] + fn test_conversion() { + use super::{Junction::*, NetworkId::*}; + let x: Junctions = GlobalConsensus(Polkadot).into(); + assert_eq!(x, Junctions::from([GlobalConsensus(Polkadot)])); + let x: Junctions = Polkadot.into(); + assert_eq!(x, Junctions::from([GlobalConsensus(Polkadot)])); + let x: Junctions = (Polkadot, Kusama).into(); + assert_eq!(x, Junctions::from([GlobalConsensus(Polkadot), GlobalConsensus(Kusama)])); + } + + #[test] + fn encode_decode_junctions_works() { + let original = Junctions::from([ + Polkadot.into(), + Kusama.into(), + 1u64.into(), + GlobalConsensus(Polkadot), + Parachain(123), + PalletInstance(45), + ]); + let encoded = original.encode(); + assert_eq!(encoded, &[6, 9, 2, 9, 3, 2, 0, 4, 9, 2, 0, 237, 1, 4, 45]); + let decoded = Junctions::decode(&mut &encoded[..]).unwrap(); + assert_eq!(decoded, original); + } +} diff --git a/polkadot/xcm/src/v4/location.rs b/polkadot/xcm/src/v4/location.rs new file mode 100644 index 000000000000..aae60720fc82 --- /dev/null +++ b/polkadot/xcm/src/v4/location.rs @@ -0,0 +1,755 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! XCM `Location` datatype. + +use super::{traits::Reanchorable, Junction, Junctions}; +use crate::{v3::MultiLocation as OldLocation, VersionedLocation}; +use core::{ + convert::{TryFrom, TryInto}, + result, +}; +use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; +use scale_info::TypeInfo; + +/// A relative path between state-bearing consensus systems. +/// +/// A location in a consensus system is defined as an *isolatable state machine* held within global +/// consensus. The location in question need not have a sophisticated consensus algorithm of its +/// own; a single account within Ethereum, for example, could be considered a location. +/// +/// A very-much non-exhaustive list of types of location include: +/// - A (normal, layer-1) block chain, e.g. the Bitcoin mainnet or a parachain. +/// - A layer-0 super-chain, e.g. the Polkadot Relay chain. +/// - A layer-2 smart contract, e.g. an ERC-20 on Ethereum. +/// - A logical functional component of a chain, e.g. a single instance of a pallet on a Frame-based +/// Substrate chain. +/// - An account. +/// +/// A `Location` is a *relative identifier*, meaning that it can only be used to define the +/// relative path between two locations, and cannot generally be used to refer to a location +/// universally. It is comprised of an integer number of parents specifying the number of times to +/// "escape" upwards into the containing consensus system and then a number of *junctions*, each +/// diving down and specifying some interior portion of state (which may be considered a +/// "sub-consensus" system). +/// +/// This specific `Location` implementation uses a `Junctions` datatype which is a Rust `enum` +/// in order to make pattern matching easier. There are occasions where it is important to ensure +/// that a value is strictly an interior location, in those cases, `Junctions` may be used. +/// +/// The `Location` value of `Null` simply refers to the interpreting consensus system. +#[derive( + Clone, + Decode, + Encode, + Eq, + PartialEq, + Ord, + PartialOrd, + Debug, + TypeInfo, + MaxEncodedLen, + serde::Serialize, + serde::Deserialize, +)] +pub struct Location { + /// The number of parent junctions at the beginning of this `Location`. + pub parents: u8, + /// The interior (i.e. non-parent) junctions that this `Location` contains. + pub interior: Junctions, +} + +impl Default for Location { + fn default() -> Self { + Self { parents: 0, interior: Junctions::Here } + } +} + +/// A relative location which is constrained to be an interior location of the context. +/// +/// See also `Location`. +pub type InteriorLocation = Junctions; + +impl Location { + /// Creates a new `Location` with the given number of parents and interior junctions. + pub fn new(parents: u8, interior: impl Into) -> Location { + Location { parents, interior: interior.into() } + } + + /// Consume `self` and return the equivalent `VersionedLocation` value. + pub const fn into_versioned(self) -> VersionedLocation { + VersionedLocation::V4(self) + } + + /// Creates a new `Location` with 0 parents and a `Here` interior. + /// + /// The resulting `Location` can be interpreted as the "current consensus system". + pub const fn here() -> Location { + Location { parents: 0, interior: Junctions::Here } + } + + /// Creates a new `Location` which evaluates to the parent context. + pub const fn parent() -> Location { + Location { parents: 1, interior: Junctions::Here } + } + + /// Creates a new `Location` which evaluates to the grand parent context. + pub const fn grandparent() -> Location { + Location { parents: 2, interior: Junctions::Here } + } + + /// Creates a new `Location` with `parents` and an empty (`Here`) interior. + pub const fn ancestor(parents: u8) -> Location { + Location { parents, interior: Junctions::Here } + } + + /// Whether the `Location` has no parents and has a `Here` interior. + pub fn is_here(&self) -> bool { + self.parents == 0 && self.interior.len() == 0 + } + + /// Remove the `NetworkId` value in any interior `Junction`s. + pub fn remove_network_id(&mut self) { + self.interior.remove_network_id(); + } + + /// Return a reference to the interior field. + pub fn interior(&self) -> &Junctions { + &self.interior + } + + /// Return a mutable reference to the interior field. + pub fn interior_mut(&mut self) -> &mut Junctions { + &mut self.interior + } + + /// Returns the number of `Parent` junctions at the beginning of `self`. + pub const fn parent_count(&self) -> u8 { + self.parents + } + + /// Returns the parent count and the interior [`Junctions`] as a tuple. + /// + /// To be used when pattern matching, for example: + /// + /// ```rust + /// # use staging_xcm::v4::{Junctions::*, Junction::*, Location}; + /// fn get_parachain_id(loc: &Location) -> Option { + /// match loc.unpack() { + /// (0, [Parachain(id)]) => Some(*id), + /// _ => None + /// } + /// } + /// ``` + pub fn unpack(&self) -> (u8, &[Junction]) { + (self.parents, self.interior.as_slice()) + } + + /// Returns boolean indicating whether `self` contains only the specified amount of + /// parents and no interior junctions. + pub const fn contains_parents_only(&self, count: u8) -> bool { + matches!(self.interior, Junctions::Here) && self.parents == count + } + + /// Returns the number of parents and junctions in `self`. + pub fn len(&self) -> usize { + self.parent_count() as usize + self.interior.len() + } + + /// Returns the first interior junction, or `None` if the location is empty or contains only + /// parents. + pub fn first_interior(&self) -> Option<&Junction> { + self.interior.first() + } + + /// Returns last junction, or `None` if the location is empty or contains only parents. + pub fn last(&self) -> Option<&Junction> { + self.interior.last() + } + + /// Splits off the first interior junction, returning the remaining suffix (first item in tuple) + /// and the first element (second item in tuple) or `None` if it was empty. + pub fn split_first_interior(self) -> (Location, Option) { + let Location { parents, interior: junctions } = self; + let (suffix, first) = junctions.split_first(); + let location = Location { parents, interior: suffix }; + (location, first) + } + + /// Splits off the last interior junction, returning the remaining prefix (first item in tuple) + /// and the last element (second item in tuple) or `None` if it was empty or if `self` only + /// contains parents. + pub fn split_last_interior(self) -> (Location, Option) { + let Location { parents, interior: junctions } = self; + let (prefix, last) = junctions.split_last(); + let location = Location { parents, interior: prefix }; + (location, last) + } + + /// Mutates `self`, suffixing its interior junctions with `new`. Returns `Err` with `new` in + /// case of overflow. + pub fn push_interior(&mut self, new: impl Into) -> result::Result<(), Junction> { + self.interior.push(new) + } + + /// Mutates `self`, prefixing its interior junctions with `new`. Returns `Err` with `new` in + /// case of overflow. + pub fn push_front_interior( + &mut self, + new: impl Into, + ) -> result::Result<(), Junction> { + self.interior.push_front(new) + } + + /// Consumes `self` and returns a `Location` suffixed with `new`, or an `Err` with + /// theoriginal value of `self` in case of overflow. + pub fn pushed_with_interior( + self, + new: impl Into, + ) -> result::Result { + match self.interior.pushed_with(new) { + Ok(i) => Ok(Location { interior: i, parents: self.parents }), + Err((i, j)) => Err((Location { interior: i, parents: self.parents }, j)), + } + } + + /// Consumes `self` and returns a `Location` prefixed with `new`, or an `Err` with the + /// original value of `self` in case of overflow. + pub fn pushed_front_with_interior( + self, + new: impl Into, + ) -> result::Result { + match self.interior.pushed_front_with(new) { + Ok(i) => Ok(Location { interior: i, parents: self.parents }), + Err((i, j)) => Err((Location { interior: i, parents: self.parents }, j)), + } + } + + /// Returns the junction at index `i`, or `None` if the location is a parent or if the location + /// does not contain that many elements. + pub fn at(&self, i: usize) -> Option<&Junction> { + let num_parents = self.parents as usize; + if i < num_parents { + return None + } + self.interior.at(i - num_parents) + } + + /// Returns a mutable reference to the junction at index `i`, or `None` if the location is a + /// parent or if it doesn't contain that many elements. + pub fn at_mut(&mut self, i: usize) -> Option<&mut Junction> { + let num_parents = self.parents as usize; + if i < num_parents { + return None + } + self.interior.at_mut(i - num_parents) + } + + /// Decrements the parent count by 1. + pub fn dec_parent(&mut self) { + self.parents = self.parents.saturating_sub(1); + } + + /// Removes the first interior junction from `self`, returning it + /// (or `None` if it was empty or if `self` contains only parents). + pub fn take_first_interior(&mut self) -> Option { + self.interior.take_first() + } + + /// Removes the last element from `interior`, returning it (or `None` if it was empty or if + /// `self` only contains parents). + pub fn take_last(&mut self) -> Option { + self.interior.take_last() + } + + /// Ensures that `self` has the same number of parents as `prefix`, its junctions begins with + /// the junctions of `prefix` and that it has a single `Junction` item following. + /// If so, returns a reference to this `Junction` item. + /// + /// # Example + /// ```rust + /// # use staging_xcm::v4::{Junctions::*, Junction::*, Location}; + /// # fn main() { + /// let mut m = Location::new(1, [PalletInstance(3), OnlyChild]); + /// assert_eq!( + /// m.match_and_split(&Location::new(1, [PalletInstance(3)])), + /// Some(&OnlyChild), + /// ); + /// assert_eq!(m.match_and_split(&Location::new(1, Here)), None); + /// # } + /// ``` + pub fn match_and_split(&self, prefix: &Location) -> Option<&Junction> { + if self.parents != prefix.parents { + return None + } + self.interior.match_and_split(&prefix.interior) + } + + pub fn starts_with(&self, prefix: &Location) -> bool { + self.parents == prefix.parents && self.interior.starts_with(&prefix.interior) + } + + /// Mutate `self` so that it is suffixed with `suffix`. + /// + /// Does not modify `self` and returns `Err` with `suffix` in case of overflow. + /// + /// # Example + /// ```rust + /// # use staging_xcm::v4::{Junctions::*, Junction::*, Location, Parent}; + /// # fn main() { + /// let mut m: Location = (Parent, Parachain(21), 69u64).into(); + /// assert_eq!(m.append_with((Parent, PalletInstance(3))), Ok(())); + /// assert_eq!(m, Location::new(1, [Parachain(21), PalletInstance(3)])); + /// # } + /// ``` + pub fn append_with(&mut self, suffix: impl Into) -> Result<(), Self> { + let prefix = core::mem::replace(self, suffix.into()); + match self.prepend_with(prefix) { + Ok(()) => Ok(()), + Err(prefix) => Err(core::mem::replace(self, prefix)), + } + } + + /// Consume `self` and return its value suffixed with `suffix`. + /// + /// Returns `Err` with the original value of `self` and `suffix` in case of overflow. + /// + /// # Example + /// ```rust + /// # use staging_xcm::v4::{Junctions::*, Junction::*, Location, Parent}; + /// # fn main() { + /// let mut m: Location = (Parent, Parachain(21), 69u64).into(); + /// let r = m.appended_with((Parent, PalletInstance(3))).unwrap(); + /// assert_eq!(r, Location::new(1, [Parachain(21), PalletInstance(3)])); + /// # } + /// ``` + pub fn appended_with(mut self, suffix: impl Into) -> Result { + match self.append_with(suffix) { + Ok(()) => Ok(self), + Err(suffix) => Err((self, suffix)), + } + } + + /// Mutate `self` so that it is prefixed with `prefix`. + /// + /// Does not modify `self` and returns `Err` with `prefix` in case of overflow. + /// + /// # Example + /// ```rust + /// # use staging_xcm::v4::{Junctions::*, Junction::*, Location, Parent}; + /// # fn main() { + /// let mut m: Location = (Parent, Parent, PalletInstance(3)).into(); + /// assert_eq!(m.prepend_with((Parent, Parachain(21), OnlyChild)), Ok(())); + /// assert_eq!(m, Location::new(1, [PalletInstance(3)])); + /// # } + /// ``` + pub fn prepend_with(&mut self, prefix: impl Into) -> Result<(), Self> { + // prefix self (suffix) + // P .. P I .. I p .. p i .. i + let mut prefix = prefix.into(); + let prepend_interior = prefix.interior.len().saturating_sub(self.parents as usize); + let final_interior = self.interior.len().saturating_add(prepend_interior); + if final_interior > super::junctions::MAX_JUNCTIONS { + return Err(prefix) + } + let suffix_parents = (self.parents as usize).saturating_sub(prefix.interior.len()); + let final_parents = (prefix.parents as usize).saturating_add(suffix_parents); + if final_parents > 255 { + return Err(prefix) + } + + // cancel out the final item on the prefix interior for one of the suffix's parents. + while self.parents > 0 && prefix.take_last().is_some() { + self.dec_parent(); + } + + // now we have either removed all suffix's parents or prefix interior. + // this means we can combine the prefix's and suffix's remaining parents/interior since + // we know that with at least one empty, the overall order will be respected: + // prefix self (suffix) + // P .. P (I) p .. p i .. i => P + p .. (no I) i + // -- or -- + // P .. P I .. I (p) i .. i => P (no p) .. I + i + + self.parents = self.parents.saturating_add(prefix.parents); + for j in prefix.interior.into_iter().rev() { + self.push_front_interior(j) + .expect("final_interior no greater than MAX_JUNCTIONS; qed"); + } + Ok(()) + } + + /// Consume `self` and return its value prefixed with `prefix`. + /// + /// Returns `Err` with the original value of `self` and `prefix` in case of overflow. + /// + /// # Example + /// ```rust + /// # use staging_xcm::v4::{Junctions::*, Junction::*, Location, Parent}; + /// # fn main() { + /// let m: Location = (Parent, Parent, PalletInstance(3)).into(); + /// let r = m.prepended_with((Parent, Parachain(21), OnlyChild)).unwrap(); + /// assert_eq!(r, Location::new(1, [PalletInstance(3)])); + /// # } + /// ``` + pub fn prepended_with(mut self, prefix: impl Into) -> Result { + match self.prepend_with(prefix) { + Ok(()) => Ok(self), + Err(prefix) => Err((self, prefix)), + } + } + + /// Remove any unneeded parents/junctions in `self` based on the given context it will be + /// interpreted in. + pub fn simplify(&mut self, context: &Junctions) { + if context.len() < self.parents as usize { + // Not enough context + return + } + while self.parents > 0 { + let maybe = context.at(context.len() - (self.parents as usize)); + match (self.interior.first(), maybe) { + (Some(i), Some(j)) if i == j => { + self.interior.take_first(); + self.parents -= 1; + }, + _ => break, + } + } + } + + /// Return the Location subsection identifying the chain that `self` points to. + pub fn chain_location(&self) -> Location { + let mut clone = self.clone(); + // start popping junctions until we reach chain identifier + while let Some(j) = clone.last() { + if matches!(j, Junction::Parachain(_) | Junction::GlobalConsensus(_)) { + // return chain subsection + return clone + } else { + (clone, _) = clone.split_last_interior(); + } + } + Location::new(clone.parents, Junctions::Here) + } +} + +impl Reanchorable for Location { + type Error = Self; + + /// Mutate `self` so that it represents the same location from the point of view of `target`. + /// The context of `self` is provided as `context`. + /// + /// Does not modify `self` in case of overflow. + fn reanchor(&mut self, target: &Location, context: &InteriorLocation) -> Result<(), ()> { + // TODO: https://github.com/paritytech/polkadot/issues/4489 Optimize this. + + // 1. Use our `context` to figure out how the `target` would address us. + let inverted_target = context.invert_target(target)?; + + // 2. Prepend `inverted_target` to `self` to get self's location from the perspective of + // `target`. + self.prepend_with(inverted_target).map_err(|_| ())?; + + // 3. Given that we know some of `target` context, ensure that any parents in `self` are + // strictly needed. + self.simplify(target.interior()); + + Ok(()) + } + + /// Consume `self` and return a new value representing the same location from the point of view + /// of `target`. The context of `self` is provided as `context`. + /// + /// Returns the original `self` in case of overflow. + fn reanchored( + mut self, + target: &Location, + context: &InteriorLocation, + ) -> Result { + match self.reanchor(target, context) { + Ok(()) => Ok(self), + Err(()) => Err(self), + } + } +} + +impl TryFrom for Option { + type Error = (); + fn try_from(value: OldLocation) -> result::Result { + Ok(Some(Location::try_from(value)?)) + } +} + +impl TryFrom for Location { + type Error = (); + fn try_from(x: OldLocation) -> result::Result { + Ok(Location { parents: x.parents, interior: x.interior.try_into()? }) + } +} + +/// A unit struct which can be converted into a `Location` of `parents` value 1. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub struct Parent; +impl From for Location { + fn from(_: Parent) -> Self { + Location { parents: 1, interior: Junctions::Here } + } +} + +/// A tuple struct which can be converted into a `Location` of `parents` value 1 with the inner +/// interior. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub struct ParentThen(pub Junctions); +impl From for Location { + fn from(ParentThen(interior): ParentThen) -> Self { + Location { parents: 1, interior } + } +} + +/// A unit struct which can be converted into a `Location` of the inner `parents` value. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub struct Ancestor(pub u8); +impl From for Location { + fn from(Ancestor(parents): Ancestor) -> Self { + Location { parents, interior: Junctions::Here } + } +} + +/// A unit struct which can be converted into a `Location` of the inner `parents` value and the +/// inner interior. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub struct AncestorThen(pub u8, pub Interior); +impl> From> for Location { + fn from(AncestorThen(parents, interior): AncestorThen) -> Self { + Location { parents, interior: interior.into() } + } +} + +xcm_procedural::impl_conversion_functions_for_location_v4!(); + +#[cfg(test)] +mod tests { + use crate::v4::prelude::*; + use parity_scale_codec::{Decode, Encode}; + + #[test] + fn conversion_works() { + let x: Location = Parent.into(); + assert_eq!(x, Location { parents: 1, interior: Here }); + // let x: Location = (Parent,).into(); + // assert_eq!(x, Location { parents: 1, interior: Here }); + // let x: Location = (Parent, Parent).into(); + // assert_eq!(x, Location { parents: 2, interior: Here }); + let x: Location = (Parent, Parent, OnlyChild).into(); + assert_eq!(x, Location { parents: 2, interior: OnlyChild.into() }); + let x: Location = OnlyChild.into(); + assert_eq!(x, Location { parents: 0, interior: OnlyChild.into() }); + let x: Location = (OnlyChild,).into(); + assert_eq!(x, Location { parents: 0, interior: OnlyChild.into() }); + } + + #[test] + fn simplify_basic_works() { + let mut location: Location = + (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); + let context = [Parachain(1000), PalletInstance(42)].into(); + let expected = GeneralIndex(69).into(); + location.simplify(&context); + assert_eq!(location, expected); + + let mut location: Location = (Parent, PalletInstance(42), GeneralIndex(69)).into(); + let context = [PalletInstance(42)].into(); + let expected = GeneralIndex(69).into(); + location.simplify(&context); + assert_eq!(location, expected); + + let mut location: Location = (Parent, PalletInstance(42), GeneralIndex(69)).into(); + let context = [Parachain(1000), PalletInstance(42)].into(); + let expected = GeneralIndex(69).into(); + location.simplify(&context); + assert_eq!(location, expected); + + let mut location: Location = + (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); + let context = [OnlyChild, Parachain(1000), PalletInstance(42)].into(); + let expected = GeneralIndex(69).into(); + location.simplify(&context); + assert_eq!(location, expected); + } + + #[test] + fn simplify_incompatible_location_fails() { + let mut location: Location = + (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); + let context = [Parachain(1000), PalletInstance(42), GeneralIndex(42)].into(); + let expected = + (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); + location.simplify(&context); + assert_eq!(location, expected); + + let mut location: Location = + (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); + let context = [Parachain(1000)].into(); + let expected = + (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); + location.simplify(&context); + assert_eq!(location, expected); + } + + #[test] + fn reanchor_works() { + let mut id: Location = (Parent, Parachain(1000), GeneralIndex(42)).into(); + let context = Parachain(2000).into(); + let target = (Parent, Parachain(1000)).into(); + let expected = GeneralIndex(42).into(); + id.reanchor(&target, &context).unwrap(); + assert_eq!(id, expected); + } + + #[test] + fn encode_and_decode_works() { + let m = Location { + parents: 1, + interior: [Parachain(42), AccountIndex64 { network: None, index: 23 }].into(), + }; + let encoded = m.encode(); + assert_eq!(encoded, [1, 2, 0, 168, 2, 0, 92].to_vec()); + let decoded = Location::decode(&mut &encoded[..]); + assert_eq!(decoded, Ok(m)); + } + + #[test] + fn match_and_split_works() { + let m = Location { + parents: 1, + interior: [Parachain(42), AccountIndex64 { network: None, index: 23 }].into(), + }; + assert_eq!(m.match_and_split(&Location { parents: 1, interior: Here }), None); + assert_eq!( + m.match_and_split(&Location { parents: 1, interior: [Parachain(42)].into() }), + Some(&AccountIndex64 { network: None, index: 23 }) + ); + assert_eq!(m.match_and_split(&m), None); + } + + #[test] + fn append_with_works() { + let acc = AccountIndex64 { network: None, index: 23 }; + let mut m = Location { parents: 1, interior: [Parachain(42)].into() }; + assert_eq!(m.append_with([PalletInstance(3), acc]), Ok(())); + assert_eq!( + m, + Location { parents: 1, interior: [Parachain(42), PalletInstance(3), acc].into() } + ); + + // cannot append to create overly long location + let acc = AccountIndex64 { network: None, index: 23 }; + let m = Location { + parents: 254, + interior: [Parachain(42), OnlyChild, OnlyChild, OnlyChild, OnlyChild].into(), + }; + let suffix: Location = (PalletInstance(3), acc, OnlyChild, OnlyChild).into(); + assert_eq!(m.clone().append_with(suffix.clone()), Err(suffix)); + } + + #[test] + fn prepend_with_works() { + let mut m = Location { + parents: 1, + interior: [Parachain(42), AccountIndex64 { network: None, index: 23 }].into(), + }; + assert_eq!(m.prepend_with(Location { parents: 1, interior: [OnlyChild].into() }), Ok(())); + assert_eq!( + m, + Location { + parents: 1, + interior: [Parachain(42), AccountIndex64 { network: None, index: 23 }].into() + } + ); + + // cannot prepend to create overly long location + let mut m = Location { parents: 254, interior: [Parachain(42)].into() }; + let prefix = Location { parents: 2, interior: Here }; + assert_eq!(m.prepend_with(prefix.clone()), Err(prefix)); + + let prefix = Location { parents: 1, interior: Here }; + assert_eq!(m.prepend_with(prefix.clone()), Ok(())); + assert_eq!(m, Location { parents: 255, interior: [Parachain(42)].into() }); + } + + #[test] + fn double_ended_ref_iteration_works() { + let m: Junctions = [Parachain(1000), Parachain(3), PalletInstance(5)].into(); + let mut iter = m.iter(); + + let first = iter.next().unwrap(); + assert_eq!(first, &Parachain(1000)); + let third = iter.next_back().unwrap(); + assert_eq!(third, &PalletInstance(5)); + let second = iter.next_back().unwrap(); + assert_eq!(iter.next(), None); + assert_eq!(iter.next_back(), None); + assert_eq!(second, &Parachain(3)); + + let res = Here + .pushed_with(*first) + .unwrap() + .pushed_with(*second) + .unwrap() + .pushed_with(*third) + .unwrap(); + assert_eq!(m, res); + + // make sure there's no funny business with the 0 indexing + let m = Here; + let mut iter = m.iter(); + + assert_eq!(iter.next(), None); + assert_eq!(iter.next_back(), None); + } + + #[test] + fn conversion_from_other_types_works() { + use crate::v3; + use core::convert::TryInto; + + fn takes_location>(_arg: Arg) {} + + takes_location(Parent); + takes_location(Here); + takes_location([Parachain(42)]); + takes_location((Ancestor(255), PalletInstance(8))); + takes_location((Ancestor(5), Parachain(1), PalletInstance(3))); + takes_location((Ancestor(2), Here)); + takes_location(AncestorThen( + 3, + [Parachain(43), AccountIndex64 { network: None, index: 155 }], + )); + takes_location((Parent, AccountId32 { network: None, id: [0; 32] })); + takes_location((Parent, Here)); + takes_location(ParentThen([Parachain(75)].into())); + takes_location([Parachain(100), PalletInstance(3)]); + + assert_eq!(v3::Location::from(v3::Junctions::Here).try_into(), Ok(Location::here())); + assert_eq!(v3::Location::from(v3::Parent).try_into(), Ok(Location::parent())); + assert_eq!( + v3::Location::from((v3::Parent, v3::Parent, v3::Junction::GeneralIndex(42u128),)) + .try_into(), + Ok(Location { parents: 2, interior: [GeneralIndex(42u128)].into() }), + ); + } +} diff --git a/polkadot/xcm/src/v4/mod.rs b/polkadot/xcm/src/v4/mod.rs new file mode 100644 index 000000000000..8e1e8d1ed9ea --- /dev/null +++ b/polkadot/xcm/src/v4/mod.rs @@ -0,0 +1,1428 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Substrate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Substrate is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! Version 4 of the Cross-Consensus Message format data structures. + +pub use super::v2::GetWeight; +use super::v3::{ + Instruction as OldInstruction, PalletInfo as OldPalletInfo, + QueryResponseInfo as OldQueryResponseInfo, Response as OldResponse, Xcm as OldXcm, +}; +use crate::DoubleEncoded; +use alloc::{vec, vec::Vec}; +use bounded_collections::{parameter_types, BoundedVec}; +use core::{ + convert::{TryFrom, TryInto}, + fmt::Debug, + result, +}; +use derivative::Derivative; +use parity_scale_codec::{self, Decode, Encode, MaxEncodedLen}; +use scale_info::TypeInfo; + +mod asset; +mod junction; +pub(crate) mod junctions; +mod location; +mod traits; + +pub use asset::{ + Asset, AssetFilter, AssetId, AssetInstance, Assets, Fungibility, WildAsset, WildFungibility, + MAX_ITEMS_IN_ASSETS, +}; +pub use junction::{BodyId, BodyPart, Junction, NetworkId}; +pub use junctions::{Junctions, HERE}; +pub use location::{Ancestor, AncestorThen, InteriorLocation, Location, Parent, ParentThen}; +pub use traits::{ + send_xcm, validate_send, Error, ExecuteXcm, Outcome, PreparedMessage, Result, SendError, + SendResult, SendXcm, Weight, XcmHash, Reanchorable, +}; +// These parts of XCM v3 are unchanged in XCM v4, and are re-imported here. +pub use super::v3::{MaybeErrorCode, OriginKind, WeightLimit}; + +/// This module's XCM version. +pub const VERSION: super::Version = 4; + +/// An identifier for a query. +pub type QueryId = u64; + +#[derive(Derivative, Default, Encode, Decode, TypeInfo)] +#[derivative(Clone(bound = ""), Eq(bound = ""), PartialEq(bound = ""), Debug(bound = ""))] +#[codec(encode_bound())] +#[codec(decode_bound())] +#[scale_info(bounds(), skip_type_params(Call))] +pub struct Xcm(pub Vec>); + +pub const MAX_INSTRUCTIONS_TO_DECODE: u8 = 100; + +impl Xcm { + /// Create an empty instance. + pub fn new() -> Self { + Self(vec![]) + } + + /// Return `true` if no instructions are held in `self`. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Return the number of instructions held in `self`. + pub fn len(&self) -> usize { + self.0.len() + } + + /// Return a reference to the inner value. + pub fn inner(&self) -> &[Instruction] { + &self.0 + } + + /// Return a mutable reference to the inner value. + pub fn inner_mut(&mut self) -> &mut Vec> { + &mut self.0 + } + + /// Consume and return the inner value. + pub fn into_inner(self) -> Vec> { + self.0 + } + + /// Return an iterator over references to the items. + pub fn iter(&self) -> impl Iterator> { + self.0.iter() + } + + /// Return an iterator over mutable references to the items. + pub fn iter_mut(&mut self) -> impl Iterator> { + self.0.iter_mut() + } + + /// Consume and return an iterator over the items. + pub fn into_iter(self) -> impl Iterator> { + self.0.into_iter() + } + + /// Consume and either return `self` if it contains some instructions, or if it's empty, then + /// instead return the result of `f`. + pub fn or_else(self, f: impl FnOnce() -> Self) -> Self { + if self.0.is_empty() { + f() + } else { + self + } + } + + /// Return the first instruction, if any. + pub fn first(&self) -> Option<&Instruction> { + self.0.first() + } + + /// Return the last instruction, if any. + pub fn last(&self) -> Option<&Instruction> { + self.0.last() + } + + /// Return the only instruction, contained in `Self`, iff only one exists (`None` otherwise). + pub fn only(&self) -> Option<&Instruction> { + if self.0.len() == 1 { + self.0.first() + } else { + None + } + } + + /// Return the only instruction, contained in `Self`, iff only one exists (returns `self` + /// otherwise). + pub fn into_only(mut self) -> core::result::Result, Self> { + if self.0.len() == 1 { + self.0.pop().ok_or(self) + } else { + Err(self) + } + } +} + +impl From>> for Xcm { + fn from(c: Vec>) -> Self { + Self(c) + } +} + +impl From> for Vec> { + fn from(c: Xcm) -> Self { + c.0 + } +} + +/// A prelude for importing all types typically used when interacting with XCM messages. +pub mod prelude { + mod contents { + pub use super::super::{ + send_xcm, validate_send, Ancestor, AncestorThen, Asset, + AssetFilter::{self, *}, + AssetId, + AssetInstance::{self, *}, + Assets, BodyId, BodyPart, Error as XcmError, ExecuteXcm, + Fungibility::{self, *}, + Instruction::*, + InteriorLocation, + Junction::{self, *}, + Junctions::{self, Here}, + HERE, + Location, MaybeErrorCode, + NetworkId::{self, *}, + OriginKind, Outcome, PalletInfo, Parent, ParentThen, PreparedMessage, QueryId, + QueryResponseInfo, Reanchorable, Response, Result as XcmResult, SendError, SendResult, SendXcm, + Weight, + WeightLimit::{self, *}, + WildAsset::{self, *}, + WildFungibility::{self, Fungible as WildFungible, NonFungible as WildNonFungible}, + XcmContext, XcmHash, XcmWeightInfo, VERSION as XCM_VERSION, + }; + } + pub use super::{Instruction, Xcm}; + pub use contents::*; + pub mod opaque { + pub use super::{ + super::opaque::{Instruction, Xcm}, + contents::*, + }; + } +} + +parameter_types! { + pub MaxPalletNameLen: u32 = 48; + /// Maximum size of the encoded error code coming from a `Dispatch` result, used for + /// `MaybeErrorCode`. This is not (yet) enforced, so it's just an indication of expectation. + pub MaxDispatchErrorLen: u32 = 128; + pub MaxPalletsInfo: u32 = 64; +} + +#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] +pub struct PalletInfo { + #[codec(compact)] + index: u32, + name: BoundedVec, + module_name: BoundedVec, + #[codec(compact)] + major: u32, + #[codec(compact)] + minor: u32, + #[codec(compact)] + patch: u32, +} + +impl TryInto for PalletInfo { + type Error = (); + + fn try_into(self) -> result::Result { + OldPalletInfo::new( + self.index, + self.name.into_inner(), + self.module_name.into_inner(), + self.major, + self.minor, + self.patch, + ) + .map_err(|_| ()) + } +} + +impl PalletInfo { + pub fn new( + index: u32, + name: Vec, + module_name: Vec, + major: u32, + minor: u32, + patch: u32, + ) -> result::Result { + let name = BoundedVec::try_from(name).map_err(|_| Error::Overflow)?; + let module_name = BoundedVec::try_from(module_name).map_err(|_| Error::Overflow)?; + + Ok(Self { index, name, module_name, major, minor, patch }) + } +} + +/// Response data to a query. +#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] +pub enum Response { + /// No response. Serves as a neutral default. + Null, + /// Some assets. + Assets(Assets), + /// The outcome of an XCM instruction. + ExecutionResult(Option<(u32, Error)>), + /// An XCM version. + Version(super::Version), + /// The index, instance name, pallet name and version of some pallets. + PalletsInfo(BoundedVec), + /// The status of a dispatch attempt using `Transact`. + DispatchResult(MaybeErrorCode), +} + +impl Default for Response { + fn default() -> Self { + Self::Null + } +} + +impl TryFrom for Response { + type Error = (); + + fn try_from(old: OldResponse) -> result::Result { + use OldResponse::*; + Ok(match old { + Null => Self::Null, + Assets(assets) => Self::Assets(assets.try_into()?), + ExecutionResult(result) => + Self::ExecutionResult(result.map(|(num, old_error)| (num, old_error.into()))), + Version(version) => Self::Version(version), + PalletsInfo(pallet_info) => { + let inner = pallet_info + .into_iter() + .map(TryInto::try_into) + .collect::, _>>()?; + Self::PalletsInfo( + BoundedVec::::try_from(inner).map_err(|_| ())?, + ) + }, + DispatchResult(maybe_error) => Self::DispatchResult(maybe_error), + }) + } +} + +/// Information regarding the composition of a query response. +#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)] +pub struct QueryResponseInfo { + /// The destination to which the query response message should be send. + pub destination: Location, + /// The `query_id` field of the `QueryResponse` message. + #[codec(compact)] + pub query_id: QueryId, + /// The `max_weight` field of the `QueryResponse` message. + pub max_weight: Weight, +} + +impl TryFrom for QueryResponseInfo { + type Error = (); + + fn try_from(old: OldQueryResponseInfo) -> result::Result { + Ok(Self { + destination: old.destination.try_into()?, + query_id: old.query_id, + max_weight: old.max_weight, + }) + } +} + +/// Contextual data pertaining to a specific list of XCM instructions. +#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug)] +pub struct XcmContext { + /// The current value of the Origin register of the `XCVM`. + pub origin: Option, + /// The identity of the XCM; this may be a hash of its versioned encoding but could also be + /// a high-level identity set by an appropriate barrier. + pub message_id: XcmHash, + /// The current value of the Topic register of the `XCVM`. + pub topic: Option<[u8; 32]>, +} + +impl XcmContext { + /// Constructor which sets the message ID to the supplied parameter and leaves the origin and + /// topic unset. + #[deprecated = "Use `with_message_id` instead."] + pub fn with_message_hash(message_id: XcmHash) -> XcmContext { + XcmContext { origin: None, message_id, topic: None } + } + + /// Constructor which sets the message ID to the supplied parameter and leaves the origin and + /// topic unset. + pub fn with_message_id(message_id: XcmHash) -> XcmContext { + XcmContext { origin: None, message_id, topic: None } + } +} + +/// Cross-Consensus Message: A message from one consensus system to another. +/// +/// Consensus systems that may send and receive messages include blockchains and smart contracts. +/// +/// All messages are delivered from a known *origin*, expressed as a `Location`. +/// +/// This is the inner XCM format and is version-sensitive. Messages are typically passed using the +/// outer XCM format, known as `VersionedXcm`. +#[derive(Derivative, Encode, Decode, TypeInfo, xcm_procedural::XcmWeightInfoTrait)] +#[derivative(Clone(bound = ""), Eq(bound = ""), PartialEq(bound = ""), Debug(bound = ""))] +#[codec(encode_bound())] +#[codec(decode_bound())] +#[scale_info(bounds(), skip_type_params(Call))] +pub enum Instruction { + /// Withdraw asset(s) (`assets`) from the ownership of `origin` and place them into the Holding + /// Register. + /// + /// - `assets`: The asset(s) to be withdrawn into holding. + /// + /// Kind: *Command*. + /// + /// Errors: + WithdrawAsset(Assets), + + /// Asset(s) (`assets`) have been received into the ownership of this system on the `origin` + /// system and equivalent derivatives should be placed into the Holding Register. + /// + /// - `assets`: The asset(s) that are minted into holding. + /// + /// Safety: `origin` must be trusted to have received and be storing `assets` such that they + /// may later be withdrawn should this system send a corresponding message. + /// + /// Kind: *Trusted Indication*. + /// + /// Errors: + ReserveAssetDeposited(Assets), + + /// Asset(s) (`assets`) have been destroyed on the `origin` system and equivalent assets should + /// be created and placed into the Holding Register. + /// + /// - `assets`: The asset(s) that are minted into the Holding Register. + /// + /// Safety: `origin` must be trusted to have irrevocably destroyed the corresponding `assets` + /// prior as a consequence of sending this message. + /// + /// Kind: *Trusted Indication*. + /// + /// Errors: + ReceiveTeleportedAsset(Assets), + + /// Respond with information that the local system is expecting. + /// + /// - `query_id`: The identifier of the query that resulted in this message being sent. + /// - `response`: The message content. + /// - `max_weight`: The maximum weight that handling this response should take. + /// - `querier`: The location responsible for the initiation of the response, if there is one. + /// In general this will tend to be the same location as the receiver of this message. NOTE: + /// As usual, this is interpreted from the perspective of the receiving consensus system. + /// + /// Safety: Since this is information only, there are no immediate concerns. However, it should + /// be remembered that even if the Origin behaves reasonably, it can always be asked to make + /// a response to a third-party chain who may or may not be expecting the response. Therefore + /// the `querier` should be checked to match the expected value. + /// + /// Kind: *Information*. + /// + /// Errors: + QueryResponse { + #[codec(compact)] + query_id: QueryId, + response: Response, + max_weight: Weight, + querier: Option, + }, + + /// Withdraw asset(s) (`assets`) from the ownership of `origin` and place equivalent assets + /// under the ownership of `beneficiary`. + /// + /// - `assets`: The asset(s) to be withdrawn. + /// - `beneficiary`: The new owner for the assets. + /// + /// Safety: No concerns. + /// + /// Kind: *Command*. + /// + /// Errors: + TransferAsset { assets: Assets, beneficiary: Location }, + + /// Withdraw asset(s) (`assets`) from the ownership of `origin` and place equivalent assets + /// under the ownership of `dest` within this consensus system (i.e. its sovereign account). + /// + /// Send an onward XCM message to `dest` of `ReserveAssetDeposited` with the given + /// `xcm`. + /// + /// - `assets`: The asset(s) to be withdrawn. + /// - `dest`: The location whose sovereign account will own the assets and thus the effective + /// beneficiary for the assets and the notification target for the reserve asset deposit + /// message. + /// - `xcm`: The instructions that should follow the `ReserveAssetDeposited` instruction, which + /// is sent onwards to `dest`. + /// + /// Safety: No concerns. + /// + /// Kind: *Command*. + /// + /// Errors: + TransferReserveAsset { assets: Assets, dest: Location, xcm: Xcm<()> }, + + /// Apply the encoded transaction `call`, whose dispatch-origin should be `origin` as expressed + /// by the kind of origin `origin_kind`. + /// + /// The Transact Status Register is set according to the result of dispatching the call. + /// + /// - `origin_kind`: The means of expressing the message origin as a dispatch origin. + /// - `require_weight_at_most`: The weight of `call`; this should be at least the chain's + /// calculated weight and will be used in the weight determination arithmetic. + /// - `call`: The encoded transaction to be applied. + /// + /// Safety: No concerns. + /// + /// Kind: *Command*. + /// + /// Errors: + Transact { origin_kind: OriginKind, require_weight_at_most: Weight, call: DoubleEncoded }, + + /// A message to notify about a new incoming HRMP channel. This message is meant to be sent by + /// the relay-chain to a para. + /// + /// - `sender`: The sender in the to-be opened channel. Also, the initiator of the channel + /// opening. + /// - `max_message_size`: The maximum size of a message proposed by the sender. + /// - `max_capacity`: The maximum number of messages that can be queued in the channel. + /// + /// Safety: The message should originate directly from the relay-chain. + /// + /// Kind: *System Notification* + HrmpNewChannelOpenRequest { + #[codec(compact)] + sender: u32, + #[codec(compact)] + max_message_size: u32, + #[codec(compact)] + max_capacity: u32, + }, + + /// A message to notify about that a previously sent open channel request has been accepted by + /// the recipient. That means that the channel will be opened during the next relay-chain + /// session change. This message is meant to be sent by the relay-chain to a para. + /// + /// Safety: The message should originate directly from the relay-chain. + /// + /// Kind: *System Notification* + /// + /// Errors: + HrmpChannelAccepted { + // NOTE: We keep this as a structured item to a) keep it consistent with the other Hrmp + // items; and b) because the field's meaning is not obvious/mentioned from the item name. + #[codec(compact)] + recipient: u32, + }, + + /// A message to notify that the other party in an open channel decided to close it. In + /// particular, `initiator` is going to close the channel opened from `sender` to the + /// `recipient`. The close will be enacted at the next relay-chain session change. This message + /// is meant to be sent by the relay-chain to a para. + /// + /// Safety: The message should originate directly from the relay-chain. + /// + /// Kind: *System Notification* + /// + /// Errors: + HrmpChannelClosing { + #[codec(compact)] + initiator: u32, + #[codec(compact)] + sender: u32, + #[codec(compact)] + recipient: u32, + }, + + /// Clear the origin. + /// + /// This may be used by the XCM author to ensure that later instructions cannot command the + /// authority of the origin (e.g. if they are being relayed from an untrusted source, as often + /// the case with `ReserveAssetDeposited`). + /// + /// Safety: No concerns. + /// + /// Kind: *Command*. + /// + /// Errors: + ClearOrigin, + + /// Mutate the origin to some interior location. + /// + /// Kind: *Command* + /// + /// Errors: + DescendOrigin(InteriorLocation), + + /// Immediately report the contents of the Error Register to the given destination via XCM. + /// + /// A `QueryResponse` message of type `ExecutionOutcome` is sent to the described destination. + /// + /// - `response_info`: Information for making the response. + /// + /// Kind: *Command* + /// + /// Errors: + ReportError(QueryResponseInfo), + + /// Remove the asset(s) (`assets`) from the Holding Register and place equivalent assets under + /// the ownership of `beneficiary` within this consensus system. + /// + /// - `assets`: The asset(s) to remove from holding. + /// - `beneficiary`: The new owner for the assets. + /// + /// Kind: *Command* + /// + /// Errors: + DepositAsset { assets: AssetFilter, beneficiary: Location }, + + /// Remove the asset(s) (`assets`) from the Holding Register and place equivalent assets under + /// the ownership of `dest` within this consensus system (i.e. deposit them into its sovereign + /// account). + /// + /// Send an onward XCM message to `dest` of `ReserveAssetDeposited` with the given `effects`. + /// + /// - `assets`: The asset(s) to remove from holding. + /// - `dest`: The location whose sovereign account will own the assets and thus the effective + /// beneficiary for the assets and the notification target for the reserve asset deposit + /// message. + /// - `xcm`: The orders that should follow the `ReserveAssetDeposited` instruction which is + /// sent onwards to `dest`. + /// + /// Kind: *Command* + /// + /// Errors: + DepositReserveAsset { assets: AssetFilter, dest: Location, xcm: Xcm<()> }, + + /// Remove the asset(s) (`want`) from the Holding Register and replace them with alternative + /// assets. + /// + /// The minimum amount of assets to be received into the Holding Register for the order not to + /// fail may be stated. + /// + /// - `give`: The maximum amount of assets to remove from holding. + /// - `want`: The minimum amount of assets which `give` should be exchanged for. + /// - `maximal`: If `true`, then prefer to give as much as possible up to the limit of `give` + /// and receive accordingly more. If `false`, then prefer to give as little as possible in + /// order to receive as little as possible while receiving at least `want`. + /// + /// Kind: *Command* + /// + /// Errors: + ExchangeAsset { give: AssetFilter, want: Assets, maximal: bool }, + + /// Remove the asset(s) (`assets`) from holding and send a `WithdrawAsset` XCM message to a + /// reserve location. + /// + /// - `assets`: The asset(s) to remove from holding. + /// - `reserve`: A valid location that acts as a reserve for all asset(s) in `assets`. The + /// sovereign account of this consensus system *on the reserve location* will have + /// appropriate assets withdrawn and `effects` will be executed on them. There will typically + /// be only one valid location on any given asset/chain combination. + /// - `xcm`: The instructions to execute on the assets once withdrawn *on the reserve + /// location*. + /// + /// Kind: *Command* + /// + /// Errors: + InitiateReserveWithdraw { assets: AssetFilter, reserve: Location, xcm: Xcm<()> }, + + /// Remove the asset(s) (`assets`) from holding and send a `ReceiveTeleportedAsset` XCM message + /// to a `dest` location. + /// + /// - `assets`: The asset(s) to remove from holding. + /// - `dest`: A valid location that respects teleports coming from this location. + /// - `xcm`: The instructions to execute on the assets once arrived *on the destination + /// location*. + /// + /// NOTE: The `dest` location *MUST* respect this origin as a valid teleportation origin for + /// all `assets`. If it does not, then the assets may be lost. + /// + /// Kind: *Command* + /// + /// Errors: + InitiateTeleport { assets: AssetFilter, dest: Location, xcm: Xcm<()> }, + + /// Report to a given destination the contents of the Holding Register. + /// + /// A `QueryResponse` message of type `Assets` is sent to the described destination. + /// + /// - `response_info`: Information for making the response. + /// - `assets`: A filter for the assets that should be reported back. The assets reported back + /// will be, asset-wise, *the lesser of this value and the holding register*. No wildcards + /// will be used when reporting assets back. + /// + /// Kind: *Command* + /// + /// Errors: + ReportHolding { response_info: QueryResponseInfo, assets: AssetFilter }, + + /// Pay for the execution of some XCM `xcm` and `orders` with up to `weight` + /// picoseconds of execution time, paying for this with up to `fees` from the Holding Register. + /// + /// - `fees`: The asset(s) to remove from the Holding Register to pay for fees. + /// - `weight_limit`: The maximum amount of weight to purchase; this must be at least the + /// expected maximum weight of the total XCM to be executed for the + /// `AllowTopLevelPaidExecutionFrom` barrier to allow the XCM be executed. + /// + /// Kind: *Command* + /// + /// Errors: + BuyExecution { fees: Asset, weight_limit: WeightLimit }, + + /// Refund any surplus weight previously bought with `BuyExecution`. + /// + /// Kind: *Command* + /// + /// Errors: None. + RefundSurplus, + + /// Set the Error Handler Register. This is code that should be called in the case of an error + /// happening. + /// + /// An error occurring within execution of this code will _NOT_ result in the error register + /// being set, nor will an error handler be called due to it. The error handler and appendix + /// may each still be set. + /// + /// The apparent weight of this instruction is inclusive of the inner `Xcm`; the executing + /// weight however includes only the difference between the previous handler and the new + /// handler, which can reasonably be negative, which would result in a surplus. + /// + /// Kind: *Command* + /// + /// Errors: None. + SetErrorHandler(Xcm), + + /// Set the Appendix Register. This is code that should be called after code execution + /// (including the error handler if any) is finished. This will be called regardless of whether + /// an error occurred. + /// + /// Any error occurring due to execution of this code will result in the error register being + /// set, and the error handler (if set) firing. + /// + /// The apparent weight of this instruction is inclusive of the inner `Xcm`; the executing + /// weight however includes only the difference between the previous appendix and the new + /// appendix, which can reasonably be negative, which would result in a surplus. + /// + /// Kind: *Command* + /// + /// Errors: None. + SetAppendix(Xcm), + + /// Clear the Error Register. + /// + /// Kind: *Command* + /// + /// Errors: None. + ClearError, + + /// Create some assets which are being held on behalf of the origin. + /// + /// - `assets`: The assets which are to be claimed. This must match exactly with the assets + /// claimable by the origin of the ticket. + /// - `ticket`: The ticket of the asset; this is an abstract identifier to help locate the + /// asset. + /// + /// Kind: *Command* + /// + /// Errors: + ClaimAsset { assets: Assets, ticket: Location }, + + /// Always throws an error of type `Trap`. + /// + /// Kind: *Command* + /// + /// Errors: + /// - `Trap`: All circumstances, whose inner value is the same as this item's inner value. + Trap(#[codec(compact)] u64), + + /// Ask the destination system to respond with the most recent version of XCM that they + /// support in a `QueryResponse` instruction. Any changes to this should also elicit similar + /// responses when they happen. + /// + /// - `query_id`: An identifier that will be replicated into the returned XCM message. + /// - `max_response_weight`: The maximum amount of weight that the `QueryResponse` item which + /// is sent as a reply may take to execute. NOTE: If this is unexpectedly large then the + /// response may not execute at all. + /// + /// Kind: *Command* + /// + /// Errors: *Fallible* + SubscribeVersion { + #[codec(compact)] + query_id: QueryId, + max_response_weight: Weight, + }, + + /// Cancel the effect of a previous `SubscribeVersion` instruction. + /// + /// Kind: *Command* + /// + /// Errors: *Fallible* + UnsubscribeVersion, + + /// Reduce Holding by up to the given assets. + /// + /// Holding is reduced by as much as possible up to the assets in the parameter. It is not an + /// error if the Holding does not contain the assets (to make this an error, use `ExpectAsset` + /// prior). + /// + /// Kind: *Command* + /// + /// Errors: *Infallible* + BurnAsset(Assets), + + /// Throw an error if Holding does not contain at least the given assets. + /// + /// Kind: *Command* + /// + /// Errors: + /// - `ExpectationFalse`: If Holding Register does not contain the assets in the parameter. + ExpectAsset(Assets), + + /// Ensure that the Origin Register equals some given value and throw an error if not. + /// + /// Kind: *Command* + /// + /// Errors: + /// - `ExpectationFalse`: If Origin Register is not equal to the parameter. + ExpectOrigin(Option), + + /// Ensure that the Error Register equals some given value and throw an error if not. + /// + /// Kind: *Command* + /// + /// Errors: + /// - `ExpectationFalse`: If the value of the Error Register is not equal to the parameter. + ExpectError(Option<(u32, Error)>), + + /// Ensure that the Transact Status Register equals some given value and throw an error if + /// not. + /// + /// Kind: *Command* + /// + /// Errors: + /// - `ExpectationFalse`: If the value of the Transact Status Register is not equal to the + /// parameter. + ExpectTransactStatus(MaybeErrorCode), + + /// Query the existence of a particular pallet type. + /// + /// - `module_name`: The module name of the pallet to query. + /// - `response_info`: Information for making the response. + /// + /// Sends a `QueryResponse` to Origin whose data field `PalletsInfo` containing the information + /// of all pallets on the local chain whose name is equal to `name`. This is empty in the case + /// that the local chain is not based on Substrate Frame. + /// + /// Safety: No concerns. + /// + /// Kind: *Command* + /// + /// Errors: *Fallible*. + QueryPallet { module_name: Vec, response_info: QueryResponseInfo }, + + /// Ensure that a particular pallet with a particular version exists. + /// + /// - `index: Compact`: The index which identifies the pallet. An error if no pallet exists at + /// this index. + /// - `name: Vec`: Name which must be equal to the name of the pallet. + /// - `module_name: Vec`: Module name which must be equal to the name of the module in + /// which the pallet exists. + /// - `crate_major: Compact`: Version number which must be equal to the major version of the + /// crate which implements the pallet. + /// - `min_crate_minor: Compact`: Version number which must be at most the minor version of the + /// crate which implements the pallet. + /// + /// Safety: No concerns. + /// + /// Kind: *Command* + /// + /// Errors: + /// - `ExpectationFalse`: In case any of the expectations are broken. + ExpectPallet { + #[codec(compact)] + index: u32, + name: Vec, + module_name: Vec, + #[codec(compact)] + crate_major: u32, + #[codec(compact)] + min_crate_minor: u32, + }, + + /// Send a `QueryResponse` message containing the value of the Transact Status Register to some + /// destination. + /// + /// - `query_response_info`: The information needed for constructing and sending the + /// `QueryResponse` message. + /// + /// Safety: No concerns. + /// + /// Kind: *Command* + /// + /// Errors: *Fallible*. + ReportTransactStatus(QueryResponseInfo), + + /// Set the Transact Status Register to its default, cleared, value. + /// + /// Safety: No concerns. + /// + /// Kind: *Command* + /// + /// Errors: *Infallible*. + ClearTransactStatus, + + /// Set the Origin Register to be some child of the Universal Ancestor. + /// + /// Safety: Should only be usable if the Origin is trusted to represent the Universal Ancestor + /// child in general. In general, no Origin should be able to represent the Universal Ancestor + /// child which is the root of the local consensus system since it would by extension + /// allow it to act as any location within the local consensus. + /// + /// The `Junction` parameter should generally be a `GlobalConsensus` variant since it is only + /// these which are children of the Universal Ancestor. + /// + /// Kind: *Command* + /// + /// Errors: *Fallible*. + UniversalOrigin(Junction), + + /// Send a message on to Non-Local Consensus system. + /// + /// This will tend to utilize some extra-consensus mechanism, the obvious one being a bridge. + /// A fee may be charged; this may be determined based on the contents of `xcm`. It will be + /// taken from the Holding register. + /// + /// - `network`: The remote consensus system to which the message should be exported. + /// - `destination`: The location relative to the remote consensus system to which the message + /// should be sent on arrival. + /// - `xcm`: The message to be exported. + /// + /// As an example, to export a message for execution on Statemine (parachain #1000 in the + /// Kusama network), you would call with `network: NetworkId::Kusama` and + /// `destination: [Parachain(1000)].into()`. Alternatively, to export a message for execution + /// on Polkadot, you would call with `network: NetworkId:: Polkadot` and `destination: Here`. + /// + /// Kind: *Command* + /// + /// Errors: *Fallible*. + ExportMessage { network: NetworkId, destination: InteriorLocation, xcm: Xcm<()> }, + + /// Lock the locally held asset and prevent further transfer or withdrawal. + /// + /// This restriction may be removed by the `UnlockAsset` instruction being called with an + /// Origin of `unlocker` and a `target` equal to the current `Origin`. + /// + /// If the locking is successful, then a `NoteUnlockable` instruction is sent to `unlocker`. + /// + /// - `asset`: The asset(s) which should be locked. + /// - `unlocker`: The value which the Origin must be for a corresponding `UnlockAsset` + /// instruction to work. + /// + /// Kind: *Command*. + /// + /// Errors: + LockAsset { asset: Asset, unlocker: Location }, + + /// Remove the lock over `asset` on this chain and (if nothing else is preventing it) allow the + /// asset to be transferred. + /// + /// - `asset`: The asset to be unlocked. + /// - `target`: The owner of the asset on the local chain. + /// + /// Safety: No concerns. + /// + /// Kind: *Command*. + /// + /// Errors: + UnlockAsset { asset: Asset, target: Location }, + + /// Asset (`asset`) has been locked on the `origin` system and may not be transferred. It may + /// only be unlocked with the receipt of the `UnlockAsset` instruction from this chain. + /// + /// - `asset`: The asset(s) which are now unlockable from this origin. + /// - `owner`: The owner of the asset on the chain in which it was locked. This may be a + /// location specific to the origin network. + /// + /// Safety: `origin` must be trusted to have locked the corresponding `asset` + /// prior as a consequence of sending this message. + /// + /// Kind: *Trusted Indication*. + /// + /// Errors: + NoteUnlockable { asset: Asset, owner: Location }, + + /// Send an `UnlockAsset` instruction to the `locker` for the given `asset`. + /// + /// This may fail if the local system is making use of the fact that the asset is locked or, + /// of course, if there is no record that the asset actually is locked. + /// + /// - `asset`: The asset(s) to be unlocked. + /// - `locker`: The location from which a previous `NoteUnlockable` was sent and to which an + /// `UnlockAsset` should be sent. + /// + /// Kind: *Command*. + /// + /// Errors: + RequestUnlock { asset: Asset, locker: Location }, + + /// Sets the Fees Mode Register. + /// + /// - `jit_withdraw`: The fees mode item; if set to `true` then fees for any instructions are + /// withdrawn as needed using the same mechanism as `WithdrawAssets`. + /// + /// Kind: *Command*. + /// + /// Errors: + SetFeesMode { jit_withdraw: bool }, + + /// Set the Topic Register. + /// + /// The 32-byte array identifier in the parameter is not guaranteed to be + /// unique; if such a property is desired, it is up to the code author to + /// enforce uniqueness. + /// + /// Safety: No concerns. + /// + /// Kind: *Command* + /// + /// Errors: + SetTopic([u8; 32]), + + /// Clear the Topic Register. + /// + /// Kind: *Command* + /// + /// Errors: None. + ClearTopic, + + /// Alter the current Origin to another given origin. + /// + /// Kind: *Command* + /// + /// Errors: If the existing state would not allow such a change. + AliasOrigin(Location), + + /// A directive to indicate that the origin expects free execution of the message. + /// + /// At execution time, this instruction just does a check on the Origin register. + /// However, at the barrier stage messages starting with this instruction can be disregarded if + /// the origin is not acceptable for free execution or the `weight_limit` is `Limited` and + /// insufficient. + /// + /// Kind: *Indication* + /// + /// Errors: If the given origin is `Some` and not equal to the current Origin register. + UnpaidExecution { weight_limit: WeightLimit, check_origin: Option }, + + /// A directive to indicate some arbitrary key value pair wants to be published somewhere. + Publish { data: Vec, Vec> }, +} + +impl Xcm { + pub fn into(self) -> Xcm { + Xcm::from(self) + } + pub fn from(xcm: Xcm) -> Self { + Self(xcm.0.into_iter().map(Instruction::::from).collect()) + } +} + +impl Instruction { + pub fn into(self) -> Instruction { + Instruction::from(self) + } + pub fn from(xcm: Instruction) -> Self { + use Instruction::*; + match xcm { + WithdrawAsset(assets) => WithdrawAsset(assets), + ReserveAssetDeposited(assets) => ReserveAssetDeposited(assets), + ReceiveTeleportedAsset(assets) => ReceiveTeleportedAsset(assets), + QueryResponse { query_id, response, max_weight, querier } => + QueryResponse { query_id, response, max_weight, querier }, + TransferAsset { assets, beneficiary } => TransferAsset { assets, beneficiary }, + TransferReserveAsset { assets, dest, xcm } => + TransferReserveAsset { assets, dest, xcm }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, + HrmpChannelAccepted { recipient } => HrmpChannelAccepted { recipient }, + HrmpChannelClosing { initiator, sender, recipient } => + HrmpChannelClosing { initiator, sender, recipient }, + Transact { origin_kind, require_weight_at_most, call } => + Transact { origin_kind, require_weight_at_most, call: call.into() }, + ReportError(response_info) => ReportError(response_info), + DepositAsset { assets, beneficiary } => DepositAsset { assets, beneficiary }, + DepositReserveAsset { assets, dest, xcm } => DepositReserveAsset { assets, dest, xcm }, + ExchangeAsset { give, want, maximal } => ExchangeAsset { give, want, maximal }, + InitiateReserveWithdraw { assets, reserve, xcm } => + InitiateReserveWithdraw { assets, reserve, xcm }, + InitiateTeleport { assets, dest, xcm } => InitiateTeleport { assets, dest, xcm }, + ReportHolding { response_info, assets } => ReportHolding { response_info, assets }, + BuyExecution { fees, weight_limit } => BuyExecution { fees, weight_limit }, + ClearOrigin => ClearOrigin, + DescendOrigin(who) => DescendOrigin(who), + RefundSurplus => RefundSurplus, + SetErrorHandler(xcm) => SetErrorHandler(xcm.into()), + SetAppendix(xcm) => SetAppendix(xcm.into()), + ClearError => ClearError, + ClaimAsset { assets, ticket } => ClaimAsset { assets, ticket }, + Trap(code) => Trap(code), + SubscribeVersion { query_id, max_response_weight } => + SubscribeVersion { query_id, max_response_weight }, + UnsubscribeVersion => UnsubscribeVersion, + BurnAsset(assets) => BurnAsset(assets), + ExpectAsset(assets) => ExpectAsset(assets), + ExpectOrigin(origin) => ExpectOrigin(origin), + ExpectError(error) => ExpectError(error), + ExpectTransactStatus(transact_status) => ExpectTransactStatus(transact_status), + QueryPallet { module_name, response_info } => + QueryPallet { module_name, response_info }, + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => + ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, + ReportTransactStatus(response_info) => ReportTransactStatus(response_info), + ClearTransactStatus => ClearTransactStatus, + UniversalOrigin(j) => UniversalOrigin(j), + ExportMessage { network, destination, xcm } => + ExportMessage { network, destination, xcm }, + LockAsset { asset, unlocker } => LockAsset { asset, unlocker }, + UnlockAsset { asset, target } => UnlockAsset { asset, target }, + NoteUnlockable { asset, owner } => NoteUnlockable { asset, owner }, + RequestUnlock { asset, locker } => RequestUnlock { asset, locker }, + SetFeesMode { jit_withdraw } => SetFeesMode { jit_withdraw }, + SetTopic(topic) => SetTopic(topic), + ClearTopic => ClearTopic, + AliasOrigin(location) => AliasOrigin(location), + UnpaidExecution { weight_limit, check_origin } => + UnpaidExecution { weight_limit, check_origin }, + } + } +} + +// TODO: Automate Generation +impl> GetWeight for Instruction { + fn weight(&self) -> Weight { + use Instruction::*; + match self { + WithdrawAsset(assets) => W::withdraw_asset(assets), + ReserveAssetDeposited(assets) => W::reserve_asset_deposited(assets), + ReceiveTeleportedAsset(assets) => W::receive_teleported_asset(assets), + QueryResponse { query_id, response, max_weight, querier } => + W::query_response(query_id, response, max_weight, querier), + TransferAsset { assets, beneficiary } => W::transfer_asset(assets, beneficiary), + TransferReserveAsset { assets, dest, xcm } => + W::transfer_reserve_asset(&assets, dest, xcm), + Transact { origin_kind, require_weight_at_most, call } => + W::transact(origin_kind, require_weight_at_most, call), + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => + W::hrmp_new_channel_open_request(sender, max_message_size, max_capacity), + HrmpChannelAccepted { recipient } => W::hrmp_channel_accepted(recipient), + HrmpChannelClosing { initiator, sender, recipient } => + W::hrmp_channel_closing(initiator, sender, recipient), + ClearOrigin => W::clear_origin(), + DescendOrigin(who) => W::descend_origin(who), + ReportError(response_info) => W::report_error(&response_info), + DepositAsset { assets, beneficiary } => W::deposit_asset(assets, beneficiary), + DepositReserveAsset { assets, dest, xcm } => + W::deposit_reserve_asset(assets, dest, xcm), + ExchangeAsset { give, want, maximal } => W::exchange_asset(give, want, maximal), + InitiateReserveWithdraw { assets, reserve, xcm } => + W::initiate_reserve_withdraw(assets, reserve, xcm), + InitiateTeleport { assets, dest, xcm } => W::initiate_teleport(assets, dest, xcm), + ReportHolding { response_info, assets } => W::report_holding(&response_info, &assets), + BuyExecution { fees, weight_limit } => W::buy_execution(fees, weight_limit), + RefundSurplus => W::refund_surplus(), + SetErrorHandler(xcm) => W::set_error_handler(xcm), + SetAppendix(xcm) => W::set_appendix(xcm), + ClearError => W::clear_error(), + ClaimAsset { assets, ticket } => W::claim_asset(assets, ticket), + Trap(code) => W::trap(code), + SubscribeVersion { query_id, max_response_weight } => + W::subscribe_version(query_id, max_response_weight), + UnsubscribeVersion => W::unsubscribe_version(), + BurnAsset(assets) => W::burn_asset(assets), + ExpectAsset(assets) => W::expect_asset(assets), + ExpectOrigin(origin) => W::expect_origin(origin), + ExpectError(error) => W::expect_error(error), + ExpectTransactStatus(transact_status) => W::expect_transact_status(transact_status), + QueryPallet { module_name, response_info } => + W::query_pallet(module_name, response_info), + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => + W::expect_pallet(index, name, module_name, crate_major, min_crate_minor), + ReportTransactStatus(response_info) => W::report_transact_status(response_info), + ClearTransactStatus => W::clear_transact_status(), + UniversalOrigin(j) => W::universal_origin(j), + ExportMessage { network, destination, xcm } => + W::export_message(network, destination, xcm), + LockAsset { asset, unlocker } => W::lock_asset(asset, unlocker), + UnlockAsset { asset, target } => W::unlock_asset(asset, target), + NoteUnlockable { asset, owner } => W::note_unlockable(asset, owner), + RequestUnlock { asset, locker } => W::request_unlock(asset, locker), + SetFeesMode { jit_withdraw } => W::set_fees_mode(jit_withdraw), + SetTopic(topic) => W::set_topic(topic), + ClearTopic => W::clear_topic(), + AliasOrigin(location) => W::alias_origin(location), + UnpaidExecution { weight_limit, check_origin } => + W::unpaid_execution(weight_limit, check_origin), + } + } +} + +pub mod opaque { + /// The basic concrete type of `Xcm`, which doesn't make any assumptions about the + /// format of a call other than it is pre-encoded. + pub type Xcm = super::Xcm<()>; + + /// The basic concrete type of `Instruction`, which doesn't make any assumptions about the + /// format of a call other than it is pre-encoded. + pub type Instruction = super::Instruction<()>; +} + +// Convert from a v3 XCM to a v4 XCM +impl TryFrom> for Xcm { + type Error = (); + fn try_from(old_xcm: OldXcm) -> result::Result { + Ok(Xcm(old_xcm.0.into_iter().map(TryInto::try_into).collect::>()?)) + } +} + +// Convert from a v3 instruction to a v4 instruction +impl TryFrom> for Instruction { + type Error = (); + fn try_from(old_instruction: OldInstruction) -> result::Result { + dbg!(&old_instruction); + use OldInstruction::*; + Ok(match old_instruction { + WithdrawAsset(assets) => Self::WithdrawAsset(assets.try_into()?), + ReserveAssetDeposited(assets) => Self::ReserveAssetDeposited(assets.try_into()?), + ReceiveTeleportedAsset(assets) => Self::ReceiveTeleportedAsset(assets.try_into()?), + QueryResponse { query_id, response, max_weight, querier: Some(querier) } => + Self::QueryResponse { + query_id, + querier: querier.try_into()?, + response: response.try_into()?, + max_weight, + }, + QueryResponse { query_id, response, max_weight, querier: None } => + Self::QueryResponse { + query_id, + querier: None, + response: response.try_into()?, + max_weight, + }, + TransferAsset { assets, beneficiary } => Self::TransferAsset { + assets: assets.try_into()?, + beneficiary: beneficiary.try_into()?, + }, + TransferReserveAsset { assets, dest, xcm } => Self::TransferReserveAsset { + assets: assets.try_into()?, + dest: dest.try_into()?, + xcm: xcm.try_into()?, + }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => + Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, + HrmpChannelAccepted { recipient } => Self::HrmpChannelAccepted { recipient }, + HrmpChannelClosing { initiator, sender, recipient } => + Self::HrmpChannelClosing { initiator, sender, recipient }, + Transact { origin_kind, require_weight_at_most, call } => + Self::Transact { origin_kind, require_weight_at_most, call: call.into() }, + ReportError(response_info) => Self::ReportError(QueryResponseInfo { + query_id: response_info.query_id, + destination: response_info.destination.try_into().map_err(|_| ())?, + max_weight: response_info.max_weight, + }), + DepositAsset { assets, beneficiary } => { + let beneficiary = beneficiary.try_into()?; + let assets = assets.try_into()?; + Self::DepositAsset { assets, beneficiary } + }, + DepositReserveAsset { assets, dest, xcm } => { + let dest = dest.try_into()?; + let xcm = xcm.try_into()?; + let assets = assets.try_into()?; + Self::DepositReserveAsset { assets, dest, xcm } + }, + ExchangeAsset { give, want, maximal } => { + let give = give.try_into()?; + let want = want.try_into()?; + Self::ExchangeAsset { give, want, maximal } + }, + InitiateReserveWithdraw { assets, reserve, xcm } => { + // No `max_assets` here, so if there's a connt, then we cannot translate. + let assets = assets.try_into()?; + let reserve = reserve.try_into()?; + let xcm = xcm.try_into()?; + Self::InitiateReserveWithdraw { assets, reserve, xcm } + }, + InitiateTeleport { assets, dest, xcm } => { + // No `max_assets` here, so if there's a connt, then we cannot translate. + let assets = assets.try_into()?; + let dest = dest.try_into()?; + let xcm = xcm.try_into()?; + Self::InitiateTeleport { assets, dest, xcm } + }, + ReportHolding { response_info, assets } => { + let response_info = QueryResponseInfo { + destination: response_info.destination.try_into().map_err(|_| ())?, + query_id: response_info.query_id, + max_weight: response_info.max_weight, + }; + Self::ReportHolding { response_info, assets: assets.try_into()? } + }, + BuyExecution { fees, weight_limit } => { + let fees = fees.try_into()?; + let weight_limit = weight_limit.into(); + Self::BuyExecution { fees, weight_limit } + }, + ClearOrigin => Self::ClearOrigin, + DescendOrigin(who) => Self::DescendOrigin(who.try_into()?), + RefundSurplus => Self::RefundSurplus, + SetErrorHandler(xcm) => Self::SetErrorHandler(xcm.try_into()?), + SetAppendix(xcm) => Self::SetAppendix(xcm.try_into()?), + ClearError => Self::ClearError, + ClaimAsset { assets, ticket } => { + let assets = assets.try_into()?; + let ticket = ticket.try_into()?; + Self::ClaimAsset { assets, ticket } + }, + Trap(code) => Self::Trap(code), + SubscribeVersion { query_id, max_response_weight } => + Self::SubscribeVersion { query_id, max_response_weight }, + UnsubscribeVersion => Self::UnsubscribeVersion, + BurnAsset(assets) => Self::BurnAsset(assets.try_into()?), + ExpectAsset(assets) => Self::ExpectAsset(assets.try_into()?), + ExpectOrigin(maybe_location) => Self::ExpectOrigin(maybe_location.map(|location| location.try_into()).transpose().map_err(|_| ())?), + ExpectError(maybe_error) => Self::ExpectError(maybe_error.map(|error| error.try_into()).transpose().map_err(|_| ())?), + ExpectTransactStatus(maybe_error_code) => Self::ExpectTransactStatus(maybe_error_code), + QueryPallet { module_name, response_info } => Self::QueryPallet { module_name, response_info: response_info.try_into().map_err(|_| ())? }, + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => Self::ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, + ReportTransactStatus(response_info) => Self::ReportTransactStatus(response_info.try_into().map_err(|_| ())?), + ClearTransactStatus => Self::ClearTransactStatus, + UniversalOrigin(junction) => Self::UniversalOrigin(junction.try_into().map_err(|_| ())?), + ExportMessage { network, destination, xcm } => Self::ExportMessage { network: network.into(), destination: destination.try_into().map_err(|_| ())?, xcm: xcm.try_into().map_err(|_| ())? }, + LockAsset { asset, unlocker } => Self::LockAsset { asset: asset.try_into().map_err(|_| ())?, unlocker: unlocker.try_into().map_err(|_| ())? }, + UnlockAsset { asset, target } => Self::UnlockAsset { asset: asset.try_into().map_err(|_| ())?, target: target.try_into().map_err(|_| ())? }, + NoteUnlockable { asset, owner } => Self::NoteUnlockable { asset: asset.try_into().map_err(|_| ())?, owner: owner.try_into().map_err(|_| ())? }, + RequestUnlock { asset, locker } => Self::RequestUnlock { asset: asset.try_into().map_err(|_| ())?, locker: locker.try_into().map_err(|_| ())? }, + SetFeesMode { jit_withdraw } => Self::SetFeesMode { jit_withdraw }, + SetTopic(topic) => Self::SetTopic(topic), + ClearTopic => Self::ClearTopic, + AliasOrigin(location) => Self::AliasOrigin(location.try_into().map_err(|_| ())?), + UnpaidExecution { weight_limit, check_origin } => Self::UnpaidExecution { weight_limit, check_origin: check_origin.map(|location| location.try_into()).transpose().map_err(|_| ())? }, + }) + } +} + +#[cfg(test)] +mod tests { + use super::{prelude::*, *}; + use crate::v3::{ + Junctions::Here as OldHere, MultiAssetFilter as OldMultiAssetFilter, + WildMultiAsset as OldWildMultiAsset, + }; + + #[test] + fn basic_roundtrip_works() { + let xcm = Xcm::<()>(vec![TransferAsset { + assets: (Here, 1u128).into(), + beneficiary: Here.into(), + }]); + let old_xcm = OldXcm::<()>(vec![OldInstruction::TransferAsset { + assets: (OldHere, 1u128).into(), + beneficiary: OldHere.into(), + }]); + assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap()); + let new_xcm: Xcm<()> = old_xcm.try_into().unwrap(); + assert_eq!(new_xcm, xcm); + } + + #[test] + fn teleport_roundtrip_works() { + let xcm = Xcm::<()>(vec![ + ReceiveTeleportedAsset((Here, 1u128).into()), + ClearOrigin, + DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Here.into() }, + ]); + let old_xcm: OldXcm<()> = OldXcm::<()>(vec![ + OldInstruction::ReceiveTeleportedAsset((OldHere, 1u128).into()), + OldInstruction::ClearOrigin, + OldInstruction::DepositAsset { + assets: crate::v3::MultiAssetFilter::Wild(crate::v3::WildMultiAsset::AllCounted(1)), + beneficiary: OldHere.into(), + }, + ]); + assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap()); + let new_xcm: Xcm<()> = old_xcm.try_into().unwrap(); + assert_eq!(new_xcm, xcm); + } + + #[test] + fn reserve_deposit_roundtrip_works() { + let xcm = Xcm::<()>(vec![ + ReserveAssetDeposited((Here, 1u128).into()), + ClearOrigin, + BuyExecution { + fees: (Here, 1u128).into(), + weight_limit: Some(Weight::from_parts(1, 1)).into(), + }, + DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Here.into() }, + ]); + let old_xcm = OldXcm::<()>(vec![ + OldInstruction::ReserveAssetDeposited((OldHere, 1u128).into()), + OldInstruction::ClearOrigin, + OldInstruction::BuyExecution { + fees: (OldHere, 1u128).into(), + weight_limit: WeightLimit::Limited(Weight::from_parts(1, 1)), + }, + OldInstruction::DepositAsset { + assets: crate::v3::MultiAssetFilter::Wild(crate::v3::WildMultiAsset::AllCounted(1)), + beneficiary: OldHere.into(), + }, + ]); + assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap()); + let new_xcm: Xcm<()> = old_xcm.try_into().unwrap(); + assert_eq!(new_xcm, xcm); + } + + #[test] + fn deposit_asset_roundtrip_works() { + let xcm = Xcm::<()>(vec![ + WithdrawAsset((Here, 1u128).into()), + DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Here.into() }, + ]); + let old_xcm = OldXcm::<()>(vec![ + OldInstruction::WithdrawAsset((OldHere, 1u128).into()), + OldInstruction::DepositAsset { + assets: OldMultiAssetFilter::Wild(OldWildMultiAsset::AllCounted(1)), + beneficiary: OldHere.into(), + }, + ]); + assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap()); + let new_xcm: Xcm<()> = old_xcm.try_into().unwrap(); + assert_eq!(new_xcm, xcm); + } + + #[test] + fn deposit_reserve_asset_roundtrip_works() { + let xcm = Xcm::<()>(vec![ + WithdrawAsset((Here, 1u128).into()), + DepositReserveAsset { + assets: Wild(AllCounted(1)), + dest: Here.into(), + xcm: Xcm::<()>(vec![]), + }, + ]); + let old_xcm = OldXcm::<()>(vec![ + OldInstruction::WithdrawAsset((OldHere, 1u128).into()), + OldInstruction::DepositReserveAsset { + assets: OldMultiAssetFilter::Wild(OldWildMultiAsset::AllCounted(1)), + dest: OldHere.into(), + xcm: OldXcm::<()>(vec![]), + }, + ]); + assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap()); + let new_xcm: Xcm<()> = old_xcm.try_into().unwrap(); + assert_eq!(new_xcm, xcm); + } +} diff --git a/polkadot/xcm/src/v4/traits.rs b/polkadot/xcm/src/v4/traits.rs new file mode 100644 index 000000000000..23a39a43b87b --- /dev/null +++ b/polkadot/xcm/src/v4/traits.rs @@ -0,0 +1,359 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Substrate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Substrate is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! Cross-Consensus Message format data structures. + +pub use crate::v3::{Error, Result, SendError, XcmHash}; +use core::result; +use parity_scale_codec::{Decode, Encode}; +use scale_info::TypeInfo; + +pub use sp_weights::Weight; + +use super::*; + +/// Outcome of an XCM execution. +#[derive(Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)] +pub enum Outcome { + /// Execution completed successfully; given weight was used. + Complete { used: Weight }, + /// Execution started, but did not complete successfully due to the given error; given weight + /// was used. + Incomplete { used: Weight, error: Error }, + /// Execution did not start due to the given error. + Error { error: Error }, +} + +impl Outcome { + pub fn ensure_complete(self) -> Result { + match self { + Outcome::Complete { .. } => Ok(()), + Outcome::Incomplete { error, .. } => Err(error), + Outcome::Error { error, .. } => Err(error), + } + } + pub fn ensure_execution(self) -> result::Result { + match self { + Outcome::Complete { used, .. } => Ok(used), + Outcome::Incomplete { used, .. } => Ok(used), + Outcome::Error { error, .. } => Err(error), + } + } + /// How much weight was used by the XCM execution attempt. + pub fn weight_used(&self) -> Weight { + match self { + Outcome::Complete { used, .. } => *used, + Outcome::Incomplete { used, .. } => *used, + Outcome::Error { .. } => Weight::zero(), + } + } +} + +impl From for Outcome { + fn from(error: Error) -> Self { + Self::Error { error } + } +} + +pub trait PreparedMessage { + fn weight_of(&self) -> Weight; +} + +/// Type of XCM message executor. +pub trait ExecuteXcm { + type Prepared: PreparedMessage; + fn prepare(message: Xcm) -> result::Result>; + fn execute( + origin: impl Into, + pre: Self::Prepared, + id: &mut XcmHash, + weight_credit: Weight, + ) -> Outcome; + fn prepare_and_execute( + origin: impl Into, + message: Xcm, + id: &mut XcmHash, + weight_limit: Weight, + weight_credit: Weight, + ) -> Outcome { + let pre = match Self::prepare(message) { + Ok(x) => x, + Err(_) => return Outcome::Error { error: Error::WeightNotComputable }, + }; + let xcm_weight = pre.weight_of(); + if xcm_weight.any_gt(weight_limit) { + return Outcome::Error { error: Error::WeightLimitReached(xcm_weight) } + } + Self::execute(origin, pre, id, weight_credit) + } + + /// Execute some XCM `message` with the message `hash` from `origin` using no more than + /// `weight_limit` weight. + /// + /// The weight limit is a basic hard-limit and the implementation may place further + /// restrictions or requirements on weight and other aspects. + #[deprecated = "Use `prepare_and_execute` instead"] + fn execute_xcm( + origin: impl Into, + message: Xcm, + mut hash: XcmHash, + weight_limit: Weight, + ) -> Outcome { + let origin = origin.into(); + log::debug!( + target: "xcm::execute_xcm", + "origin: {:?}, message: {:?}, weight_limit: {:?}", + origin, + message, + weight_limit, + ); + Self::prepare_and_execute(origin, message, &mut hash, weight_limit, Weight::zero()) + } + + /// Execute some XCM `message` with the message `hash` from `origin` using no more than + /// `weight_limit` weight. + /// + /// Some amount of `weight_credit` may be provided which, depending on the implementation, may + /// allow execution without associated payment. + #[deprecated = "Use `prepare_and_execute` instead"] + fn execute_xcm_in_credit( + origin: impl Into, + message: Xcm, + mut hash: XcmHash, + weight_limit: Weight, + weight_credit: Weight, + ) -> Outcome { + let pre = match Self::prepare(message) { + Ok(x) => x, + Err(_) => return Outcome::Error { error: Error::WeightNotComputable }, + }; + let xcm_weight = pre.weight_of(); + if xcm_weight.any_gt(weight_limit) { + return Outcome::Error { error: Error::WeightLimitReached(xcm_weight) } + } + Self::execute(origin, pre, &mut hash, weight_credit) + } + + /// Deduct some `fees` to the sovereign account of the given `location` and place them as per + /// the convention for fees. + fn charge_fees(location: impl Into, fees: Assets) -> Result; +} + +pub enum Weightless {} +impl PreparedMessage for Weightless { + fn weight_of(&self) -> Weight { + unreachable!() + } +} + +impl ExecuteXcm for () { + type Prepared = Weightless; + fn prepare(message: Xcm) -> result::Result> { + Err(message) + } + fn execute(_: impl Into, _: Self::Prepared, _: &mut XcmHash, _: Weight) -> Outcome { + unreachable!() + } + fn charge_fees(_location: impl Into, _fees: Assets) -> Result { + Err(Error::Unimplemented) + } +} + +pub trait Reanchorable: Sized { + /// Type to return in case of an error. + type Error; + + /// Mutate `self` so that it represents the same location from the point of view of `target`. + /// The context of `self` is provided as `context`. + /// + /// Does not modify `self` in case of overflow. + fn reanchor( + &mut self, + target: &Location, + context: &InteriorLocation, + ) -> core::result::Result<(), ()>; + + /// Consume `self` and return a new value representing the same location from the point of view + /// of `target`. The context of `self` is provided as `context`. + /// + /// Returns the original `self` in case of overflow. + fn reanchored( + self, + target: &Location, + context: &InteriorLocation, + ) -> core::result::Result; +} + +/// Result value when attempting to send an XCM message. +pub type SendResult = result::Result<(T, Assets), SendError>; + +/// Utility for sending an XCM message to a given location. +/// +/// These can be amalgamated in tuples to form sophisticated routing systems. In tuple format, each +/// router might return `NotApplicable` to pass the execution to the next sender item. Note that +/// each `NotApplicable` might alter the destination and the XCM message for to the next router. +/// +/// # Example +/// ```rust +/// # use parity_scale_codec::Encode; +/// # use staging_xcm::v4::{prelude::*, Weight}; +/// # use staging_xcm::VersionedXcm; +/// # use std::convert::Infallible; +/// +/// /// A sender that only passes the message through and does nothing. +/// struct Sender1; +/// impl SendXcm for Sender1 { +/// type Ticket = Infallible; +/// fn validate(_: &mut Option, _: &mut Option>) -> SendResult { +/// Err(SendError::NotApplicable) +/// } +/// fn deliver(_: Infallible) -> Result { +/// unreachable!() +/// } +/// } +/// +/// /// A sender that accepts a message that has two junctions, otherwise stops the routing. +/// struct Sender2; +/// impl SendXcm for Sender2 { +/// type Ticket = (); +/// fn validate(destination: &mut Option, message: &mut Option>) -> SendResult<()> { +/// match destination.as_ref().ok_or(SendError::MissingArgument)?.unpack() { +/// (0, [j1, j2]) => Ok(((), Assets::new())), +/// _ => Err(SendError::Unroutable), +/// } +/// } +/// fn deliver(_: ()) -> Result { +/// Ok([0; 32]) +/// } +/// } +/// +/// /// A sender that accepts a message from a parent, passing through otherwise. +/// struct Sender3; +/// impl SendXcm for Sender3 { +/// type Ticket = (); +/// fn validate(destination: &mut Option, message: &mut Option>) -> SendResult<()> { +/// match destination.as_ref().ok_or(SendError::MissingArgument)?.unpack() { +/// (1, []) => Ok(((), Assets::new())), +/// _ => Err(SendError::NotApplicable), +/// } +/// } +/// fn deliver(_: ()) -> Result { +/// Ok([0; 32]) +/// } +/// } +/// +/// // A call to send via XCM. We don't really care about this. +/// # fn main() { +/// let call: Vec = ().encode(); +/// let message = Xcm(vec![Instruction::Transact { +/// origin_kind: OriginKind::Superuser, +/// require_weight_at_most: Weight::zero(), +/// call: call.into(), +/// }]); +/// let message_hash = message.using_encoded(sp_io::hashing::blake2_256); +/// +/// // Sender2 will block this. +/// assert!(send_xcm::<(Sender1, Sender2, Sender3)>(Parent.into(), message.clone()).is_err()); +/// +/// // Sender3 will catch this. +/// assert!(send_xcm::<(Sender1, Sender3)>(Parent.into(), message.clone()).is_ok()); +/// # } +/// ``` +pub trait SendXcm { + /// Intermediate value which connects the two phases of the send operation. + type Ticket; + + /// Check whether the given `_message` is deliverable to the given `_destination` and if so + /// determine the cost which will be paid by this chain to do so, returning a `Validated` token + /// which can be used to enact delivery. + /// + /// The `destination` and `message` must be `Some` (or else an error will be returned) and they + /// may only be consumed if the `Err` is not `NotApplicable`. + /// + /// If it is not a destination which can be reached with this type but possibly could by others, + /// then this *MUST* return `NotApplicable`. Any other error will cause the tuple + /// implementation to exit early without trying other type fields. + fn validate( + destination: &mut Option, + message: &mut Option>, + ) -> SendResult; + + /// Actually carry out the delivery operation for a previously validated message sending. + fn deliver(ticket: Self::Ticket) -> result::Result; +} + +#[impl_trait_for_tuples::impl_for_tuples(30)] +impl SendXcm for Tuple { + for_tuples! { type Ticket = (#( Option ),* ); } + + fn validate( + destination: &mut Option, + message: &mut Option>, + ) -> SendResult { + let mut maybe_cost: Option = None; + let one_ticket: Self::Ticket = (for_tuples! { #( + if maybe_cost.is_some() { + None + } else { + match Tuple::validate(destination, message) { + Err(SendError::NotApplicable) => None, + Err(e) => { return Err(e) }, + Ok((v, c)) => { + maybe_cost = Some(c); + Some(v) + }, + } + } + ),* }); + if let Some(cost) = maybe_cost { + Ok((one_ticket, cost)) + } else { + Err(SendError::NotApplicable) + } + } + + fn deliver(one_ticket: Self::Ticket) -> result::Result { + for_tuples!( #( + if let Some(validated) = one_ticket.Tuple { + return Tuple::deliver(validated); + } + )* ); + Err(SendError::Unroutable) + } +} + +/// Convenience function for using a `SendXcm` implementation. Just interprets the `dest` and wraps +/// both in `Some` before passing them as as mutable references into `T::send_xcm`. +pub fn validate_send(dest: Location, msg: Xcm<()>) -> SendResult { + T::validate(&mut Some(dest), &mut Some(msg)) +} + +/// Convenience function for using a `SendXcm` implementation. Just interprets the `dest` and wraps +/// both in `Some` before passing them as as mutable references into `T::send_xcm`. +/// +/// Returns either `Ok` with the price of the delivery, or `Err` with the reason why the message +/// could not be sent. +/// +/// Generally you'll want to validate and get the price first to ensure that the sender can pay it +/// before actually doing the delivery. +pub fn send_xcm( + dest: Location, + msg: Xcm<()>, +) -> result::Result<(XcmHash, Assets), SendError> { + let (ticket, price) = T::validate(&mut Some(dest), &mut Some(msg))?; + let hash = T::deliver(ticket)?; + Ok((hash, price)) +} diff --git a/polkadot/xcm/xcm-builder/src/asset_conversion.rs b/polkadot/xcm/xcm-builder/src/asset_conversion.rs index 5b76ed764a81..340428a6583d 100644 --- a/polkadot/xcm/xcm-builder/src/asset_conversion.rs +++ b/polkadot/xcm/xcm-builder/src/asset_conversion.rs @@ -23,19 +23,15 @@ use xcm::latest::prelude::*; use xcm_executor::traits::{Error as MatchError, MatchesFungibles, MatchesNonFungibles}; /// Converter struct implementing `AssetIdConversion` converting a numeric asset ID (must be -/// `TryFrom/TryInto`) into a `GeneralIndex` junction, prefixed by some `MultiLocation` value. -/// The `MultiLocation` value will typically be a `PalletInstance` junction. +/// `TryFrom/TryInto`) into a `GeneralIndex` junction, prefixed by some `Location` value. +/// The `Location` value will typically be a `PalletInstance` junction. pub struct AsPrefixedGeneralIndex( PhantomData<(Prefix, AssetId, ConvertAssetId)>, ); -impl< - Prefix: Get, - AssetId: Clone, - ConvertAssetId: MaybeEquivalence, - > MaybeEquivalence - for AsPrefixedGeneralIndex +impl, AssetId: Clone, ConvertAssetId: MaybeEquivalence> + MaybeEquivalence for AsPrefixedGeneralIndex { - fn convert(id: &MultiLocation) -> Option { + fn convert(id: &Location) -> Option { let prefix = Prefix::get(); if prefix.parent_count() != id.parent_count() || prefix @@ -51,7 +47,7 @@ impl< _ => None, } } - fn convert_back(what: &AssetId) -> Option { + fn convert_back(what: &AssetId) -> Option { let mut location = Prefix::get(); let id = ConvertAssetId::convert_back(what)?; location.push_interior(Junction::GeneralIndex(id)).ok()?; @@ -65,14 +61,14 @@ pub struct ConvertedConcreteId( impl< AssetId: Clone, Balance: Clone, - ConvertAssetId: MaybeEquivalence, + ConvertAssetId: MaybeEquivalence, ConvertBalance: MaybeEquivalence, > MatchesFungibles for ConvertedConcreteId { - fn matches_fungibles(a: &MultiAsset) -> result::Result<(AssetId, Balance), MatchError> { + fn matches_fungibles(a: &Asset) -> result::Result<(AssetId, Balance), MatchError> { let (amount, id) = match (&a.fun, &a.id) { - (Fungible(ref amount), Concrete(ref id)) => (amount, id), + (Fungible(ref amount), AssetId(ref id)) => (amount, id), _ => return Err(MatchError::AssetNotHandled), }; let what = ConvertAssetId::convert(id).ok_or(MatchError::AssetIdConversionFailed)?; @@ -84,56 +80,14 @@ impl< impl< ClassId: Clone, InstanceId: Clone, - ConvertClassId: MaybeEquivalence, + ConvertClassId: MaybeEquivalence, ConvertInstanceId: MaybeEquivalence, > MatchesNonFungibles for ConvertedConcreteId { - fn matches_nonfungibles(a: &MultiAsset) -> result::Result<(ClassId, InstanceId), MatchError> { - let (instance, class) = match (&a.fun, &a.id) { - (NonFungible(ref instance), Concrete(ref class)) => (instance, class), - _ => return Err(MatchError::AssetNotHandled), - }; - let what = ConvertClassId::convert(class).ok_or(MatchError::AssetIdConversionFailed)?; - let instance = - ConvertInstanceId::convert(instance).ok_or(MatchError::InstanceConversionFailed)?; - Ok((what, instance)) - } -} - -pub struct ConvertedAbstractId( - PhantomData<(AssetId, Balance, ConvertAssetId, ConvertOther)>, -); -impl< - AssetId: Clone, - Balance: Clone, - ConvertAssetId: MaybeEquivalence<[u8; 32], AssetId>, - ConvertBalance: MaybeEquivalence, - > MatchesFungibles - for ConvertedAbstractId -{ - fn matches_fungibles(a: &MultiAsset) -> result::Result<(AssetId, Balance), MatchError> { - let (amount, id) = match (&a.fun, &a.id) { - (Fungible(ref amount), Abstract(ref id)) => (amount, id), - _ => return Err(MatchError::AssetNotHandled), - }; - let what = ConvertAssetId::convert(id).ok_or(MatchError::AssetIdConversionFailed)?; - let amount = - ConvertBalance::convert(amount).ok_or(MatchError::AmountToBalanceConversionFailed)?; - Ok((what, amount)) - } -} -impl< - ClassId: Clone, - InstanceId: Clone, - ConvertClassId: MaybeEquivalence<[u8; 32], ClassId>, - ConvertInstanceId: MaybeEquivalence, - > MatchesNonFungibles - for ConvertedAbstractId -{ - fn matches_nonfungibles(a: &MultiAsset) -> result::Result<(ClassId, InstanceId), MatchError> { + fn matches_nonfungibles(a: &Asset) -> result::Result<(ClassId, InstanceId), MatchError> { let (instance, class) = match (&a.fun, &a.id) { - (NonFungible(ref instance), Abstract(ref class)) => (instance, class), + (NonFungible(ref instance), AssetId(ref class)) => (instance, class), _ => return Err(MatchError::AssetNotHandled), }; let what = ConvertClassId::convert(class).ok_or(MatchError::AssetIdConversionFailed)?; @@ -145,8 +99,6 @@ impl< #[deprecated = "Use `ConvertedConcreteId` instead"] pub type ConvertedConcreteAssetId = ConvertedConcreteId; -#[deprecated = "Use `ConvertedAbstractId` instead"] -pub type ConvertedAbstractAssetId = ConvertedAbstractId; pub struct MatchedConvertedConcreteId( PhantomData<(AssetId, Balance, MatchAssetId, ConvertAssetId, ConvertOther)>, @@ -154,15 +106,15 @@ pub struct MatchedConvertedConcreteId, - ConvertAssetId: MaybeEquivalence, + MatchAssetId: Contains, + ConvertAssetId: MaybeEquivalence, ConvertBalance: MaybeEquivalence, > MatchesFungibles for MatchedConvertedConcreteId { - fn matches_fungibles(a: &MultiAsset) -> result::Result<(AssetId, Balance), MatchError> { + fn matches_fungibles(a: &Asset) -> result::Result<(AssetId, Balance), MatchError> { let (amount, id) = match (&a.fun, &a.id) { - (Fungible(ref amount), Concrete(ref id)) if MatchAssetId::contains(id) => (amount, id), + (Fungible(ref amount), AssetId(ref id)) if MatchAssetId::contains(id) => (amount, id), _ => return Err(MatchError::AssetNotHandled), }; let what = ConvertAssetId::convert(id).ok_or(MatchError::AssetIdConversionFailed)?; @@ -174,15 +126,15 @@ impl< impl< ClassId: Clone, InstanceId: Clone, - MatchClassId: Contains, - ConvertClassId: MaybeEquivalence, + MatchClassId: Contains, + ConvertClassId: MaybeEquivalence, ConvertInstanceId: MaybeEquivalence, > MatchesNonFungibles for MatchedConvertedConcreteId { - fn matches_nonfungibles(a: &MultiAsset) -> result::Result<(ClassId, InstanceId), MatchError> { + fn matches_nonfungibles(a: &Asset) -> result::Result<(ClassId, InstanceId), MatchError> { let (instance, class) = match (&a.fun, &a.id) { - (NonFungible(ref instance), Concrete(ref class)) if MatchClassId::contains(class) => + (NonFungible(ref instance), AssetId(ref class)) if MatchClassId::contains(class) => (instance, class), _ => return Err(MatchError::AssetNotHandled), }; @@ -200,10 +152,10 @@ mod tests { use xcm_executor::traits::JustTry; struct OnlyParentZero; - impl Contains for OnlyParentZero { - fn contains(a: &MultiLocation) -> bool { + impl Contains for OnlyParentZero { + fn contains(a: &Location) -> bool { match a { - MultiLocation { parents: 0, .. } => true, + Location { parents: 0, .. } => true, _ => false, } } @@ -214,7 +166,7 @@ mod tests { type AssetIdForTrustBackedAssets = u32; type Balance = u128; frame_support::parameter_types! { - pub TrustBackedAssetsPalletLocation: MultiLocation = PalletInstance(50).into(); + pub TrustBackedAssetsPalletLocation: Location = PalletInstance(50).into(); } // ConvertedConcreteId cfg @@ -231,13 +183,13 @@ mod tests { >; assert_eq!( TrustBackedAssetsPalletLocation::get(), - MultiLocation { parents: 0, interior: X1(PalletInstance(50)) } + Location { parents: 0, interior: [PalletInstance(50)].into() } ); // err - does not match assert_eq!( - Converter::matches_fungibles(&MultiAsset { - id: Concrete(MultiLocation::new(1, X2(PalletInstance(50), GeneralIndex(1)))), + Converter::matches_fungibles(&Asset { + id: AssetId(Location::new(1, [PalletInstance(50), GeneralIndex(1)])), fun: Fungible(12345), }), Err(MatchError::AssetNotHandled) @@ -245,10 +197,10 @@ mod tests { // err - matches, but convert fails assert_eq!( - Converter::matches_fungibles(&MultiAsset { - id: Concrete(MultiLocation::new( + Converter::matches_fungibles(&Asset { + id: AssetId(Location::new( 0, - X2(PalletInstance(50), GeneralKey { length: 1, data: [1; 32] }) + [PalletInstance(50), GeneralKey { length: 1, data: [1; 32] }] )), fun: Fungible(12345), }), @@ -257,8 +209,8 @@ mod tests { // err - matches, but NonFungible assert_eq!( - Converter::matches_fungibles(&MultiAsset { - id: Concrete(MultiLocation::new(0, X2(PalletInstance(50), GeneralIndex(1)))), + Converter::matches_fungibles(&Asset { + id: AssetId(Location::new(0, [PalletInstance(50), GeneralIndex(1)])), fun: NonFungible(Index(54321)), }), Err(MatchError::AssetNotHandled) @@ -266,8 +218,8 @@ mod tests { // ok assert_eq!( - Converter::matches_fungibles(&MultiAsset { - id: Concrete(MultiLocation::new(0, X2(PalletInstance(50), GeneralIndex(1)))), + Converter::matches_fungibles(&Asset { + id: AssetId(Location::new(0, [PalletInstance(50), GeneralIndex(1)])), fun: Fungible(12345), }), Ok((1, 12345)) @@ -279,7 +231,7 @@ mod tests { type ClassId = u32; type ClassInstanceId = u64; frame_support::parameter_types! { - pub TrustBackedAssetsPalletLocation: MultiLocation = PalletInstance(50).into(); + pub TrustBackedAssetsPalletLocation: Location = PalletInstance(50).into(); } // ConvertedConcreteId cfg @@ -303,13 +255,13 @@ mod tests { >; assert_eq!( TrustBackedAssetsPalletLocation::get(), - MultiLocation { parents: 0, interior: X1(PalletInstance(50)) } + Location { parents: 0, interior: [PalletInstance(50)].into() } ); // err - does not match assert_eq!( - Converter::matches_nonfungibles(&MultiAsset { - id: Concrete(MultiLocation::new(1, X2(PalletInstance(50), GeneralIndex(1)))), + Converter::matches_nonfungibles(&Asset { + id: AssetId(Location::new(1, [PalletInstance(50), GeneralIndex(1)])), fun: NonFungible(Index(54321)), }), Err(MatchError::AssetNotHandled) @@ -317,10 +269,10 @@ mod tests { // err - matches, but convert fails assert_eq!( - Converter::matches_nonfungibles(&MultiAsset { - id: Concrete(MultiLocation::new( + Converter::matches_nonfungibles(&Asset { + id: AssetId(Location::new( 0, - X2(PalletInstance(50), GeneralKey { length: 1, data: [1; 32] }) + [PalletInstance(50), GeneralKey { length: 1, data: [1; 32] }] )), fun: NonFungible(Index(54321)), }), @@ -329,8 +281,8 @@ mod tests { // err - matches, but Fungible vs NonFungible assert_eq!( - Converter::matches_nonfungibles(&MultiAsset { - id: Concrete(MultiLocation::new(0, X2(PalletInstance(50), GeneralIndex(1)))), + Converter::matches_nonfungibles(&Asset { + id: AssetId(Location::new(0, [PalletInstance(50), GeneralIndex(1)])), fun: Fungible(12345), }), Err(MatchError::AssetNotHandled) @@ -338,8 +290,8 @@ mod tests { // ok assert_eq!( - Converter::matches_nonfungibles(&MultiAsset { - id: Concrete(MultiLocation::new(0, X2(PalletInstance(50), GeneralIndex(1)))), + Converter::matches_nonfungibles(&Asset { + id: AssetId(Location::new(0, [PalletInstance(50), GeneralIndex(1)])), fun: NonFungible(Index(54321)), }), Ok((1, 54321)) diff --git a/polkadot/xcm/xcm-builder/src/barriers.rs b/polkadot/xcm/xcm-builder/src/barriers.rs index c2b62751c688..80411ab5a224 100644 --- a/polkadot/xcm/xcm-builder/src/barriers.rs +++ b/polkadot/xcm/xcm-builder/src/barriers.rs @@ -34,7 +34,7 @@ use xcm_executor::traits::{CheckSuspension, OnResponse, Properties, ShouldExecut pub struct TakeWeightCredit; impl ShouldExecute for TakeWeightCredit { fn should_execute( - _origin: &MultiLocation, + _origin: &Location, _instructions: &mut [Instruction], max_weight: Weight, properties: &mut Properties, @@ -60,9 +60,9 @@ const MAX_ASSETS_FOR_BUY_EXECUTION: usize = 2; /// Only allows for `TeleportAsset`, `WithdrawAsset`, `ClaimAsset` and `ReserveAssetDeposit` XCMs /// because they are the only ones that place assets in the Holding Register to pay for execution. pub struct AllowTopLevelPaidExecutionFrom(PhantomData); -impl> ShouldExecute for AllowTopLevelPaidExecutionFrom { +impl> ShouldExecute for AllowTopLevelPaidExecutionFrom { fn should_execute( - origin: &MultiLocation, + origin: &Location, instructions: &mut [Instruction], max_weight: Weight, _properties: &mut Properties, @@ -158,14 +158,11 @@ impl> ShouldExecute for AllowTopLevelPaidExecutionFro pub struct WithComputedOrigin( PhantomData<(InnerBarrier, LocalUniversal, MaxPrefixes)>, ); -impl< - InnerBarrier: ShouldExecute, - LocalUniversal: Get, - MaxPrefixes: Get, - > ShouldExecute for WithComputedOrigin +impl, MaxPrefixes: Get> + ShouldExecute for WithComputedOrigin { fn should_execute( - origin: &MultiLocation, + origin: &Location, instructions: &mut [Instruction], max_weight: Weight, properties: &mut Properties, @@ -175,7 +172,7 @@ impl< "WithComputedOrigin origin: {:?}, instructions: {:?}, max_weight: {:?}, properties: {:?}", origin, instructions, max_weight, properties, ); - let mut actual_origin = *origin; + let mut actual_origin = origin.clone(); let skipped = Cell::new(0usize); // NOTE: We do not check the validity of `UniversalOrigin` here, meaning that a malicious // origin could place a `UniversalOrigin` in order to spoof some location which gets free @@ -190,10 +187,11 @@ impl< // Note the origin is *relative to local consensus*! So we need to escape // local consensus with the `parents` before diving in into the // `universal_location`. - actual_origin = X1(*new_global).relative_to(&LocalUniversal::get()); + actual_origin = + Junctions::from([*new_global]).relative_to(&LocalUniversal::get()); }, DescendOrigin(j) => { - let Ok(_) = actual_origin.append_with(*j) else { + let Ok(_) = actual_origin.append_with(j.clone()) else { return Err(ProcessMessageError::Unsupported) }; }, @@ -221,7 +219,7 @@ impl< pub struct TrailingSetTopicAsId(PhantomData); impl ShouldExecute for TrailingSetTopicAsId { fn should_execute( - origin: &MultiLocation, + origin: &Location, instructions: &mut [Instruction], max_weight: Weight, properties: &mut Properties, @@ -250,7 +248,7 @@ where SuspensionChecker: CheckSuspension, { fn should_execute( - origin: &MultiLocation, + origin: &Location, instructions: &mut [Instruction], max_weight: Weight, properties: &mut Properties, @@ -268,9 +266,9 @@ where /// Use only for executions from completely trusted origins, from which no permissionless messages /// can be sent. pub struct AllowUnpaidExecutionFrom(PhantomData); -impl> ShouldExecute for AllowUnpaidExecutionFrom { +impl> ShouldExecute for AllowUnpaidExecutionFrom { fn should_execute( - origin: &MultiLocation, + origin: &Location, instructions: &mut [Instruction], _max_weight: Weight, _properties: &mut Properties, @@ -290,9 +288,9 @@ impl> ShouldExecute for AllowUnpaidExecutionFrom { /// /// Use only for executions from trusted origin groups. pub struct AllowExplicitUnpaidExecutionFrom(PhantomData); -impl> ShouldExecute for AllowExplicitUnpaidExecutionFrom { +impl> ShouldExecute for AllowExplicitUnpaidExecutionFrom { fn should_execute( - origin: &MultiLocation, + origin: &Location, instructions: &mut [Instruction], max_weight: Weight, _properties: &mut Properties, @@ -314,11 +312,11 @@ impl> ShouldExecute for AllowExplicitUnpaidExecutionF /// Allows a message only if it is from a system-level child parachain. pub struct IsChildSystemParachain(PhantomData); -impl> Contains for IsChildSystemParachain { - fn contains(l: &MultiLocation) -> bool { +impl> Contains for IsChildSystemParachain { + fn contains(l: &Location) -> bool { matches!( - l.interior(), - Junctions::X1(Junction::Parachain(id)) + l.interior().as_slice(), + [Junction::Parachain(id)] if ParaId::from(*id).is_system() && l.parent_count() == 0, ) } @@ -328,7 +326,7 @@ impl> Contains for IsChildSystemPara pub struct AllowKnownQueryResponses(PhantomData); impl ShouldExecute for AllowKnownQueryResponses { fn should_execute( - origin: &MultiLocation, + origin: &Location, instructions: &mut [Instruction], _max_weight: Weight, _properties: &mut Properties, @@ -354,9 +352,9 @@ impl ShouldExecute for AllowKnownQueryResponses(PhantomData); -impl> ShouldExecute for AllowSubscriptionsFrom { +impl> ShouldExecute for AllowSubscriptionsFrom { fn should_execute( - origin: &MultiLocation, + origin: &Location, instructions: &mut [Instruction], _max_weight: Weight, _properties: &mut Properties, @@ -391,7 +389,7 @@ where Allow: ShouldExecute, { fn should_execute( - origin: &MultiLocation, + origin: &Location, message: &mut [Instruction], max_weight: Weight, properties: &mut Properties, @@ -405,7 +403,7 @@ where pub struct DenyReserveTransferToRelayChain; impl ShouldExecute for DenyReserveTransferToRelayChain { fn should_execute( - origin: &MultiLocation, + origin: &Location, message: &mut [Instruction], _max_weight: Weight, _properties: &mut Properties, @@ -414,22 +412,18 @@ impl ShouldExecute for DenyReserveTransferToRelayChain { |_| true, |inst| match inst { InitiateReserveWithdraw { - reserve: MultiLocation { parents: 1, interior: Here }, + reserve: Location { parents: 1, interior: Here }, .. } | - DepositReserveAsset { - dest: MultiLocation { parents: 1, interior: Here }, .. - } | - TransferReserveAsset { - dest: MultiLocation { parents: 1, interior: Here }, .. - } => { + DepositReserveAsset { dest: Location { parents: 1, interior: Here }, .. } | + TransferReserveAsset { dest: Location { parents: 1, interior: Here }, .. } => { Err(ProcessMessageError::Unsupported) // Deny }, // An unexpected reserve transfer has arrived from the Relay Chain. Generally, // `IsReserve` should not allow this, but we just log it here. ReserveAssetDeposited { .. } - if matches!(origin, MultiLocation { parents: 1, interior: Here }) => + if matches!(origin, Location { parents: 1, interior: Here }) => { log::warn!( target: "xcm::barrier", diff --git a/polkadot/xcm/xcm-builder/src/controller.rs b/polkadot/xcm/xcm-builder/src/controller.rs index 0ee638b73e1c..d88aca4df05d 100644 --- a/polkadot/xcm/xcm-builder/src/controller.rs +++ b/polkadot/xcm/xcm-builder/src/controller.rs @@ -45,7 +45,7 @@ pub trait ExecuteControllerWeightInfo { /// Execute an XCM locally, for a given origin. /// /// An implementation of that trait will handle the low-level details of the execution, such as: -/// - Validating and Converting the origin to a MultiLocation. +/// - Validating and Converting the origin to a Location. /// - Handling versioning. /// - Calling the internal executor, which implements [`ExecuteXcm`]. pub trait ExecuteController { @@ -92,7 +92,7 @@ pub trait SendController { /// - `msg`: the XCM to be sent. fn send( origin: Origin, - dest: Box, + dest: Box, message: Box>, ) -> Result; } @@ -127,7 +127,7 @@ pub trait QueryController: QueryHandler { fn query( origin: Origin, timeout: Timeout, - match_querier: VersionedMultiLocation, + match_querier: VersionedLocation, ) -> Result; } @@ -138,7 +138,7 @@ impl ExecuteController for () { _message: Box>, _max_weight: Weight, ) -> Result { - Ok(Outcome::Error(XcmError::Unimplemented)) + Ok(Outcome::Error { error: XcmError::Unimplemented }) } } @@ -152,7 +152,7 @@ impl SendController for () { type WeightInfo = (); fn send( _origin: Origin, - _dest: Box, + _dest: Box, _message: Box>, ) -> Result { Ok(Default::default()) @@ -180,7 +180,7 @@ impl QueryController for () { fn query( _origin: Origin, _timeout: Timeout, - _match_querier: VersionedMultiLocation, + _match_querier: VersionedLocation, ) -> Result { Ok(Default::default()) } diff --git a/polkadot/xcm/xcm-builder/src/currency_adapter.rs b/polkadot/xcm/xcm-builder/src/currency_adapter.rs index 8ecf1dee72db..6701bafabb97 100644 --- a/polkadot/xcm/xcm-builder/src/currency_adapter.rs +++ b/polkadot/xcm/xcm-builder/src/currency_adapter.rs @@ -20,17 +20,17 @@ use super::MintLocation; use frame_support::traits::{ExistenceRequirement::AllowDeath, Get, WithdrawReasons}; use sp_runtime::traits::CheckedSub; use sp_std::{marker::PhantomData, result}; -use xcm::latest::{Error as XcmError, MultiAsset, MultiLocation, Result, XcmContext}; +use xcm::latest::{Asset, Error as XcmError, Location, Result, XcmContext}; use xcm_executor::{ traits::{ConvertLocation, MatchesFungible, TransactAsset}, - Assets, + AssetsInHolding, }; /// Asset transaction errors. enum Error { /// The given asset is not handled. (According to [`XcmError::AssetNotFound`]) AssetNotHandled, - /// `MultiLocation` to `AccountId` conversion failed. + /// `Location` to `AccountId` conversion failed. AccountIdConversionFailed, } @@ -60,7 +60,7 @@ impl From for XcmError { /// /// /// Our relay chain's location. /// parameter_types! { -/// pub RelayChain: MultiLocation = Parent.into(); +/// pub RelayChain: Location = Parent.into(); /// pub CheckingAccount: AccountId = PalletId(*b"checking").into_account_truncating(); /// } /// @@ -139,7 +139,7 @@ impl< > TransactAsset for CurrencyAdapter { - fn can_check_in(_origin: &MultiLocation, what: &MultiAsset, _context: &XcmContext) -> Result { + fn can_check_in(_origin: &Location, what: &Asset, _context: &XcmContext) -> Result { log::trace!(target: "xcm::currency_adapter", "can_check_in origin: {:?}, what: {:?}", _origin, what); // Check we handle this asset. let amount: Currency::Balance = @@ -153,7 +153,7 @@ impl< } } - fn check_in(_origin: &MultiLocation, what: &MultiAsset, _context: &XcmContext) { + fn check_in(_origin: &Location, what: &Asset, _context: &XcmContext) { log::trace!(target: "xcm::currency_adapter", "check_in origin: {:?}, what: {:?}", _origin, what); if let Some(amount) = Matcher::matches_fungible(what) { match CheckedAccount::get() { @@ -166,7 +166,7 @@ impl< } } - fn can_check_out(_dest: &MultiLocation, what: &MultiAsset, _context: &XcmContext) -> Result { + fn can_check_out(_dest: &Location, what: &Asset, _context: &XcmContext) -> Result { log::trace!(target: "xcm::currency_adapter", "check_out dest: {:?}, what: {:?}", _dest, what); let amount = Matcher::matches_fungible(what).ok_or(Error::AssetNotHandled)?; match CheckedAccount::get() { @@ -178,7 +178,7 @@ impl< } } - fn check_out(_dest: &MultiLocation, what: &MultiAsset, _context: &XcmContext) { + fn check_out(_dest: &Location, what: &Asset, _context: &XcmContext) { log::trace!(target: "xcm::currency_adapter", "check_out dest: {:?}, what: {:?}", _dest, what); if let Some(amount) = Matcher::matches_fungible(what) { match CheckedAccount::get() { @@ -192,8 +192,8 @@ impl< } fn deposit_asset( - what: &MultiAsset, - who: &MultiLocation, + what: &Asset, + who: &Location, _context: Option<&XcmContext>, ) -> Result { log::trace!(target: "xcm::currency_adapter", "deposit_asset what: {:?}, who: {:?}", what, who); @@ -206,10 +206,10 @@ impl< } fn withdraw_asset( - what: &MultiAsset, - who: &MultiLocation, + what: &Asset, + who: &Location, _maybe_context: Option<&XcmContext>, - ) -> result::Result { + ) -> result::Result { log::trace!(target: "xcm::currency_adapter", "withdraw_asset what: {:?}, who: {:?}", what, who); // Check we handle this asset. let amount = Matcher::matches_fungible(what).ok_or(Error::AssetNotHandled)?; @@ -221,11 +221,11 @@ impl< } fn internal_transfer_asset( - asset: &MultiAsset, - from: &MultiLocation, - to: &MultiLocation, + asset: &Asset, + from: &Location, + to: &Location, _context: &XcmContext, - ) -> result::Result { + ) -> result::Result { log::trace!(target: "xcm::currency_adapter", "internal_transfer_asset asset: {:?}, from: {:?}, to: {:?}", asset, from, to); let amount = Matcher::matches_fungible(asset).ok_or(Error::AssetNotHandled)?; let from = diff --git a/polkadot/xcm/xcm-builder/src/fee_handling.rs b/polkadot/xcm/xcm-builder/src/fee_handling.rs index c158d5d862d7..6b126023370c 100644 --- a/polkadot/xcm/xcm-builder/src/fee_handling.rs +++ b/polkadot/xcm/xcm-builder/src/fee_handling.rs @@ -25,27 +25,27 @@ pub trait HandleFee { /// fees. /// /// Returns any part of the fee that wasn't consumed. - fn handle_fee(fee: MultiAssets, context: Option<&XcmContext>, reason: FeeReason) - -> MultiAssets; + fn handle_fee(fee: Assets, context: Option<&XcmContext>, reason: FeeReason) + -> Assets; } // Default `HandleFee` implementation that just burns the fee. impl HandleFee for () { - fn handle_fee(_: MultiAssets, _: Option<&XcmContext>, _: FeeReason) -> MultiAssets { - MultiAssets::new() + fn handle_fee(_: Assets, _: Option<&XcmContext>, _: FeeReason) -> Assets { + Assets::new() } } #[impl_trait_for_tuples::impl_for_tuples(1, 30)] impl HandleFee for Tuple { fn handle_fee( - fee: MultiAssets, + fee: Assets, context: Option<&XcmContext>, reason: FeeReason, - ) -> MultiAssets { + ) -> Assets { let mut unconsumed_fee = fee; for_tuples!( #( - unconsumed_fee = Tuple::handle_fee(unconsumed_fee, context, reason); + unconsumed_fee = Tuple::handle_fee(unconsumed_fee, context, reason.clone()); if unconsumed_fee.is_none() { return unconsumed_fee; } @@ -60,15 +60,15 @@ impl HandleFee for Tuple { pub struct XcmFeeManagerFromComponents( PhantomData<(WaivedLocations, HandleFee)>, ); -impl, FeeHandler: HandleFee> FeeManager +impl, FeeHandler: HandleFee> FeeManager for XcmFeeManagerFromComponents { - fn is_waived(origin: Option<&MultiLocation>, _: FeeReason) -> bool { + fn is_waived(origin: Option<&Location>, _: FeeReason) -> bool { let Some(loc) = origin else { return false }; WaivedLocations::contains(loc) } - fn handle_fee(fee: MultiAssets, context: Option<&XcmContext>, reason: FeeReason) { + fn handle_fee(fee: Assets, context: Option<&XcmContext>, reason: FeeReason) { FeeHandler::handle_fee(fee, context, reason); } } @@ -76,7 +76,7 @@ impl, FeeHandler: HandleFee> FeeManager /// Try to deposit the given fee in the specified account. /// Burns the fee in case of a failure. pub fn deposit_or_burn_fee>( - fee: MultiAssets, + fee: Assets, context: Option<&XcmContext>, receiver: AccountId, ) { @@ -110,12 +110,12 @@ impl< > HandleFee for XcmFeeToAccount { fn handle_fee( - fee: MultiAssets, + fee: Assets, context: Option<&XcmContext>, _reason: FeeReason, - ) -> MultiAssets { + ) -> Assets { deposit_or_burn_fee::(fee, context, ReceiverAccount::get()); - MultiAssets::new() + Assets::new() } } diff --git a/polkadot/xcm/xcm-builder/src/filter_asset_location.rs b/polkadot/xcm/xcm-builder/src/filter_asset_location.rs index df81f536f7b7..d80c5d70deea 100644 --- a/polkadot/xcm/xcm-builder/src/filter_asset_location.rs +++ b/polkadot/xcm/xcm-builder/src/filter_asset_location.rs @@ -14,28 +14,26 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -//! Various implementations of `ContainsPair` or -//! `Contains<(MultiLocation, Vec)>`. +//! Various implementations of `ContainsPair` or +//! `Contains<(Location, Vec)>`. use frame_support::traits::{Contains, ContainsPair, Get}; use sp_std::{marker::PhantomData, vec::Vec}; -use xcm::latest::{AssetId::Concrete, MultiAsset, MultiAssetFilter, MultiLocation, WildMultiAsset}; +use xcm::latest::{Asset, AssetFilter, AssetId, Location, WildAsset}; /// Accepts an asset iff it is a native asset. pub struct NativeAsset; -impl ContainsPair for NativeAsset { - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool { +impl ContainsPair for NativeAsset { + fn contains(asset: &Asset, origin: &Location) -> bool { log::trace!(target: "xcm::contains", "NativeAsset asset: {:?}, origin: {:?}", asset, origin); - matches!(asset.id, Concrete(ref id) if id == origin) + matches!(asset.id, AssetId(ref id) if id == origin) } } /// Accepts an asset if it is contained in the given `T`'s `Get` implementation. pub struct Case(PhantomData); -impl> ContainsPair - for Case -{ - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool { +impl> ContainsPair for Case { + fn contains(asset: &Asset, origin: &Location) -> bool { log::trace!(target: "xcm::contains", "Case asset: {:?}, origin: {:?}", asset, origin); let (a, o) = T::get(); a.matches(asset) && &o == origin @@ -44,18 +42,18 @@ impl> ContainsPair( - sp_std::marker::PhantomData<(Location, AssetFilters)>, +/// the `AssetFilter` instances provided by the `Get` implementation of `AssetFilters`. +pub struct LocationWithAssetFilters( + sp_std::marker::PhantomData<(LocationFilter, AssetFilters)>, ); -impl, AssetFilters: Get>> - Contains<(MultiLocation, Vec)> for LocationWithAssetFilters +impl, AssetFilters: Get>> + Contains<(Location, Vec)> for LocationWithAssetFilters { - fn contains((location, assets): &(MultiLocation, Vec)) -> bool { + fn contains((location, assets): &(Location, Vec)) -> bool { log::trace!(target: "xcm::contains", "LocationWithAssetFilters location: {:?}, assets: {:?}", location, assets); // `location` must match the `Location` filter. - if !Location::contains(location) { + if !LocationFilter::contains(location) { return false } @@ -72,12 +70,12 @@ impl, AssetFilters: Get> } } -/// Implementation of `Get>` which accepts every asset. +/// Implementation of `Get>` which accepts every asset. /// (For example, it can be used with `LocationWithAssetFilters`). pub struct AllAssets; -impl Get> for AllAssets { - fn get() -> Vec { - sp_std::vec![MultiAssetFilter::Wild(WildMultiAsset::All)] +impl Get> for AllAssets { + fn get() -> Vec { + sp_std::vec![AssetFilter::Wild(WildAsset::All)] } } @@ -90,24 +88,24 @@ mod tests { #[test] fn location_with_asset_filters_works() { frame_support::parameter_types! { - pub ParaA: MultiLocation = MultiLocation::new(1, X1(Parachain(1001))); - pub ParaB: MultiLocation = MultiLocation::new(1, X1(Parachain(1002))); - pub ParaC: MultiLocation = MultiLocation::new(1, X1(Parachain(1003))); + pub ParaA: Location = Location::new(1, [Parachain(1001)]); + pub ParaB: Location = Location::new(1, [Parachain(1002)]); + pub ParaC: Location = Location::new(1, [Parachain(1003)]); - pub AssetXLocation: MultiLocation = MultiLocation::new(1, X1(GeneralIndex(1111))); - pub AssetYLocation: MultiLocation = MultiLocation::new(1, X1(GeneralIndex(2222))); - pub AssetZLocation: MultiLocation = MultiLocation::new(1, X1(GeneralIndex(3333))); + pub AssetXLocation: Location = Location::new(1, [GeneralIndex(1111)]); + pub AssetYLocation: Location = Location::new(1, [GeneralIndex(2222)]); + pub AssetZLocation: Location = Location::new(1, [GeneralIndex(3333)]); - pub OnlyAssetXOrAssetY: sp_std::vec::Vec = sp_std::vec![ - Wild(AllOf { fun: WildFungible, id: Concrete(AssetXLocation::get()) }), - Wild(AllOf { fun: WildFungible, id: Concrete(AssetYLocation::get()) }), + pub OnlyAssetXOrAssetY: sp_std::vec::Vec = sp_std::vec![ + Wild(AllOf { fun: WildFungible, id: AssetId(AssetXLocation::get()) }), + Wild(AllOf { fun: WildFungible, id: AssetId(AssetYLocation::get()) }), ]; - pub OnlyAssetZ: sp_std::vec::Vec = sp_std::vec![ - Wild(AllOf { fun: WildFungible, id: Concrete(AssetZLocation::get()) }) + pub OnlyAssetZ: sp_std::vec::Vec = sp_std::vec![ + Wild(AllOf { fun: WildFungible, id: AssetId(AssetZLocation::get()) }) ]; } - let test_data: Vec<(MultiLocation, Vec, bool)> = vec![ + let test_data: Vec<(Location, Vec, bool)> = vec![ (ParaA::get(), vec![(AssetXLocation::get(), 1).into()], true), (ParaA::get(), vec![(AssetYLocation::get(), 1).into()], true), (ParaA::get(), vec![(AssetZLocation::get(), 1).into()], false), @@ -202,7 +200,7 @@ mod tests { for (location, assets, expected_result) in test_data { assert_eq!( - Filter::contains(&(location, assets.clone())), + Filter::contains(&(location.clone(), assets.clone())), expected_result, "expected_result: {expected_result} not matched for (location, assets): ({:?}, {:?})!", location, assets, ) diff --git a/polkadot/xcm/xcm-builder/src/fungibles_adapter.rs b/polkadot/xcm/xcm-builder/src/fungibles_adapter.rs index 63ce608824eb..704f1738cbf3 100644 --- a/polkadot/xcm/xcm-builder/src/fungibles_adapter.rs +++ b/polkadot/xcm/xcm-builder/src/fungibles_adapter.rs @@ -38,11 +38,11 @@ impl< > TransactAsset for FungiblesTransferAdapter { fn internal_transfer_asset( - what: &MultiAsset, - from: &MultiLocation, - to: &MultiLocation, + what: &Asset, + from: &Location, + to: &Location, _context: &XcmContext, - ) -> result::Result { + ) -> result::Result { log::trace!( target: "xcm::fungibles_adapter", "internal_transfer_asset what: {:?}, from: {:?}, to: {:?}", @@ -198,11 +198,7 @@ impl< CheckingAccount, > { - fn can_check_in( - _origin: &MultiLocation, - what: &MultiAsset, - _context: &XcmContext, - ) -> XcmResult { + fn can_check_in(_origin: &Location, what: &Asset, _context: &XcmContext) -> XcmResult { log::trace!( target: "xcm::fungibles_adapter", "can_check_in origin: {:?}, what: {:?}", @@ -219,7 +215,7 @@ impl< } } - fn check_in(_origin: &MultiLocation, what: &MultiAsset, _context: &XcmContext) { + fn check_in(_origin: &Location, what: &Asset, _context: &XcmContext) { log::trace!( target: "xcm::fungibles_adapter", "check_in origin: {:?}, what: {:?}", @@ -236,11 +232,7 @@ impl< } } - fn can_check_out( - _origin: &MultiLocation, - what: &MultiAsset, - _context: &XcmContext, - ) -> XcmResult { + fn can_check_out(_origin: &Location, what: &Asset, _context: &XcmContext) -> XcmResult { log::trace!( target: "xcm::fungibles_adapter", "can_check_in origin: {:?}, what: {:?}", @@ -257,7 +249,7 @@ impl< } } - fn check_out(_dest: &MultiLocation, what: &MultiAsset, _context: &XcmContext) { + fn check_out(_dest: &Location, what: &Asset, _context: &XcmContext) { log::trace!( target: "xcm::fungibles_adapter", "check_out dest: {:?}, what: {:?}", @@ -275,8 +267,8 @@ impl< } fn deposit_asset( - what: &MultiAsset, - who: &MultiLocation, + what: &Asset, + who: &Location, _context: Option<&XcmContext>, ) -> XcmResult { log::trace!( @@ -294,10 +286,10 @@ impl< } fn withdraw_asset( - what: &MultiAsset, - who: &MultiLocation, + what: &Asset, + who: &Location, _maybe_context: Option<&XcmContext>, - ) -> result::Result { + ) -> result::Result { log::trace!( target: "xcm::fungibles_adapter", "withdraw_asset what: {:?}, who: {:?}", @@ -331,7 +323,7 @@ impl< > TransactAsset for FungiblesAdapter { - fn can_check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { + fn can_check_in(origin: &Location, what: &Asset, context: &XcmContext) -> XcmResult { FungiblesMutateAdapter::< Assets, Matcher, @@ -342,7 +334,7 @@ impl< >::can_check_in(origin, what, context) } - fn check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) { + fn check_in(origin: &Location, what: &Asset, context: &XcmContext) { FungiblesMutateAdapter::< Assets, Matcher, @@ -353,7 +345,7 @@ impl< >::check_in(origin, what, context) } - fn can_check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { + fn can_check_out(dest: &Location, what: &Asset, context: &XcmContext) -> XcmResult { FungiblesMutateAdapter::< Assets, Matcher, @@ -364,7 +356,7 @@ impl< >::can_check_out(dest, what, context) } - fn check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) { + fn check_out(dest: &Location, what: &Asset, context: &XcmContext) { FungiblesMutateAdapter::< Assets, Matcher, @@ -376,8 +368,8 @@ impl< } fn deposit_asset( - what: &MultiAsset, - who: &MultiLocation, + what: &Asset, + who: &Location, context: Option<&XcmContext>, ) -> XcmResult { FungiblesMutateAdapter::< @@ -391,10 +383,10 @@ impl< } fn withdraw_asset( - what: &MultiAsset, - who: &MultiLocation, + what: &Asset, + who: &Location, maybe_context: Option<&XcmContext>, - ) -> result::Result { + ) -> result::Result { FungiblesMutateAdapter::< Assets, Matcher, @@ -406,11 +398,11 @@ impl< } fn internal_transfer_asset( - what: &MultiAsset, - from: &MultiLocation, - to: &MultiLocation, + what: &Asset, + from: &Location, + to: &Location, context: &XcmContext, - ) -> result::Result { + ) -> result::Result { FungiblesTransferAdapter::::internal_transfer_asset( what, from, to, context ) diff --git a/polkadot/xcm/xcm-builder/src/lib.rs b/polkadot/xcm/xcm-builder/src/lib.rs index 35f95b85c89c..2347901a68f3 100644 --- a/polkadot/xcm/xcm-builder/src/lib.rs +++ b/polkadot/xcm/xcm-builder/src/lib.rs @@ -47,11 +47,11 @@ pub use origin_conversion::{ }; mod asset_conversion; +#[allow(deprecated)] +pub use asset_conversion::ConvertedConcreteAssetId; pub use asset_conversion::{ - AsPrefixedGeneralIndex, ConvertedAbstractId, ConvertedConcreteId, MatchedConvertedConcreteId, + AsPrefixedGeneralIndex, ConvertedConcreteId, MatchedConvertedConcreteId, }; -#[allow(deprecated)] -pub use asset_conversion::{ConvertedAbstractAssetId, ConvertedConcreteAssetId}; mod barriers; pub use barriers::{ @@ -92,7 +92,7 @@ mod matches_location; pub use matches_location::{StartsWith, StartsWithExplicitGlobalConsensus}; mod matches_token; -pub use matches_token::{IsAbstract, IsConcrete}; +pub use matches_token::IsConcrete; mod matcher; pub use matcher::{CreateMatcher, MatchXcm, Matcher}; diff --git a/polkadot/xcm/xcm-builder/src/location_conversion.rs b/polkadot/xcm/xcm-builder/src/location_conversion.rs index 25d16f7eb8cc..b8796530495f 100644 --- a/polkadot/xcm/xcm-builder/src/location_conversion.rs +++ b/polkadot/xcm/xcm-builder/src/location_conversion.rs @@ -27,12 +27,12 @@ use xcm_executor::traits::ConvertLocation; pub trait DescribeLocation { /// Create a description of the given `location` if possible. No two locations should have the /// same descriptor. - fn describe_location(location: &MultiLocation) -> Option>; + fn describe_location(location: &Location) -> Option>; } #[impl_trait_for_tuples::impl_for_tuples(30)] impl DescribeLocation for Tuple { - fn describe_location(l: &MultiLocation) -> Option> { + fn describe_location(l: &Location) -> Option> { for_tuples!( #( match Tuple::describe_location(l) { Some(result) => return Some(result), @@ -45,9 +45,9 @@ impl DescribeLocation for Tuple { pub struct DescribeTerminus; impl DescribeLocation for DescribeTerminus { - fn describe_location(l: &MultiLocation) -> Option> { - match (l.parents, &l.interior) { - (0, Here) => Some(Vec::new()), + fn describe_location(l: &Location) -> Option> { + match l.unpack() { + (0, HERE) => Some(Vec::new()), _ => return None, } } @@ -55,10 +55,9 @@ impl DescribeLocation for DescribeTerminus { pub struct DescribePalletTerminal; impl DescribeLocation for DescribePalletTerminal { - fn describe_location(l: &MultiLocation) -> Option> { - match (l.parents, &l.interior) { - (0, X1(PalletInstance(i))) => - Some((b"Pallet", Compact::::from(*i as u32)).encode()), + fn describe_location(l: &Location) -> Option> { + match l.unpack() { + (0, [PalletInstance(i)]) => Some((b"Pallet", Compact::::from(*i as u32)).encode()), _ => return None, } } @@ -66,9 +65,9 @@ impl DescribeLocation for DescribePalletTerminal { pub struct DescribeAccountId32Terminal; impl DescribeLocation for DescribeAccountId32Terminal { - fn describe_location(l: &MultiLocation) -> Option> { - match (l.parents, &l.interior) { - (0, X1(AccountId32 { id, .. })) => Some((b"AccountId32", id).encode()), + fn describe_location(l: &Location) -> Option> { + match l.unpack() { + (0, [AccountId32 { id, .. }]) => Some((b"AccountId32", id).encode()), _ => return None, } } @@ -76,9 +75,9 @@ impl DescribeLocation for DescribeAccountId32Terminal { pub struct DescribeAccountKey20Terminal; impl DescribeLocation for DescribeAccountKey20Terminal { - fn describe_location(l: &MultiLocation) -> Option> { - match (l.parents, &l.interior) { - (0, X1(AccountKey20 { key, .. })) => Some((b"AccountKey20", key).encode()), + fn describe_location(l: &Location) -> Option> { + match l.unpack() { + (0, [AccountKey20 { key, .. }]) => Some((b"AccountKey20", key).encode()), _ => return None, } } @@ -89,9 +88,9 @@ impl DescribeLocation for DescribeAccountKey20Terminal { pub struct DescribeTreasuryVoiceTerminal; impl DescribeLocation for DescribeTreasuryVoiceTerminal { - fn describe_location(l: &MultiLocation) -> Option> { - match (l.parents, &l.interior) { - (0, X1(Plurality { id: BodyId::Treasury, part: BodyPart::Voice })) => + fn describe_location(location: &Location) -> Option> { + match location.unpack() { + (0, [Plurality { id: BodyId::Treasury, part: BodyPart::Voice }]) => Some((b"Treasury", b"Voice").encode()), _ => None, } @@ -102,9 +101,9 @@ pub type DescribeAccountIdTerminal = (DescribeAccountId32Terminal, DescribeAccou pub struct DescribeBodyTerminal; impl DescribeLocation for DescribeBodyTerminal { - fn describe_location(l: &MultiLocation) -> Option> { - match (l.parents, &l.interior) { - (0, X1(Plurality { id, part })) => Some((b"Body", id, part).encode()), + fn describe_location(l: &Location) -> Option> { + match l.unpack() { + (0, [Plurality { id, part }]) => Some((b"Body", id, part).encode()), _ => return None, } } @@ -121,20 +120,21 @@ pub type DescribeAllTerminal = ( pub struct DescribeFamily(PhantomData); impl DescribeLocation for DescribeFamily { - fn describe_location(l: &MultiLocation) -> Option> { - match (l.parents, l.interior.first()) { + fn describe_location(l: &Location) -> Option> { + match (l.parent_count(), l.first_interior()) { (0, Some(Parachain(index))) => { - let tail = l.interior.split_first().0; + let tail = l.clone().split_first_interior().0; let interior = Suffix::describe_location(&tail.into())?; Some((b"ChildChain", Compact::::from(*index), interior).encode()) }, (1, Some(Parachain(index))) => { - let tail = l.interior.split_first().0; - let interior = Suffix::describe_location(&tail.into())?; + let tail_junctions = l.interior().clone().split_first().0; + let tail = Location::new(0, tail_junctions); + let interior = Suffix::describe_location(&tail)?; Some((b"SiblingChain", Compact::::from(*index), interior).encode()) }, (1, _) => { - let tail = l.interior.into(); + let tail = l.interior().clone().into(); let interior = Suffix::describe_location(&tail)?; Some((b"ParentChain", interior).encode()) }, @@ -147,7 +147,7 @@ pub struct HashedDescription(PhantomData<(AccountId, Descri impl + Clone, Describe: DescribeLocation> ConvertLocation for HashedDescription { - fn convert_location(value: &MultiLocation) -> Option { + fn convert_location(value: &Location) -> Option { Some(blake2_256(&Describe::describe_location(value)?).into()) } } @@ -156,34 +156,26 @@ impl + Clone, Describe: DescribeLocation> ConvertLocat /// are recommended to use the more extensible `HashedDescription` type. pub struct LegacyDescribeForeignChainAccount; impl DescribeLocation for LegacyDescribeForeignChainAccount { - fn describe_location(location: &MultiLocation) -> Option> { - Some(match location { + fn describe_location(location: &Location) -> Option> { + Some(match location.unpack() { // Used on the relay chain for sending paras that use 32 byte accounts - MultiLocation { - parents: 0, - interior: X2(Parachain(para_id), AccountId32 { id, .. }), - } => LegacyDescribeForeignChainAccount::from_para_32(para_id, id, 0), + (0, [Parachain(para_id), AccountId32 { id, .. }]) => + LegacyDescribeForeignChainAccount::from_para_32(para_id, id, 0), // Used on the relay chain for sending paras that use 20 byte accounts - MultiLocation { - parents: 0, - interior: X2(Parachain(para_id), AccountKey20 { key, .. }), - } => LegacyDescribeForeignChainAccount::from_para_20(para_id, key, 0), + (0, [Parachain(para_id), AccountKey20 { key, .. }]) => + LegacyDescribeForeignChainAccount::from_para_20(para_id, key, 0), // Used on para-chain for sending paras that use 32 byte accounts - MultiLocation { - parents: 1, - interior: X2(Parachain(para_id), AccountId32 { id, .. }), - } => LegacyDescribeForeignChainAccount::from_para_32(para_id, id, 1), + (1, [Parachain(para_id), AccountId32 { id, .. }]) => + LegacyDescribeForeignChainAccount::from_para_32(para_id, id, 1), // Used on para-chain for sending paras that use 20 byte accounts - MultiLocation { - parents: 1, - interior: X2(Parachain(para_id), AccountKey20 { key, .. }), - } => LegacyDescribeForeignChainAccount::from_para_20(para_id, key, 1), + (1, [Parachain(para_id), AccountKey20 { key, .. }]) => + LegacyDescribeForeignChainAccount::from_para_20(para_id, key, 1), // Used on para-chain for sending from the relay chain - MultiLocation { parents: 1, interior: X1(AccountId32 { id, .. }) } => + (1, [AccountId32 { id, .. }]) => LegacyDescribeForeignChainAccount::from_relay_32(id, 1), // No other conversions provided @@ -278,16 +270,16 @@ pub struct Account32Hash(PhantomData<(Network, AccountId)>); impl>, AccountId: From<[u8; 32]> + Into<[u8; 32]> + Clone> ConvertLocation for Account32Hash { - fn convert_location(location: &MultiLocation) -> Option { + fn convert_location(location: &Location) -> Option { Some(("multiloc", location).using_encoded(blake2_256).into()) } } -/// A [`MultiLocation`] consisting of a single `Parent` [`Junction`] will be converted to the +/// A [`Location`] consisting of a single `Parent` [`Junction`] will be converted to the /// parent `AccountId`. pub struct ParentIsPreset(PhantomData); impl ConvertLocation for ParentIsPreset { - fn convert_location(location: &MultiLocation) -> Option { + fn convert_location(location: &Location) -> Option { if location.contains_parents_only(1) { Some( b"Parent" @@ -304,10 +296,9 @@ pub struct ChildParachainConvertsVia(PhantomData<(ParaId, Acc impl + Into + AccountIdConversion, AccountId: Clone> ConvertLocation for ChildParachainConvertsVia { - fn convert_location(location: &MultiLocation) -> Option { - match location { - MultiLocation { parents: 0, interior: X1(Parachain(id)) } => - Some(ParaId::from(*id).into_account_truncating()), + fn convert_location(location: &Location) -> Option { + match location.unpack() { + (0, [Parachain(id)]) => Some(ParaId::from(*id).into_account_truncating()), _ => None, } } @@ -317,10 +308,9 @@ pub struct SiblingParachainConvertsVia(PhantomData<(ParaId, A impl + Into + AccountIdConversion, AccountId: Clone> ConvertLocation for SiblingParachainConvertsVia { - fn convert_location(location: &MultiLocation) -> Option { - match location { - MultiLocation { parents: 1, interior: X1(Parachain(id)) } => - Some(ParaId::from(*id).into_account_truncating()), + fn convert_location(location: &Location) -> Option { + match location.unpack() { + (1, [Parachain(id)]) => Some(ParaId::from(*id).into_account_truncating()), _ => None, } } @@ -331,15 +321,13 @@ pub struct AccountId32Aliases(PhantomData<(Network, AccountI impl>, AccountId: From<[u8; 32]> + Into<[u8; 32]> + Clone> ConvertLocation for AccountId32Aliases { - fn convert_location(location: &MultiLocation) -> Option { - let id = match *location { - MultiLocation { parents: 0, interior: X1(AccountId32 { id, network: None }) } => id, - MultiLocation { parents: 0, interior: X1(AccountId32 { id, network }) } - if network == Network::get() => - id, + fn convert_location(location: &Location) -> Option { + let id = match location.unpack() { + (0, [AccountId32 { id, network: None }]) => id, + (0, [AccountId32 { id, network }]) if *network == Network::get() => id, _ => return None, }; - Some(id.into()) + Some((*id).into()) } } @@ -351,25 +339,22 @@ pub struct LocalTreasuryVoiceConvertsVia( impl, AccountId: From<[u8; 32]> + Into<[u8; 32]> + Clone> ConvertLocation for LocalTreasuryVoiceConvertsVia { - fn convert_location(location: &MultiLocation) -> Option { - match *location { - MultiLocation { - parents: 0, - interior: X1(Plurality { id: BodyId::Treasury, part: BodyPart::Voice }), - } => Some((TreasuryAccount::get().into() as [u8; 32]).into()), + fn convert_location(location: &Location) -> Option { + match location.unpack() { + (0, [Plurality { id: BodyId::Treasury, part: BodyPart::Voice }]) => Some((TreasuryAccount::get().into() as [u8; 32]).into()), _ => None, } } } /// Conversion implementation which converts from a `[u8; 32]`-based `AccountId` into a -/// `MultiLocation` consisting solely of a `AccountId32` junction with a fixed value for its +/// `Location` consisting solely of a `AccountId32` junction with a fixed value for its /// network (provided by `Network`) and the `AccountId`'s `[u8; 32]` datum for the `id`. pub struct AliasesIntoAccountId32(PhantomData<(Network, AccountId)>); impl<'a, Network: Get>, AccountId: Clone + Into<[u8; 32]> + Clone> - TryConvert<&'a AccountId, MultiLocation> for AliasesIntoAccountId32 + TryConvert<&'a AccountId, Location> for AliasesIntoAccountId32 { - fn try_convert(who: &AccountId) -> Result { + fn try_convert(who: &AccountId) -> Result { Ok(AccountId32 { network: Network::get(), id: who.clone().into() }.into()) } } @@ -378,15 +363,13 @@ pub struct AccountKey20Aliases(PhantomData<(Network, Account impl>, AccountId: From<[u8; 20]> + Into<[u8; 20]> + Clone> ConvertLocation for AccountKey20Aliases { - fn convert_location(location: &MultiLocation) -> Option { - let key = match *location { - MultiLocation { parents: 0, interior: X1(AccountKey20 { key, network: None }) } => key, - MultiLocation { parents: 0, interior: X1(AccountKey20 { key, network }) } - if network == Network::get() => - key, + fn convert_location(location: &Location) -> Option { + let key = match location.unpack() { + (0, [AccountKey20 { key, network: None }]) => key, + (0, [AccountKey20 { key, network }]) if *network == Network::get() => key, _ => return None, }; - Some(key.into()) + Some((*key).into()) } } @@ -402,10 +385,10 @@ impl>, AccountId: From<[u8; 20]> + Into<[u8; 20]> pub struct GlobalConsensusConvertsFor( PhantomData<(UniversalLocation, AccountId)>, ); -impl, AccountId: From<[u8; 32]> + Clone> +impl, AccountId: From<[u8; 32]> + Clone> ConvertLocation for GlobalConsensusConvertsFor { - fn convert_location(location: &MultiLocation) -> Option { + fn convert_location(location: &Location) -> Option { let universal_source = UniversalLocation::get(); log::trace!( target: "xcm::location_conversion", @@ -413,7 +396,7 @@ impl, AccountId: From<[u8; 32]> + universal_source, location, ); let (remote_network, remote_location) = - ensure_is_remote(universal_source, *location).ok()?; + ensure_is_remote(universal_source, location.clone()).ok()?; match remote_location { Here => Some(AccountId::from(Self::from_params(&remote_network))), @@ -445,21 +428,21 @@ impl GlobalConsensusConvertsFor( PhantomData<(UniversalLocation, AccountId)>, ); -impl, AccountId: From<[u8; 32]> + Clone> +impl, AccountId: From<[u8; 32]> + Clone> ConvertLocation for GlobalConsensusParachainConvertsFor { - fn convert_location(location: &MultiLocation) -> Option { + fn convert_location(location: &Location) -> Option { let universal_source = UniversalLocation::get(); log::trace!( target: "xcm::location_conversion", "GlobalConsensusParachainConvertsFor universal_source: {:?}, location: {:?}", universal_source, location, ); - let devolved = ensure_is_remote(universal_source, *location).ok()?; + let devolved = ensure_is_remote(universal_source, location.clone()).ok()?; let (remote_network, remote_location) = devolved; - match remote_location { - X1(Parachain(remote_network_para_id)) => + match remote_location.as_slice() { + [Parachain(remote_network_para_id)] => Some(AccountId::from(Self::from_params(&remote_network, &remote_network_para_id))), _ => None, } @@ -509,12 +492,12 @@ mod tests { #[test] fn inverter_works_in_tree() { parameter_types! { - pub UniversalLocation: InteriorMultiLocation = X3(Parachain(1), account20(), account20()); + pub UniversalLocation: InteriorLocation = [Parachain(1), account20(), account20()].into(); } - let input = MultiLocation::new(3, X2(Parachain(2), account32())); + let input = Location::new(3, [Parachain(2), account32()]); let inverted = UniversalLocation::get().invert_target(&input).unwrap(); - assert_eq!(inverted, MultiLocation::new(2, X3(Parachain(1), account20(), account20()))); + assert_eq!(inverted, Location::new(2, [Parachain(1), account20(), account20()])); } // Network Topology @@ -524,12 +507,12 @@ mod tests { #[test] fn inverter_uses_context_as_inverted_location() { parameter_types! { - pub UniversalLocation: InteriorMultiLocation = X2(account20(), account20()); + pub UniversalLocation: InteriorLocation = [account20(), account20()].into(); } - let input = MultiLocation::grandparent(); + let input = Location::grandparent(); let inverted = UniversalLocation::get().invert_target(&input).unwrap(); - assert_eq!(inverted, X2(account20(), account20()).into()); + assert_eq!(inverted, [account20(), account20()].into()); } // Network Topology @@ -539,10 +522,10 @@ mod tests { #[test] fn inverter_uses_only_child_on_missing_context() { parameter_types! { - pub UniversalLocation: InteriorMultiLocation = PalletInstance(5).into(); + pub UniversalLocation: InteriorLocation = PalletInstance(5).into(); } - let input = MultiLocation::grandparent(); + let input = Location::grandparent(); let inverted = UniversalLocation::get().invert_target(&input).unwrap(); assert_eq!(inverted, (OnlyChild, PalletInstance(5)).into()); } @@ -550,10 +533,10 @@ mod tests { #[test] fn inverter_errors_when_location_is_too_large() { parameter_types! { - pub UniversalLocation: InteriorMultiLocation = Here; + pub UniversalLocation: InteriorLocation = Here; } - let input = MultiLocation { parents: 99, interior: X1(Parachain(88)) }; + let input = Location { parents: 99, interior: [Parachain(88)].into() }; let inverted = UniversalLocation::get().invert_target(&input); assert_eq!(inverted, Err(())); } @@ -561,8 +544,8 @@ mod tests { #[test] fn global_consensus_converts_for_works() { parameter_types! { - pub UniversalLocationInNetwork1: InteriorMultiLocation = X2(GlobalConsensus(ByGenesis([1; 32])), Parachain(1234)); - pub UniversalLocationInNetwork2: InteriorMultiLocation = X2(GlobalConsensus(ByGenesis([2; 32])), Parachain(1234)); + pub UniversalLocationInNetwork1: InteriorLocation = [GlobalConsensus(ByGenesis([1; 32])), Parachain(1234)].into(); + pub UniversalLocationInNetwork2: InteriorLocation = [GlobalConsensus(ByGenesis([2; 32])), Parachain(1234)].into(); } let network_1 = UniversalLocationInNetwork1::get().global_consensus().expect("NetworkId"); let network_2 = UniversalLocationInNetwork2::get().global_consensus().expect("NetworkId"); @@ -571,17 +554,17 @@ mod tests { let network_5 = ByGenesis([5; 32]); let test_data = vec![ - (MultiLocation::parent(), false), - (MultiLocation::new(0, Here), false), - (MultiLocation::new(0, X1(GlobalConsensus(network_1))), false), - (MultiLocation::new(1, X1(GlobalConsensus(network_1))), false), - (MultiLocation::new(2, X1(GlobalConsensus(network_1))), false), - (MultiLocation::new(0, X1(GlobalConsensus(network_2))), false), - (MultiLocation::new(1, X1(GlobalConsensus(network_2))), false), - (MultiLocation::new(2, X1(GlobalConsensus(network_2))), true), - (MultiLocation::new(0, X2(GlobalConsensus(network_2), Parachain(1000))), false), - (MultiLocation::new(1, X2(GlobalConsensus(network_2), Parachain(1000))), false), - (MultiLocation::new(2, X2(GlobalConsensus(network_2), Parachain(1000))), false), + (Location::parent(), false), + (Location::new(0, Here), false), + (Location::new(0, [GlobalConsensus(network_1)]), false), + (Location::new(1, [GlobalConsensus(network_1)]), false), + (Location::new(2, [GlobalConsensus(network_1)]), false), + (Location::new(0, [GlobalConsensus(network_2)]), false), + (Location::new(1, [GlobalConsensus(network_2)]), false), + (Location::new(2, [GlobalConsensus(network_2)]), true), + (Location::new(0, [GlobalConsensus(network_2), Parachain(1000)]), false), + (Location::new(1, [GlobalConsensus(network_2), Parachain(1000)]), false), + (Location::new(2, [GlobalConsensus(network_2), Parachain(1000)]), false), ]; for (location, expected_result) in test_data { @@ -596,14 +579,14 @@ mod tests { "expected_result: {}, but conversion passed: {:?}, location: {:?}", expected_result, account, location ); - match &location { - MultiLocation { interior: X1(GlobalConsensus(network)), .. } => + match location.unpack() { + (_, [GlobalConsensus(network)]) => assert_eq!( account, GlobalConsensusConvertsFor::::from_params(network), "expected_result: {}, but conversion passed: {:?}, location: {:?}", expected_result, account, location ), - _ => panic!("expected_result: {}, conversion passed: {:?}, but MultiLocation does not match expected pattern, location: {:?}", expected_result, account, location) + _ => panic!("expected_result: {}, conversion passed: {:?}, but Location does not match expected pattern, location: {:?}", expected_result, account, location) } }, None => { @@ -619,32 +602,32 @@ mod tests { // all success let res_1_gc_network_3 = GlobalConsensusConvertsFor::::convert_location( - &MultiLocation::new(2, X1(GlobalConsensus(network_3))), + &Location::new(2, [GlobalConsensus(network_3)]), ) .expect("conversion is ok"); let res_2_gc_network_3 = GlobalConsensusConvertsFor::::convert_location( - &MultiLocation::new(2, X1(GlobalConsensus(network_3))), + &Location::new(2, [GlobalConsensus(network_3)]), ) .expect("conversion is ok"); let res_1_gc_network_4 = GlobalConsensusConvertsFor::::convert_location( - &MultiLocation::new(2, X1(GlobalConsensus(network_4))), + &Location::new(2, [GlobalConsensus(network_4)]), ) .expect("conversion is ok"); let res_2_gc_network_4 = GlobalConsensusConvertsFor::::convert_location( - &MultiLocation::new(2, X1(GlobalConsensus(network_4))), + &Location::new(2, [GlobalConsensus(network_4)]), ) .expect("conversion is ok"); let res_1_gc_network_5 = GlobalConsensusConvertsFor::::convert_location( - &MultiLocation::new(2, X1(GlobalConsensus(network_5))), + &Location::new(2, [GlobalConsensus(network_5)]), ) .expect("conversion is ok"); let res_2_gc_network_5 = GlobalConsensusConvertsFor::::convert_location( - &MultiLocation::new(2, X1(GlobalConsensus(network_5))), + &Location::new(2, [GlobalConsensus(network_5)]), ) .expect("conversion is ok"); @@ -660,42 +643,30 @@ mod tests { #[test] fn global_consensus_parachain_converts_for_works() { parameter_types! { - pub UniversalLocation: InteriorMultiLocation = X2(GlobalConsensus(ByGenesis([9; 32])), Parachain(1234)); + pub UniversalLocation: InteriorLocation = [GlobalConsensus(ByGenesis([9; 32])), Parachain(1234)].into(); } let test_data = vec![ - (MultiLocation::parent(), false), - (MultiLocation::new(0, X1(Parachain(1000))), false), - (MultiLocation::new(1, X1(Parachain(1000))), false), + (Location::parent(), false), + (Location::new(0, [Parachain(1000)]), false), + (Location::new(1, [Parachain(1000)]), false), ( - MultiLocation::new( + Location::new( 2, - X3( + [ GlobalConsensus(ByGenesis([0; 32])), Parachain(1000), AccountId32 { network: None, id: [1; 32].into() }, - ), + ], ), false, ), - (MultiLocation::new(2, X1(GlobalConsensus(ByGenesis([0; 32])))), false), - ( - MultiLocation::new(0, X2(GlobalConsensus(ByGenesis([0; 32])), Parachain(1000))), - false, - ), - ( - MultiLocation::new(1, X2(GlobalConsensus(ByGenesis([0; 32])), Parachain(1000))), - false, - ), - (MultiLocation::new(2, X2(GlobalConsensus(ByGenesis([0; 32])), Parachain(1000))), true), - ( - MultiLocation::new(3, X2(GlobalConsensus(ByGenesis([0; 32])), Parachain(1000))), - false, - ), - ( - MultiLocation::new(9, X2(GlobalConsensus(ByGenesis([0; 32])), Parachain(1000))), - false, - ), + (Location::new(2, [GlobalConsensus(ByGenesis([0; 32]))]), false), + (Location::new(0, [GlobalConsensus(ByGenesis([0; 32])), Parachain(1000)]), false), + (Location::new(1, [GlobalConsensus(ByGenesis([0; 32])), Parachain(1000)]), false), + (Location::new(2, [GlobalConsensus(ByGenesis([0; 32])), Parachain(1000)]), true), + (Location::new(3, [GlobalConsensus(ByGenesis([0; 32])), Parachain(1000)]), false), + (Location::new(9, [GlobalConsensus(ByGenesis([0; 32])), Parachain(1000)]), false), ]; for (location, expected_result) in test_data { @@ -710,8 +681,8 @@ mod tests { "expected_result: {}, but conversion passed: {:?}, location: {:?}", expected_result, account, location ); - match &location { - MultiLocation { interior: X2(GlobalConsensus(network), Parachain(para_id)), .. } => + match location.unpack() { + (_, [GlobalConsensus(network), Parachain(para_id)]) => assert_eq!( account, GlobalConsensusParachainConvertsFor::::from_params(network, para_id), @@ -720,7 +691,7 @@ mod tests { _ => assert_eq!( true, expected_result, - "expected_result: {}, conversion passed: {:?}, but MultiLocation does not match expected pattern, location: {:?}", expected_result, account, location + "expected_result: {}, conversion passed: {:?}, but Location does not match expected pattern, location: {:?}", expected_result, account, location ) } }, @@ -737,22 +708,22 @@ mod tests { // all success let res_gc_a_p1000 = GlobalConsensusParachainConvertsFor::::convert_location( - &MultiLocation::new(2, X2(GlobalConsensus(ByGenesis([3; 32])), Parachain(1000))), + &Location::new(2, [GlobalConsensus(ByGenesis([3; 32])), Parachain(1000)]), ) .expect("conversion is ok"); let res_gc_a_p1001 = GlobalConsensusParachainConvertsFor::::convert_location( - &MultiLocation::new(2, X2(GlobalConsensus(ByGenesis([3; 32])), Parachain(1001))), + &Location::new(2, [GlobalConsensus(ByGenesis([3; 32])), Parachain(1001)]), ) .expect("conversion is ok"); let res_gc_b_p1000 = GlobalConsensusParachainConvertsFor::::convert_location( - &MultiLocation::new(2, X2(GlobalConsensus(ByGenesis([4; 32])), Parachain(1000))), + &Location::new(2, [GlobalConsensus(ByGenesis([4; 32])), Parachain(1000)]), ) .expect("conversion is ok"); let res_gc_b_p1001 = GlobalConsensusParachainConvertsFor::::convert_location( - &MultiLocation::new(2, X2(GlobalConsensus(ByGenesis([4; 32])), Parachain(1001))), + &Location::new(2, [GlobalConsensus(ByGenesis([4; 32])), Parachain(1001)]), ) .expect("conversion is ok"); assert_ne!(res_gc_a_p1000, res_gc_a_p1001); @@ -765,9 +736,9 @@ mod tests { #[test] fn remote_account_convert_on_para_sending_para_32() { - let mul = MultiLocation { + let mul = Location { parents: 1, - interior: X2(Parachain(1), AccountId32 { network: None, id: [0u8; 32] }), + interior: [Parachain(1), AccountId32 { network: None, id: [0u8; 32] }].into(), }; let rem_1 = ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).unwrap(); @@ -779,19 +750,20 @@ mod tests { rem_1 ); - let mul = MultiLocation { + let mul = Location { parents: 1, - interior: X2( + interior: [ Parachain(1), AccountId32 { network: Some(NetworkId::Polkadot), id: [0u8; 32] }, - ), + ] + .into(), }; assert_eq!(ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).unwrap(), rem_1); - let mul = MultiLocation { + let mul = Location { parents: 1, - interior: X2(Parachain(2), AccountId32 { network: None, id: [0u8; 32] }), + interior: [Parachain(2), AccountId32 { network: None, id: [0u8; 32] }].into(), }; let rem_2 = ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).unwrap(); @@ -808,9 +780,9 @@ mod tests { #[test] fn remote_account_convert_on_para_sending_para_20() { - let mul = MultiLocation { + let mul = Location { parents: 1, - interior: X2(Parachain(1), AccountKey20 { network: None, key: [0u8; 20] }), + interior: [Parachain(1), AccountKey20 { network: None, key: [0u8; 20] }].into(), }; let rem_1 = ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).unwrap(); @@ -822,19 +794,20 @@ mod tests { rem_1 ); - let mul = MultiLocation { + let mul = Location { parents: 1, - interior: X2( + interior: [ Parachain(1), AccountKey20 { network: Some(NetworkId::Polkadot), key: [0u8; 20] }, - ), + ] + .into(), }; assert_eq!(ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).unwrap(), rem_1); - let mul = MultiLocation { + let mul = Location { parents: 1, - interior: X2(Parachain(2), AccountKey20 { network: None, key: [0u8; 20] }), + interior: [Parachain(2), AccountKey20 { network: None, key: [0u8; 20] }].into(), }; let rem_2 = ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).unwrap(); @@ -851,9 +824,9 @@ mod tests { #[test] fn remote_account_convert_on_para_sending_relay() { - let mul = MultiLocation { + let mul = Location { parents: 1, - interior: X1(AccountId32 { network: None, id: [0u8; 32] }), + interior: [AccountId32 { network: None, id: [0u8; 32] }].into(), }; let rem_1 = ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).unwrap(); @@ -865,16 +838,16 @@ mod tests { rem_1 ); - let mul = MultiLocation { + let mul = Location { parents: 1, - interior: X1(AccountId32 { network: Some(NetworkId::Polkadot), id: [0u8; 32] }), + interior: [AccountId32 { network: Some(NetworkId::Polkadot), id: [0u8; 32] }].into(), }; assert_eq!(ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).unwrap(), rem_1); - let mul = MultiLocation { + let mul = Location { parents: 1, - interior: X1(AccountId32 { network: None, id: [1u8; 32] }), + interior: [AccountId32 { network: None, id: [1u8; 32] }].into(), }; let rem_2 = ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).unwrap(); @@ -891,9 +864,9 @@ mod tests { #[test] fn remote_account_convert_on_relay_sending_para_20() { - let mul = MultiLocation { + let mul = Location { parents: 0, - interior: X2(Parachain(1), AccountKey20 { network: None, key: [0u8; 20] }), + interior: [Parachain(1), AccountKey20 { network: None, key: [0u8; 20] }].into(), }; let rem_1 = ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).unwrap(); @@ -905,9 +878,9 @@ mod tests { rem_1 ); - let mul = MultiLocation { + let mul = Location { parents: 0, - interior: X2(Parachain(2), AccountKey20 { network: None, key: [0u8; 20] }), + interior: [Parachain(2), AccountKey20 { network: None, key: [0u8; 20] }].into(), }; let rem_2 = ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).unwrap(); @@ -924,9 +897,9 @@ mod tests { #[test] fn remote_account_convert_on_relay_sending_para_32() { - let mul = MultiLocation { + let mul = Location { parents: 0, - interior: X2(Parachain(1), AccountId32 { network: None, id: [0u8; 32] }), + interior: [Parachain(1), AccountId32 { network: None, id: [0u8; 32] }].into(), }; let rem_1 = ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).unwrap(); @@ -938,19 +911,20 @@ mod tests { rem_1 ); - let mul = MultiLocation { + let mul = Location { parents: 0, - interior: X2( + interior: [ Parachain(1), AccountId32 { network: Some(NetworkId::Polkadot), id: [0u8; 32] }, - ), + ] + .into(), }; assert_eq!(ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).unwrap(), rem_1); - let mul = MultiLocation { + let mul = Location { parents: 0, - interior: X2(Parachain(2), AccountId32 { network: None, id: [0u8; 32] }), + interior: [Parachain(2), AccountId32 { network: None, id: [0u8; 32] }].into(), }; let rem_2 = ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).unwrap(); @@ -966,20 +940,17 @@ mod tests { } #[test] - fn remote_account_fails_with_bad_multilocation() { - let mul = MultiLocation { + fn remote_account_fails_with_bad_location() { + let mul = Location { parents: 1, - interior: X1(AccountKey20 { network: None, key: [0u8; 20] }), + interior: [AccountKey20 { network: None, key: [0u8; 20] }].into(), }; assert!(ForeignChainAliasAccount::<[u8; 32]>::convert_location(&mul).is_none()); } #[test] fn remote_account_convert_on_para_sending_from_remote_para_treasury() { - let relay_treasury_to_para_location = MultiLocation { - parents: 1, - interior: X1(Plurality { id: BodyId::Treasury, part: BodyPart::Voice }), - }; + let relay_treasury_to_para_location = Location::new(1, [Plurality { id: BodyId::Treasury, part: BodyPart::Voice }]); let actual_description = ForeignChainAliasTreasuryAccount::<[u8; 32]>::convert_location( &relay_treasury_to_para_location, ) @@ -993,13 +964,10 @@ mod tests { actual_description ); - let para_to_para_treasury_location = MultiLocation { - parents: 1, - interior: X2( - Parachain(1001), - Plurality { id: BodyId::Treasury, part: BodyPart::Voice }, - ), - }; + let para_to_para_treasury_location = Location::new(1, [ + Parachain(1001), + Plurality { id: BodyId::Treasury, part: BodyPart::Voice }, + ]); let actual_description = ForeignChainAliasTreasuryAccount::<[u8; 32]>::convert_location( ¶_to_para_treasury_location, ) @@ -1016,10 +984,7 @@ mod tests { #[test] fn local_account_convert_on_para_from_relay_treasury() { - let location = MultiLocation { - parents: 0, - interior: X1(Plurality { id: BodyId::Treasury, part: BodyPart::Voice }), - }; + let location = Location::new(0, [Plurality { id: BodyId::Treasury, part: BodyPart::Voice }]); parameter_types! { pub TreasuryAccountId: AccountId = AccountId::new([42u8; 32]); diff --git a/polkadot/xcm/xcm-builder/src/matcher.rs b/polkadot/xcm/xcm-builder/src/matcher.rs index 9da135dae31e..eae43b290fb2 100644 --- a/polkadot/xcm/xcm-builder/src/matcher.rs +++ b/polkadot/xcm/xcm-builder/src/matcher.rs @@ -18,7 +18,7 @@ use core::ops::ControlFlow; use frame_support::traits::ProcessMessageError; -use xcm::latest::{Instruction, MultiLocation}; +use xcm::latest::{Instruction, Location}; /// Creates an instruction matcher from an XCM. Since XCM versions differ, we need to make a trait /// here to unify the interfaces among them. @@ -67,7 +67,7 @@ impl<'a, Call> CreateMatcher for &'a mut [Instruction] { pub trait MatchXcm { /// The concrete instruction type. Necessary to specify as it changes between XCM versions. type Inst; - /// The `MultiLocation` type. Necessary to specify as it changes between XCM versions. + /// The `Location` type. Necessary to specify as it changes between XCM versions. type Loc; /// The error type to throw when errors happen during matching. type Error; @@ -125,7 +125,7 @@ pub struct Matcher<'a, Call> { impl<'a, Call> MatchXcm for Matcher<'a, Call> { type Error = ProcessMessageError; type Inst = Instruction; - type Loc = MultiLocation; + type Loc = Location; fn assert_remaining_insts(self, n: usize) -> Result where diff --git a/polkadot/xcm/xcm-builder/src/matches_location.rs b/polkadot/xcm/xcm-builder/src/matches_location.rs index cfc71eafd028..593224229a3d 100644 --- a/polkadot/xcm/xcm-builder/src/matches_location.rs +++ b/polkadot/xcm/xcm-builder/src/matches_location.rs @@ -14,37 +14,37 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -//! Various implementations and utilities for matching and filtering `MultiLocation` and -//! `InteriorMultiLocation` types. +//! Various implementations and utilities for matching and filtering `Location` and +//! `InteriorLocation` types. use frame_support::traits::{Contains, Get}; -use xcm::latest::{InteriorMultiLocation, MultiLocation, NetworkId}; +use xcm::latest::{InteriorLocation, Location, NetworkId}; -/// An implementation of `Contains` that checks for `MultiLocation` or -/// `InteriorMultiLocation` if starts with the provided type `T`. +/// An implementation of `Contains` that checks for `Location` or +/// `InteriorLocation` if starts with the provided type `T`. pub struct StartsWith(sp_std::marker::PhantomData); -impl> Contains for StartsWith { - fn contains(t: &MultiLocation) -> bool { +impl> Contains for StartsWith { + fn contains(t: &Location) -> bool { t.starts_with(&T::get()) } } -impl> Contains for StartsWith { - fn contains(t: &InteriorMultiLocation) -> bool { +impl> Contains for StartsWith { + fn contains(t: &InteriorLocation) -> bool { t.starts_with(&T::get()) } } -/// An implementation of `Contains` that checks for `MultiLocation` or -/// `InteriorMultiLocation` if starts with expected `GlobalConsensus(NetworkId)` provided as type +/// An implementation of `Contains` that checks for `Location` or +/// `InteriorLocation` if starts with expected `GlobalConsensus(NetworkId)` provided as type /// `T`. pub struct StartsWithExplicitGlobalConsensus(sp_std::marker::PhantomData); -impl> Contains for StartsWithExplicitGlobalConsensus { - fn contains(location: &MultiLocation) -> bool { - matches!(location.interior.global_consensus(), Ok(requested_network) if requested_network.eq(&T::get())) +impl> Contains for StartsWithExplicitGlobalConsensus { + fn contains(location: &Location) -> bool { + matches!(location.interior().global_consensus(), Ok(requested_network) if requested_network.eq(&T::get())) } } -impl> Contains for StartsWithExplicitGlobalConsensus { - fn contains(location: &InteriorMultiLocation) -> bool { +impl> Contains for StartsWithExplicitGlobalConsensus { + fn contains(location: &InteriorLocation) -> bool { matches!(location.global_consensus(), Ok(requested_network) if requested_network.eq(&T::get())) } } diff --git a/polkadot/xcm/xcm-builder/src/matches_token.rs b/polkadot/xcm/xcm-builder/src/matches_token.rs index b6a320d89316..e49fd18f88d8 100644 --- a/polkadot/xcm/xcm-builder/src/matches_token.rs +++ b/polkadot/xcm/xcm-builder/src/matches_token.rs @@ -19,25 +19,24 @@ use frame_support::traits::Get; use sp_std::marker::PhantomData; use xcm::latest::{ - AssetId::{Abstract, Concrete}, - AssetInstance, + Asset, AssetId, AssetInstance, Fungibility::{Fungible, NonFungible}, - MultiAsset, MultiLocation, + Location, }; use xcm_executor::traits::{MatchesFungible, MatchesNonFungible}; -/// Converts a `MultiAsset` into balance `B` if it is a concrete fungible with an id equal to that +/// Converts a `Asset` into balance `B` if its id is equal to that /// given by `T`'s `Get`. /// /// # Example /// /// ``` -/// use xcm::latest::{MultiLocation, Parent}; +/// use xcm::latest::{Location, Parent}; /// use staging_xcm_builder::IsConcrete; /// use xcm_executor::traits::MatchesFungible; /// /// frame_support::parameter_types! { -/// pub TargetLocation: MultiLocation = Parent.into(); +/// pub TargetLocation: Location = Parent.into(); /// } /// /// # fn main() { @@ -47,62 +46,18 @@ use xcm_executor::traits::{MatchesFungible, MatchesNonFungible}; /// # } /// ``` pub struct IsConcrete(PhantomData); -impl, B: TryFrom> MatchesFungible for IsConcrete { - fn matches_fungible(a: &MultiAsset) -> Option { +impl, B: TryFrom> MatchesFungible for IsConcrete { + fn matches_fungible(a: &Asset) -> Option { match (&a.id, &a.fun) { - (Concrete(ref id), Fungible(ref amount)) if id == &T::get() => - (*amount).try_into().ok(), + (AssetId(ref id), Fungible(ref amount)) if id == &T::get() => (*amount).try_into().ok(), _ => None, } } } -impl, I: TryFrom> MatchesNonFungible for IsConcrete { - fn matches_nonfungible(a: &MultiAsset) -> Option { +impl, I: TryFrom> MatchesNonFungible for IsConcrete { + fn matches_nonfungible(a: &Asset) -> Option { match (&a.id, &a.fun) { - (Concrete(id), NonFungible(instance)) if id == &T::get() => (*instance).try_into().ok(), - _ => None, - } - } -} - -/// Same as [`IsConcrete`] but for a fungible with abstract location. -/// -/// # Example -/// -/// ``` -/// use xcm::latest::prelude::*; -/// use staging_xcm_builder::IsAbstract; -/// use xcm_executor::traits::{MatchesFungible, MatchesNonFungible}; -/// -/// frame_support::parameter_types! { -/// pub TargetLocation: [u8; 32] = [7u8; 32]; -/// } -/// -/// # fn main() { -/// let asset = ([7u8; 32], 999u128).into(); -/// // match `asset` if it is an abstract asset in `TargetLocation`. -/// assert_eq!( as MatchesFungible>::matches_fungible(&asset), Some(999)); -/// let nft = ([7u8; 32], [42u8; 4]).into(); -/// assert_eq!( -/// as MatchesNonFungible<[u8; 4]>>::matches_nonfungible(&nft), -/// Some([42u8; 4]) -/// ); -/// # } -/// ``` -pub struct IsAbstract(PhantomData); -impl, B: TryFrom> MatchesFungible for IsAbstract { - fn matches_fungible(a: &MultiAsset) -> Option { - match (&a.id, &a.fun) { - (Abstract(ref id), Fungible(ref amount)) if id == &T::get() => - (*amount).try_into().ok(), - _ => None, - } - } -} -impl, B: TryFrom> MatchesNonFungible for IsAbstract { - fn matches_nonfungible(a: &MultiAsset) -> Option { - match (&a.id, &a.fun) { - (Abstract(id), NonFungible(instance)) if id == &T::get() => (*instance).try_into().ok(), + (AssetId(id), NonFungible(instance)) if id == &T::get() => (*instance).try_into().ok(), _ => None, } } diff --git a/polkadot/xcm/xcm-builder/src/nonfungibles_adapter.rs b/polkadot/xcm/xcm-builder/src/nonfungibles_adapter.rs index 357dc534a5f1..c05e3ea7a042 100644 --- a/polkadot/xcm/xcm-builder/src/nonfungibles_adapter.rs +++ b/polkadot/xcm/xcm-builder/src/nonfungibles_adapter.rs @@ -40,11 +40,11 @@ impl< > TransactAsset for NonFungiblesTransferAdapter { fn transfer_asset( - what: &MultiAsset, - from: &MultiLocation, - to: &MultiLocation, + what: &Asset, + from: &Location, + to: &Location, context: &XcmContext, - ) -> result::Result { + ) -> result::Result { log::trace!( target: LOG_TARGET, "transfer_asset what: {:?}, from: {:?}, to: {:?}, context: {:?}", @@ -131,7 +131,7 @@ impl< CheckingAccount, > { - fn can_check_in(_origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { + fn can_check_in(_origin: &Location, what: &Asset, context: &XcmContext) -> XcmResult { log::trace!( target: LOG_TARGET, "can_check_in origin: {:?}, what: {:?}, context: {:?}", @@ -150,7 +150,7 @@ impl< } } - fn check_in(_origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) { + fn check_in(_origin: &Location, what: &Asset, context: &XcmContext) { log::trace!( target: LOG_TARGET, "check_in origin: {:?}, what: {:?}, context: {:?}", @@ -169,7 +169,7 @@ impl< } } - fn can_check_out(_dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { + fn can_check_out(_dest: &Location, what: &Asset, context: &XcmContext) -> XcmResult { log::trace!( target: LOG_TARGET, "can_check_out dest: {:?}, what: {:?}, context: {:?}", @@ -188,7 +188,7 @@ impl< } } - fn check_out(_dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) { + fn check_out(_dest: &Location, what: &Asset, context: &XcmContext) { log::trace!( target: LOG_TARGET, "check_out dest: {:?}, what: {:?}, context: {:?}", @@ -208,8 +208,8 @@ impl< } fn deposit_asset( - what: &MultiAsset, - who: &MultiLocation, + what: &Asset, + who: &Location, context: Option<&XcmContext>, ) -> XcmResult { log::trace!( @@ -228,10 +228,10 @@ impl< } fn withdraw_asset( - what: &MultiAsset, - who: &MultiLocation, + what: &Asset, + who: &Location, maybe_context: Option<&XcmContext>, - ) -> result::Result { + ) -> result::Result { log::trace!( target: LOG_TARGET, "withdraw_asset what: {:?}, who: {:?}, maybe_context: {:?}", @@ -267,7 +267,7 @@ impl< > TransactAsset for NonFungiblesAdapter { - fn can_check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { + fn can_check_in(origin: &Location, what: &Asset, context: &XcmContext) -> XcmResult { NonFungiblesMutateAdapter::< Assets, Matcher, @@ -278,7 +278,7 @@ impl< >::can_check_in(origin, what, context) } - fn check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) { + fn check_in(origin: &Location, what: &Asset, context: &XcmContext) { NonFungiblesMutateAdapter::< Assets, Matcher, @@ -289,7 +289,7 @@ impl< >::check_in(origin, what, context) } - fn can_check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { + fn can_check_out(dest: &Location, what: &Asset, context: &XcmContext) -> XcmResult { NonFungiblesMutateAdapter::< Assets, Matcher, @@ -300,7 +300,7 @@ impl< >::can_check_out(dest, what, context) } - fn check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) { + fn check_out(dest: &Location, what: &Asset, context: &XcmContext) { NonFungiblesMutateAdapter::< Assets, Matcher, @@ -312,8 +312,8 @@ impl< } fn deposit_asset( - what: &MultiAsset, - who: &MultiLocation, + what: &Asset, + who: &Location, context: Option<&XcmContext>, ) -> XcmResult { NonFungiblesMutateAdapter::< @@ -327,10 +327,10 @@ impl< } fn withdraw_asset( - what: &MultiAsset, - who: &MultiLocation, + what: &Asset, + who: &Location, maybe_context: Option<&XcmContext>, - ) -> result::Result { + ) -> result::Result { NonFungiblesMutateAdapter::< Assets, Matcher, @@ -342,11 +342,11 @@ impl< } fn transfer_asset( - what: &MultiAsset, - from: &MultiLocation, - to: &MultiLocation, + what: &Asset, + from: &Location, + to: &Location, context: &XcmContext, - ) -> result::Result { + ) -> result::Result { NonFungiblesTransferAdapter::::transfer_asset( what, from, to, context, ) diff --git a/polkadot/xcm/xcm-builder/src/origin_aliases.rs b/polkadot/xcm/xcm-builder/src/origin_aliases.rs index 82c5f71b7a12..bbf810463a7c 100644 --- a/polkadot/xcm/xcm-builder/src/origin_aliases.rs +++ b/polkadot/xcm/xcm-builder/src/origin_aliases.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -//! Implementation for `ContainsPair`. +//! Implementation for `ContainsPair`. use frame_support::traits::{Contains, ContainsPair}; use sp_std::marker::PhantomData; @@ -25,13 +25,15 @@ use xcm::latest::prelude::*; /// /// Requires that the prefixed origin `AccountId32` matches the target `AccountId32`. pub struct AliasForeignAccountId32(PhantomData); -impl> ContainsPair +impl> ContainsPair for AliasForeignAccountId32 { - fn contains(origin: &MultiLocation, target: &MultiLocation) -> bool { - if let (prefix, Some(account_id @ AccountId32 { .. })) = origin.split_last_interior() { + fn contains(origin: &Location, target: &Location) -> bool { + if let (prefix, Some(account_id @ AccountId32 { .. })) = + origin.clone().split_last_interior() + { return Prefix::contains(&prefix) && - *target == MultiLocation { parents: 0, interior: X1(account_id) } + *target == Location { parents: 0, interior: [account_id].into() } } false } diff --git a/polkadot/xcm/xcm-builder/src/origin_conversion.rs b/polkadot/xcm/xcm-builder/src/origin_conversion.rs index cced7dedf62d..f64b5660f667 100644 --- a/polkadot/xcm/xcm-builder/src/origin_conversion.rs +++ b/polkadot/xcm/xcm-builder/src/origin_conversion.rs @@ -21,7 +21,7 @@ use frame_system::RawOrigin as SystemRawOrigin; use polkadot_parachain_primitives::primitives::IsSystem; use sp_runtime::traits::TryConvert; use sp_std::marker::PhantomData; -use xcm::latest::{BodyId, BodyPart, Junction, Junctions::*, MultiLocation, NetworkId, OriginKind}; +use xcm::latest::{BodyId, BodyPart, Junction, Junctions::*, Location, NetworkId, OriginKind}; use xcm_executor::traits::{ConvertLocation, ConvertOrigin}; /// Sovereign accounts use the system's `Signed` origin with an account ID derived from the @@ -35,9 +35,9 @@ where RuntimeOrigin::AccountId: Clone, { fn convert_origin( - origin: impl Into, + origin: impl Into, kind: OriginKind, - ) -> Result { + ) -> Result { let origin = origin.into(); log::trace!( target: "xcm::origin_conversion", @@ -56,9 +56,9 @@ where pub struct ParentAsSuperuser(PhantomData); impl ConvertOrigin for ParentAsSuperuser { fn convert_origin( - origin: impl Into, + origin: impl Into, kind: OriginKind, - ) -> Result { + ) -> Result { let origin = origin.into(); log::trace!(target: "xcm::origin_conversion", "ParentAsSuperuser origin: {:?}, kind: {:?}", origin, kind); if kind == OriginKind::Superuser && origin.contains_parents_only(1) { @@ -76,17 +76,16 @@ impl, RuntimeOrigin: OriginTrait> ConvertOrigin { fn convert_origin( - origin: impl Into, + origin: impl Into, kind: OriginKind, - ) -> Result { + ) -> Result { let origin = origin.into(); log::trace!(target: "xcm::origin_conversion", "ChildSystemParachainAsSuperuser origin: {:?}, kind: {:?}", origin, kind); - match (kind, origin) { - ( - OriginKind::Superuser, - MultiLocation { parents: 0, interior: X1(Junction::Parachain(id)) }, - ) if ParaId::from(id).is_system() => Ok(RuntimeOrigin::root()), - (_, origin) => Err(origin), + match (kind, origin.unpack()) { + (OriginKind::Superuser, (0, [Junction::Parachain(id)])) + if ParaId::from(*id).is_system() => + Ok(RuntimeOrigin::root()), + _ => Err(origin), } } } @@ -98,21 +97,20 @@ impl, RuntimeOrigin: OriginTrait> ConvertOrigin { fn convert_origin( - origin: impl Into, + origin: impl Into, kind: OriginKind, - ) -> Result { + ) -> Result { let origin = origin.into(); log::trace!( target: "xcm::origin_conversion", "SiblingSystemParachainAsSuperuser origin: {:?}, kind: {:?}", origin, kind, ); - match (kind, origin) { - ( - OriginKind::Superuser, - MultiLocation { parents: 1, interior: X1(Junction::Parachain(id)) }, - ) if ParaId::from(id).is_system() => Ok(RuntimeOrigin::root()), - (_, origin) => Err(origin), + match (kind, origin.unpack()) { + (OriginKind::Superuser, (1, [Junction::Parachain(id)])) + if ParaId::from(*id).is_system() => + Ok(RuntimeOrigin::root()), + _ => Err(origin), } } } @@ -124,17 +122,15 @@ impl, RuntimeOrigin: From> ConvertOr for ChildParachainAsNative { fn convert_origin( - origin: impl Into, + origin: impl Into, kind: OriginKind, - ) -> Result { + ) -> Result { let origin = origin.into(); log::trace!(target: "xcm::origin_conversion", "ChildParachainAsNative origin: {:?}, kind: {:?}", origin, kind); - match (kind, origin) { - ( - OriginKind::Native, - MultiLocation { parents: 0, interior: X1(Junction::Parachain(id)) }, - ) => Ok(RuntimeOrigin::from(ParachainOrigin::from(id))), - (_, origin) => Err(origin), + match (kind, origin.unpack()) { + (OriginKind::Native, (0, [Junction::Parachain(id)])) => + Ok(RuntimeOrigin::from(ParachainOrigin::from(*id))), + _ => Err(origin), } } } @@ -146,21 +142,19 @@ impl, RuntimeOrigin: From> ConvertOr for SiblingParachainAsNative { fn convert_origin( - origin: impl Into, + origin: impl Into, kind: OriginKind, - ) -> Result { + ) -> Result { let origin = origin.into(); log::trace!( target: "xcm::origin_conversion", "SiblingParachainAsNative origin: {:?}, kind: {:?}", origin, kind, ); - match (kind, origin) { - ( - OriginKind::Native, - MultiLocation { parents: 1, interior: X1(Junction::Parachain(id)) }, - ) => Ok(RuntimeOrigin::from(ParachainOrigin::from(id))), - (_, origin) => Err(origin), + match (kind, origin.unpack()) { + (OriginKind::Native, (1, [Junction::Parachain(id)])) => + Ok(RuntimeOrigin::from(ParachainOrigin::from(*id))), + _ => Err(origin), } } } @@ -173,9 +167,9 @@ impl, RuntimeOrigin> ConvertOrigin { fn convert_origin( - origin: impl Into, + origin: impl Into, kind: OriginKind, - ) -> Result { + ) -> Result { let origin = origin.into(); log::trace!(target: "xcm::origin_conversion", "RelayChainAsNative origin: {:?}, kind: {:?}", origin, kind); if kind == OriginKind::Native && origin.contains_parents_only(1) { @@ -193,22 +187,20 @@ where RuntimeOrigin::AccountId: From<[u8; 32]>, { fn convert_origin( - origin: impl Into, + origin: impl Into, kind: OriginKind, - ) -> Result { + ) -> Result { let origin = origin.into(); log::trace!( target: "xcm::origin_conversion", "SignedAccountId32AsNative origin: {:?}, kind: {:?}", origin, kind, ); - match (kind, origin) { - ( - OriginKind::Native, - MultiLocation { parents: 0, interior: X1(Junction::AccountId32 { id, network }) }, - ) if matches!(network, None) || network == Network::get() => - Ok(RuntimeOrigin::signed(id.into())), - (_, origin) => Err(origin), + match (kind, origin.unpack()) { + (OriginKind::Native, (0, [Junction::AccountId32 { id, network }])) + if matches!(network, None) || *network == Network::get() => + Ok(RuntimeOrigin::signed((*id).into())), + _ => Err(origin), } } } @@ -222,34 +214,32 @@ where RuntimeOrigin::AccountId: From<[u8; 20]>, { fn convert_origin( - origin: impl Into, + origin: impl Into, kind: OriginKind, - ) -> Result { + ) -> Result { let origin = origin.into(); log::trace!( target: "xcm::origin_conversion", "SignedAccountKey20AsNative origin: {:?}, kind: {:?}", origin, kind, ); - match (kind, origin) { - ( - OriginKind::Native, - MultiLocation { parents: 0, interior: X1(Junction::AccountKey20 { key, network }) }, - ) if (matches!(network, None) || network == Network::get()) => - Ok(RuntimeOrigin::signed(key.into())), - (_, origin) => Err(origin), + match (kind, origin.unpack()) { + (OriginKind::Native, (0, [Junction::AccountKey20 { key, network }])) + if (matches!(network, None) || *network == Network::get()) => + Ok(RuntimeOrigin::signed((*key).into())), + _ => Err(origin), } } } /// `EnsureOrigin` barrier to convert from dispatch origin to XCM origin, if one exists. pub struct EnsureXcmOrigin(PhantomData<(RuntimeOrigin, Conversion)>); -impl> +impl> EnsureOrigin for EnsureXcmOrigin where RuntimeOrigin::PalletsOrigin: PartialEq, { - type Success = MultiLocation; + type Success = Location; fn try_origin(o: RuntimeOrigin) -> Result { let o = match Conversion::try_convert(o) { Ok(location) => return Ok(location), @@ -282,13 +272,12 @@ impl< RuntimeOrigin: OriginTrait + Clone, AccountId: Into<[u8; 32]>, Network: Get>, - > TryConvert - for SignedToAccountId32 + > TryConvert for SignedToAccountId32 where RuntimeOrigin::PalletsOrigin: From> + TryInto, Error = RuntimeOrigin::PalletsOrigin>, { - fn try_convert(o: RuntimeOrigin) -> Result { + fn try_convert(o: RuntimeOrigin) -> Result { o.try_with_caller(|caller| match caller.try_into() { Ok(SystemRawOrigin::Signed(who)) => Ok(Junction::AccountId32 { network: Network::get(), id: who.into() }.into()), @@ -299,7 +288,7 @@ where } /// `Convert` implementation to convert from some an origin which implements `Backing` into a -/// corresponding `Plurality` `MultiLocation`. +/// corresponding `Plurality` `Location`. /// /// Typically used when configuring `pallet-xcm` for allowing a collective's Origin to dispatch an /// XCM from a `Plurality` origin. @@ -307,12 +296,12 @@ pub struct BackingToPlurality( PhantomData<(RuntimeOrigin, COrigin, Body)>, ); impl> - TryConvert for BackingToPlurality + TryConvert for BackingToPlurality where RuntimeOrigin::PalletsOrigin: From + TryInto, { - fn try_convert(o: RuntimeOrigin) -> Result { + fn try_convert(o: RuntimeOrigin) -> Result { o.try_with_caller(|caller| match caller.try_into() { Ok(co) => match co.get_backing() { Some(backing) => Ok(Junction::Plurality { @@ -333,10 +322,10 @@ pub struct OriginToPluralityVoice( PhantomData<(RuntimeOrigin, EnsureBodyOrigin, Body)>, ); impl, Body: Get> - TryConvert + TryConvert for OriginToPluralityVoice { - fn try_convert(o: RuntimeOrigin) -> Result { + fn try_convert(o: RuntimeOrigin) -> Result { match EnsureBodyOrigin::try_origin(o) { Ok(_) => Ok(Junction::Plurality { id: Body::get(), part: BodyPart::Voice }.into()), Err(o) => Err(o), diff --git a/polkadot/xcm/xcm-builder/src/pay.rs b/polkadot/xcm/xcm-builder/src/pay.rs index 4c9b9a6088de..6b466483cfad 100644 --- a/polkadot/xcm/xcm-builder/src/pay.rs +++ b/polkadot/xcm/xcm-builder/src/pay.rs @@ -30,7 +30,7 @@ use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; /// ownership of some `Interior` location of the local chain to a particular `Beneficiary`. The /// `AssetKind` value is not itself bounded (to avoid the issue of needing to wrap some preexisting /// datatype), however a converter type `AssetKindToLocatableAsset` must be provided in order to -/// translate it into a `LocatableAsset`, which comprises both an XCM `MultiLocation` describing +/// translate it into a `LocatableAsset`, which comprises both an XCM `Location` describing /// the XCM endpoint on which the asset to be paid resides and an XCM `AssetId` to identify the /// specific asset at that endpoint. /// @@ -65,14 +65,14 @@ pub struct PayOverXcm< )>, ); impl< - Interior: Get, + Interior: Get, Router: SendXcm, Querier: QueryHandler, Timeout: Get, Beneficiary: Clone, AssetKind, AssetKindToLocatableAsset: TryConvert, - BeneficiaryRefToLocation: for<'a> TryConvert<&'a Beneficiary, MultiLocation>, + BeneficiaryRefToLocation: for<'a> TryConvert<&'a Beneficiary, Location>, > Pay for PayOverXcm< Interior, @@ -105,7 +105,7 @@ impl< let beneficiary = BeneficiaryRefToLocation::try_convert(&who) .map_err(|_| xcm::latest::Error::InvalidLocation)?; - let query_id = Querier::new_query(asset_location, Timeout::get(), Interior::get()); + let query_id = Querier::new_query(asset_location.clone(), Timeout::get(), Interior::get()); let message = Xcm(vec![ DescendOrigin(Interior::get()), @@ -120,8 +120,7 @@ impl< ])), TransferAsset { beneficiary, - assets: vec![MultiAsset { id: asset_id, fun: Fungibility::Fungible(amount) }] - .into(), + assets: vec![Asset { id: asset_id, fun: Fungibility::Fungible(amount) }].into(), }, ]); @@ -195,16 +194,16 @@ pub struct LocatableAssetId { /// The asset's ID. pub asset_id: AssetId, /// The (relative) location in which the asset ID is meaningful. - pub location: MultiLocation, + pub location: Location, } /// Adapter `struct` which implements a conversion from any `AssetKind` into a [`LocatableAssetId`] /// value using a fixed `Location` for the `location` field. -pub struct FixedLocation(sp_std::marker::PhantomData); -impl, AssetKind: Into> TryConvert - for FixedLocation +pub struct FixedLocation(sp_std::marker::PhantomData); +impl, AssetKind: Into> + TryConvert for FixedLocation { fn try_convert(value: AssetKind) -> Result { - Ok(LocatableAssetId { asset_id: value.into(), location: Location::get() }) + Ok(LocatableAssetId { asset_id: value.into(), location: FixedLocationValue::get() }) } } diff --git a/polkadot/xcm/xcm-builder/src/process_xcm_message.rs b/polkadot/xcm/xcm-builder/src/process_xcm_message.rs index 330ff40aac0f..e6bc5b15d147 100644 --- a/polkadot/xcm/xcm-builder/src/process_xcm_message.rs +++ b/polkadot/xcm/xcm-builder/src/process_xcm_message.rs @@ -31,7 +31,7 @@ pub struct ProcessXcmMessage( PhantomData<(MessageOrigin, XcmExecutor, Call)>, ); impl< - MessageOrigin: Into + FullCodec + MaxEncodedLen + Clone + Eq + PartialEq + TypeInfo + Debug, + MessageOrigin: Into + FullCodec + MaxEncodedLen + Clone + Eq + PartialEq + TypeInfo + Debug, XcmExecutor: ExecuteXcm, Call, > ProcessMessage for ProcessXcmMessage @@ -56,10 +56,10 @@ impl< let (consumed, result) = match XcmExecutor::execute(origin.into(), pre, id, Weight::zero()) { - Outcome::Complete(w) => (w, Ok(true)), - Outcome::Incomplete(w, _) => (w, Ok(false)), + Outcome::Complete { used } => (used, Ok(true)), + Outcome::Incomplete { used, .. } => (used, Ok(false)), // In the error-case we assume the worst case and consume all possible weight. - Outcome::Error(_) => (required, Err(ProcessMessageError::Unsupported)), + Outcome::Error { .. } => (required, Err(ProcessMessageError::Unsupported)), }; meter.consume(consumed); result diff --git a/polkadot/xcm/xcm-builder/src/routing.rs b/polkadot/xcm/xcm-builder/src/routing.rs index f4c18adddb37..9c0302baee06 100644 --- a/polkadot/xcm/xcm-builder/src/routing.rs +++ b/polkadot/xcm/xcm-builder/src/routing.rs @@ -38,7 +38,7 @@ impl SendXcm for WithUniqueTopic { type Ticket = (Inner::Ticket, [u8; 32]); fn validate( - destination: &mut Option, + destination: &mut Option, message: &mut Option>, ) -> SendResult { let mut message = message.take().ok_or(SendError::MissingArgument)?; @@ -82,7 +82,7 @@ impl SendXcm for WithTopicSource, + destination: &mut Option, message: &mut Option>, ) -> SendResult { let mut message = message.take().ok_or(SendError::MissingArgument)?; diff --git a/polkadot/xcm/xcm-builder/src/test_utils.rs b/polkadot/xcm/xcm-builder/src/test_utils.rs index d0f867ba62d6..74f1a723cbc8 100644 --- a/polkadot/xcm/xcm-builder/src/test_utils.rs +++ b/polkadot/xcm/xcm-builder/src/test_utils.rs @@ -27,11 +27,11 @@ pub use xcm_executor::{ traits::{ AssetExchange, AssetLock, ConvertOrigin, Enact, LockError, OnResponse, TransactAsset, }, - Assets, Config, + Config, AssetsInHolding, }; parameter_types! { - pub static SubscriptionRequests: Vec<(MultiLocation, Option<(QueryId, Weight)>)> = vec![]; + pub static SubscriptionRequests: Vec<(Location, Option<(QueryId, Weight)>)> = vec![]; pub static MaxAssetsIntoHolding: u32 = 4; } @@ -39,39 +39,39 @@ pub struct TestSubscriptionService; impl VersionChangeNotifier for TestSubscriptionService { fn start( - location: &MultiLocation, + location: &Location, query_id: QueryId, max_weight: Weight, _context: &XcmContext, ) -> XcmResult { let mut r = SubscriptionRequests::get(); - r.push((*location, Some((query_id, max_weight)))); + r.push((location.clone(), Some((query_id, max_weight)))); SubscriptionRequests::set(r); Ok(()) } - fn stop(location: &MultiLocation, _context: &XcmContext) -> XcmResult { + fn stop(location: &Location, _context: &XcmContext) -> XcmResult { let mut r = SubscriptionRequests::get(); r.retain(|(l, _q)| l != location); - r.push((*location, None)); + r.push((location.clone(), None)); SubscriptionRequests::set(r); Ok(()) } - fn is_subscribed(location: &MultiLocation) -> bool { + fn is_subscribed(location: &Location) -> bool { let r = SubscriptionRequests::get(); r.iter().any(|(l, q)| l == location && q.is_some()) } } parameter_types! { - pub static TrappedAssets: Vec<(MultiLocation, MultiAssets)> = vec![]; + pub static TrappedAssets: Vec<(Location, Assets)> = vec![]; } pub struct TestAssetTrap; impl DropAssets for TestAssetTrap { - fn drop_assets(origin: &MultiLocation, assets: Assets, _context: &XcmContext) -> Weight { - let mut t: Vec<(MultiLocation, MultiAssets)> = TrappedAssets::get(); - t.push((*origin, assets.into())); + fn drop_assets(origin: &Location, assets: AssetsInHolding, _context: &XcmContext) -> Weight { + let mut t: Vec<(Location, Assets)> = TrappedAssets::get(); + t.push((origin.clone(), assets.into())); TrappedAssets::set(t); Weight::from_parts(5, 5) } @@ -79,13 +79,13 @@ impl DropAssets for TestAssetTrap { impl ClaimAssets for TestAssetTrap { fn claim_assets( - origin: &MultiLocation, - ticket: &MultiLocation, - what: &MultiAssets, + origin: &Location, + ticket: &Location, + what: &Assets, _context: &XcmContext, ) -> bool { - let mut t: Vec<(MultiLocation, MultiAssets)> = TrappedAssets::get(); - if let (0, X1(GeneralIndex(i))) = (ticket.parents, &ticket.interior) { + let mut t: Vec<(Location, Assets)> = TrappedAssets::get(); + if let (0, [GeneralIndex(i)]) = ticket.unpack() { if let Some((l, a)) = t.get(*i as usize) { if l == origin && a == what { t.swap_remove(*i as usize); @@ -102,11 +102,11 @@ pub struct TestAssetExchanger; impl AssetExchange for TestAssetExchanger { fn exchange_asset( - _origin: Option<&MultiLocation>, - _give: Assets, - want: &MultiAssets, + _origin: Option<&Location>, + _give: AssetsInHolding, + want: &Assets, _maximal: bool, - ) -> Result { + ) -> Result { Ok(want.clone().into()) } } @@ -135,17 +135,17 @@ impl PalletsInfoAccess for TestPalletsInfo { } pub struct TestUniversalAliases; -impl Contains<(MultiLocation, Junction)> for TestUniversalAliases { - fn contains(aliases: &(MultiLocation, Junction)) -> bool { +impl Contains<(Location, Junction)> for TestUniversalAliases { + fn contains(aliases: &(Location, Junction)) -> bool { &aliases.0 == &Here.into_location() && &aliases.1 == &GlobalConsensus(ByGenesis([0; 32])) } } parameter_types! { - pub static LockedAssets: Vec<(MultiLocation, MultiAsset)> = vec![]; + pub static LockedAssets: Vec<(Location, Asset)> = vec![]; } -pub struct TestLockTicket(MultiLocation, MultiAsset); +pub struct TestLockTicket(Location, Asset); impl Enact for TestLockTicket { fn enact(self) -> Result<(), LockError> { let mut locked_assets = LockedAssets::get(); @@ -154,7 +154,7 @@ impl Enact for TestLockTicket { Ok(()) } } -pub struct TestUnlockTicket(MultiLocation, MultiAsset); +pub struct TestUnlockTicket(Location, Asset); impl Enact for TestUnlockTicket { fn enact(self) -> Result<(), LockError> { let mut locked_assets = LockedAssets::get(); @@ -183,33 +183,33 @@ impl AssetLock for TestAssetLocker { type ReduceTicket = TestReduceTicket; fn prepare_lock( - unlocker: MultiLocation, - asset: MultiAsset, - _owner: MultiLocation, + unlocker: Location, + asset: Asset, + _owner: Location, ) -> Result { Ok(TestLockTicket(unlocker, asset)) } fn prepare_unlock( - unlocker: MultiLocation, - asset: MultiAsset, - _owner: MultiLocation, + unlocker: Location, + asset: Asset, + _owner: Location, ) -> Result { Ok(TestUnlockTicket(unlocker, asset)) } fn note_unlockable( - _locker: MultiLocation, - _asset: MultiAsset, - _owner: MultiLocation, + _locker: Location, + _asset: Asset, + _owner: Location, ) -> Result<(), LockError> { Ok(()) } fn prepare_reduce_unlockable( - _locker: MultiLocation, - _asset: MultiAsset, - _owner: MultiLocation, + _locker: Location, + _asset: Asset, + _owner: Location, ) -> Result { Ok(TestReduceTicket) } diff --git a/polkadot/xcm/xcm-builder/src/tests/aliases.rs b/polkadot/xcm/xcm-builder/src/tests/aliases.rs index f686926a2522..520e20515e63 100644 --- a/polkadot/xcm/xcm-builder/src/tests/aliases.rs +++ b/polkadot/xcm/xcm-builder/src/tests/aliases.rs @@ -66,20 +66,22 @@ fn alias_origin_should_work() { ]); let message = Xcm(vec![AliasOrigin((AccountId32 { network: None, id: [0; 32] }).into())]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( (Parachain(1), AccountId32 { network: None, id: [0; 32] }), message.clone(), - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::NoPermission)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::NoPermission }); - let r = XcmExecutor::::execute_xcm( + let r = XcmExecutor::::prepare_and_execute( (Parent, Parachain(1), AccountId32 { network: None, id: [0; 32] }), message.clone(), - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); } diff --git a/polkadot/xcm/xcm-builder/src/tests/assets.rs b/polkadot/xcm/xcm-builder/src/tests/assets.rs index e1d61a9d1c6d..b18122c178b2 100644 --- a/polkadot/xcm/xcm-builder/src/tests/assets.rs +++ b/polkadot/xcm/xcm-builder/src/tests/assets.rs @@ -32,10 +32,10 @@ fn exchange_asset_should_work() { maximal: true, }, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let r = - XcmExecutor::::execute_xcm(Parent, message, hash, Weight::from_parts(50, 50)); - assert_eq!(r, Outcome::Complete(Weight::from_parts(40, 40))); + XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, Weight::from_parts(50, 50), Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(40, 40) }); assert_eq!(asset_list(Parent), vec![(Here, 100u128).into(), (Parent, 950u128).into()]); assert_eq!(exchange_assets(), vec![(Parent, 50u128).into()].into()); } @@ -56,10 +56,10 @@ fn exchange_asset_without_maximal_should_work() { maximal: false, }, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let r = - XcmExecutor::::execute_xcm(Parent, message, hash, Weight::from_parts(50, 50)); - assert_eq!(r, Outcome::Complete(Weight::from_parts(40, 40))); + XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, Weight::from_parts(50, 50), Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(40, 40) }); assert_eq!(asset_list(Parent), vec![(Here, 50u128).into(), (Parent, 950u128).into()]); assert_eq!(exchange_assets(), vec![(Here, 50u128).into(), (Parent, 50u128).into()].into()); } @@ -80,10 +80,10 @@ fn exchange_asset_should_fail_when_no_deal_possible() { maximal: false, }, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let r = - XcmExecutor::::execute_xcm(Parent, message, hash, Weight::from_parts(50, 50)); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(40, 40), XcmError::NoDeal)); + XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, Weight::from_parts(50, 50), Weight::zero()); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(40, 40), error: XcmError::NoDeal }); assert_eq!(asset_list(Parent), vec![(Parent, 1000u128).into()]); assert_eq!(exchange_assets(), vec![(Here, 100u128).into()].into()); } @@ -100,32 +100,33 @@ fn paying_reserve_deposit_should_work() { BuyExecution { fees, weight_limit: Limited(Weight::from_parts(30, 30)) }, DepositAsset { assets: AllCounted(1).into(), beneficiary: Here.into() }, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(50, 50); - let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(30, 30))); + let r = XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(30, 30) }); assert_eq!(asset_list(Here), vec![(Parent, 40u128).into()]); } #[test] fn transfer_should_work() { // we'll let them have message execution for free. - AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); + AllowUnpaidFrom::set(vec![[Parachain(1)].into()]); // Child parachain #1 owns 1000 tokens held by us in reserve. add_asset(Parachain(1), (Here, 1000)); // They want to transfer 100 of them to their sibling parachain #2 let message = Xcm(vec![TransferAsset { assets: (Here, 100u128).into(), - beneficiary: X1(AccountIndex64 { index: 3, network: None }).into(), + beneficiary: [AccountIndex64 { index: 3, network: None }].into(), }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); assert_eq!( asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 100u128).into()] @@ -136,27 +137,31 @@ fn transfer_should_work() { #[test] fn reserve_transfer_should_work() { - AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); + AllowUnpaidFrom::set(vec![[Parachain(1)].into()]); // Child parachain #1 owns 1000 tokens held by us in reserve. add_asset(Parachain(1), (Here, 1000)); // The remote account owned by gav. - let three: MultiLocation = X1(AccountIndex64 { index: 3, network: None }).into(); + let three: Location = [AccountIndex64 { index: 3, network: None }].into(); // They want to transfer 100 of our native asset from sovereign account of parachain #1 into #2 // and let them know to hand it to account #3. let message = Xcm(vec![TransferReserveAsset { assets: (Here, 100u128).into(), dest: Parachain(2).into(), - xcm: Xcm::<()>(vec![DepositAsset { assets: AllCounted(1).into(), beneficiary: three }]), + xcm: Xcm::<()>(vec![DepositAsset { + assets: AllCounted(1).into(), + beneficiary: three.clone(), + }]), }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); let expected_msg = Xcm::<()>(vec![ ReserveAssetDeposited((Parent, 100u128).into()), @@ -171,7 +176,7 @@ fn reserve_transfer_should_work() { #[test] fn burn_should_work() { // we'll let them have message execution for free. - AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); + AllowUnpaidFrom::set(vec![[Parachain(1)].into()]); // Child parachain #1 owns 1000 tokens held by us in reserve. add_asset(Parachain(1), (Here, 1000)); // They want to burn 100 of them @@ -180,14 +185,15 @@ fn burn_should_work() { BurnAsset((Here, 100u128).into()), DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Parachain(1).into() }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(30, 30))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(30, 30) }); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900u128).into()]); assert_eq!(sent_xcm(), vec![]); @@ -197,14 +203,15 @@ fn burn_should_work() { BurnAsset((Here, 1000u128).into()), DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Parachain(1).into() }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(30, 30))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(30, 30) }); assert_eq!(asset_list(Parachain(1)), vec![]); assert_eq!(sent_xcm(), vec![]); } @@ -212,7 +219,7 @@ fn burn_should_work() { #[test] fn basic_asset_trap_should_work() { // we'll let them have message execution for free. - AllowUnpaidFrom::set(vec![X1(Parachain(1)).into(), X1(Parachain(2)).into()]); + AllowUnpaidFrom::set(vec![[Parachain(1)].into(), [Parachain(2)].into()]); // Child parachain #1 owns 1000 tokens held by us in reserve. add_asset(Parachain(1), (Here, 1000)); @@ -224,14 +231,15 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(20, 20), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(25, 25))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(25, 25) }); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900u128).into()]); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![]); @@ -243,15 +251,16 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let old_trapped_assets = TrappedAssets::get(); - let r = XcmExecutor::::execute_xcm( + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(20, 20), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::UnknownClaim)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::UnknownClaim }); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900u128).into()]); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![]); assert_eq!(old_trapped_assets, TrappedAssets::get()); @@ -264,15 +273,16 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let old_trapped_assets = TrappedAssets::get(); - let r = XcmExecutor::::execute_xcm( + let r = XcmExecutor::::prepare_and_execute( Parachain(2), message, - hash, + &mut hash, Weight::from_parts(20, 20), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::UnknownClaim)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::UnknownClaim }); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900u128).into()]); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![]); assert_eq!(old_trapped_assets, TrappedAssets::get()); @@ -285,15 +295,16 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let old_trapped_assets = TrappedAssets::get(); - let r = XcmExecutor::::execute_xcm( + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(20, 20), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::UnknownClaim)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::UnknownClaim }); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900u128).into()]); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![]); assert_eq!(old_trapped_assets, TrappedAssets::get()); @@ -305,14 +316,15 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(20, 20), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(20, 20))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(20, 20) }); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900u128).into()]); assert_eq!( asset_list(AccountIndex64 { index: 3, network: None }), @@ -327,141 +339,147 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(20, 20), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::UnknownClaim)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::UnknownClaim }); } #[test] fn max_assets_limit_should_work() { // we'll let them have message execution for free. - AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); + AllowUnpaidFrom::set(vec![[Parachain(1)].into()]); // Child parachain #1 owns 1000 tokens held by us in reserve. - add_asset(Parachain(1), ([1u8; 32], 1000u128)); - add_asset(Parachain(1), ([2u8; 32], 1000u128)); - add_asset(Parachain(1), ([3u8; 32], 1000u128)); - add_asset(Parachain(1), ([4u8; 32], 1000u128)); - add_asset(Parachain(1), ([5u8; 32], 1000u128)); - add_asset(Parachain(1), ([6u8; 32], 1000u128)); - add_asset(Parachain(1), ([7u8; 32], 1000u128)); - add_asset(Parachain(1), ([8u8; 32], 1000u128)); - add_asset(Parachain(1), ([9u8; 32], 1000u128)); + add_asset(Parachain(1), (Junctions::from([GeneralIndex(0)]), 1000u128)); + add_asset(Parachain(1), (Junctions::from([GeneralIndex(1)]), 1000u128)); + add_asset(Parachain(1), (Junctions::from([GeneralIndex(2)]), 1000u128)); + add_asset(Parachain(1), (Junctions::from([GeneralIndex(3)]), 1000u128)); + add_asset(Parachain(1), (Junctions::from([GeneralIndex(4)]), 1000u128)); + add_asset(Parachain(1), (Junctions::from([GeneralIndex(5)]), 1000u128)); + add_asset(Parachain(1), (Junctions::from([GeneralIndex(6)]), 1000u128)); + add_asset(Parachain(1), (Junctions::from([GeneralIndex(7)]), 1000u128)); + add_asset(Parachain(1), (Junctions::from([GeneralIndex(8)]), 1000u128)); // Attempt to withdraw 8 (=2x4)different assets. This will succeed. let message = Xcm(vec![ - WithdrawAsset(([1u8; 32], 100u128).into()), - WithdrawAsset(([2u8; 32], 100u128).into()), - WithdrawAsset(([3u8; 32], 100u128).into()), - WithdrawAsset(([4u8; 32], 100u128).into()), - WithdrawAsset(([5u8; 32], 100u128).into()), - WithdrawAsset(([6u8; 32], 100u128).into()), - WithdrawAsset(([7u8; 32], 100u128).into()), - WithdrawAsset(([8u8; 32], 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(0)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(1)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(2)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(3)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(4)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(5)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(6)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(7)]), 100u128).into()), ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(100, 100), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(85, 85))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(85, 85) }); // Attempt to withdraw 9 different assets will fail. let message = Xcm(vec![ - WithdrawAsset(([1u8; 32], 100u128).into()), - WithdrawAsset(([2u8; 32], 100u128).into()), - WithdrawAsset(([3u8; 32], 100u128).into()), - WithdrawAsset(([4u8; 32], 100u128).into()), - WithdrawAsset(([5u8; 32], 100u128).into()), - WithdrawAsset(([6u8; 32], 100u128).into()), - WithdrawAsset(([7u8; 32], 100u128).into()), - WithdrawAsset(([8u8; 32], 100u128).into()), - WithdrawAsset(([9u8; 32], 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(0)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(1)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(2)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(3)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(4)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(5)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(6)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(7)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(8)]), 100u128).into()), ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(100, 100), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(95, 95), XcmError::HoldingWouldOverflow)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(95, 95), error: XcmError::HoldingWouldOverflow }); // Attempt to withdraw 4 different assets and then the same 4 and then a different 4 will // succeed. let message = Xcm(vec![ - WithdrawAsset(([1u8; 32], 100u128).into()), - WithdrawAsset(([2u8; 32], 100u128).into()), - WithdrawAsset(([3u8; 32], 100u128).into()), - WithdrawAsset(([4u8; 32], 100u128).into()), - WithdrawAsset(([1u8; 32], 100u128).into()), - WithdrawAsset(([2u8; 32], 100u128).into()), - WithdrawAsset(([3u8; 32], 100u128).into()), - WithdrawAsset(([4u8; 32], 100u128).into()), - WithdrawAsset(([5u8; 32], 100u128).into()), - WithdrawAsset(([6u8; 32], 100u128).into()), - WithdrawAsset(([7u8; 32], 100u128).into()), - WithdrawAsset(([8u8; 32], 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(0)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(1)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(2)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(3)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(0)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(1)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(2)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(3)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(4)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(5)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(6)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(7)]), 100u128).into()), ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(200, 200), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(125, 125))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(125, 125) }); // Attempt to withdraw 4 different assets and then a different 4 and then the same 4 will fail. let message = Xcm(vec![ - WithdrawAsset(([1u8; 32], 100u128).into()), - WithdrawAsset(([2u8; 32], 100u128).into()), - WithdrawAsset(([3u8; 32], 100u128).into()), - WithdrawAsset(([4u8; 32], 100u128).into()), - WithdrawAsset(([5u8; 32], 100u128).into()), - WithdrawAsset(([6u8; 32], 100u128).into()), - WithdrawAsset(([7u8; 32], 100u128).into()), - WithdrawAsset(([8u8; 32], 100u128).into()), - WithdrawAsset(([1u8; 32], 100u128).into()), - WithdrawAsset(([2u8; 32], 100u128).into()), - WithdrawAsset(([3u8; 32], 100u128).into()), - WithdrawAsset(([4u8; 32], 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(0)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(1)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(2)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(3)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(4)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(5)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(6)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(7)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(0)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(1)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(2)]), 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(3)]), 100u128).into()), ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(200, 200), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(95, 95), XcmError::HoldingWouldOverflow)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(95, 95), error: XcmError::HoldingWouldOverflow }); // Attempt to withdraw 4 different assets and then a different 4 and then the same 4 will fail. let message = Xcm(vec![ - WithdrawAsset(MultiAssets::from(vec![ - ([1u8; 32], 100u128).into(), - ([2u8; 32], 100u128).into(), - ([3u8; 32], 100u128).into(), - ([4u8; 32], 100u128).into(), - ([5u8; 32], 100u128).into(), - ([6u8; 32], 100u128).into(), - ([7u8; 32], 100u128).into(), - ([8u8; 32], 100u128).into(), + WithdrawAsset(Assets::from(vec![ + (Junctions::from([GeneralIndex(0)]), 100u128).into(), + (Junctions::from([GeneralIndex(1)]), 100u128).into(), + (Junctions::from([GeneralIndex(2)]), 100u128).into(), + (Junctions::from([GeneralIndex(3)]), 100u128).into(), + (Junctions::from([GeneralIndex(4)]), 100u128).into(), + (Junctions::from([GeneralIndex(5)]), 100u128).into(), + (Junctions::from([GeneralIndex(6)]), 100u128).into(), + (Junctions::from([GeneralIndex(7)]), 100u128).into(), ])), - WithdrawAsset(([1u8; 32], 100u128).into()), + WithdrawAsset((Junctions::from([GeneralIndex(0)]), 100u128).into()), ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(200, 200), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(25, 25), XcmError::HoldingWouldOverflow)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(25, 25), error: XcmError::HoldingWouldOverflow }); } diff --git a/polkadot/xcm/xcm-builder/src/tests/basic.rs b/polkadot/xcm/xcm-builder/src/tests/basic.rs index 02fcd8962dbf..6010aa993c56 100644 --- a/polkadot/xcm/xcm-builder/src/tests/basic.rs +++ b/polkadot/xcm/xcm-builder/src/tests/basic.rs @@ -27,14 +27,8 @@ fn basic_setup_works() { assert_eq!(to_account(Parachain(50)), Ok(1050)); assert_eq!(to_account((Parent, Parachain(1))), Ok(2001)); assert_eq!(to_account((Parent, Parachain(50))), Ok(2050)); - assert_eq!( - to_account(MultiLocation::new(0, X1(AccountIndex64 { index: 1, network: None }))), - Ok(1), - ); - assert_eq!( - to_account(MultiLocation::new(0, X1(AccountIndex64 { index: 42, network: None }))), - Ok(42), - ); + assert_eq!(to_account(Location::new(0, [AccountIndex64 { index: 1, network: None }])), Ok(1),); + assert_eq!(to_account(Location::new(0, [AccountIndex64 { index: 42, network: None }])), Ok(42),); assert_eq!(to_account(Here), Ok(3000)); } @@ -65,7 +59,7 @@ fn code_registers_should_work() { SetErrorHandler(Xcm(vec![ TransferAsset { assets: (Here, 2u128).into(), - beneficiary: X1(AccountIndex64 { index: 3, network: None }).into(), + beneficiary: [AccountIndex64 { index: 3, network: None }].into(), }, // It was handled fine. ClearError, @@ -73,33 +67,33 @@ fn code_registers_should_work() { // Set the appendix - this will always fire. SetAppendix(Xcm(vec![TransferAsset { assets: (Here, 4u128).into(), - beneficiary: X1(AccountIndex64 { index: 3, network: None }).into(), + beneficiary: [AccountIndex64 { index: 3, network: None }].into(), }])), // First xfer always works ok TransferAsset { assets: (Here, 1u128).into(), - beneficiary: X1(AccountIndex64 { index: 3, network: None }).into(), + beneficiary: [AccountIndex64 { index: 3, network: None }].into(), }, // Second xfer results in error on the second message - our error handler will fire. TransferAsset { assets: (Here, 8u128).into(), - beneficiary: X1(AccountIndex64 { index: 3, network: None }).into(), + beneficiary: [AccountIndex64 { index: 3, network: None }].into(), }, ]); // Weight limit of 70 is needed. let limit = ::Weigher::weight(&mut message).unwrap(); assert_eq!(limit, Weight::from_parts(70, 70)); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm(Here, message.clone(), hash, limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(50, 50))); // We don't pay the 20 weight for the error handler. + let r = XcmExecutor::::prepare_and_execute(Here, message.clone(), &mut hash, limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(50, 50) }); // We don't pay the 20 weight for the error handler. assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 13u128).into()]); assert_eq!(asset_list(Here), vec![(Here, 8u128).into()]); assert_eq!(sent_xcm(), vec![]); - let r = XcmExecutor::::execute_xcm(Here, message, hash, limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(70, 70))); // We pay the full weight here. + let r = XcmExecutor::::prepare_and_execute(Here, message, &mut hash, limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(70, 70) }); // We pay the full weight here. assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 20u128).into()]); assert_eq!(asset_list(Here), vec![(Here, 1u128).into()]); assert_eq!(sent_xcm(), vec![]); diff --git a/polkadot/xcm/xcm-builder/src/tests/bridging/local_para_para.rs b/polkadot/xcm/xcm-builder/src/tests/bridging/local_para_para.rs index 406843a0fe8a..17a1d5324bad 100644 --- a/polkadot/xcm/xcm-builder/src/tests/bridging/local_para_para.rs +++ b/polkadot/xcm/xcm-builder/src/tests/bridging/local_para_para.rs @@ -21,8 +21,8 @@ use super::*; parameter_types! { - pub UniversalLocation: Junctions = X2(GlobalConsensus(Local::get()), Parachain(1)); - pub RemoteUniversalLocation: Junctions = X2(GlobalConsensus(Remote::get()), Parachain(1)); + pub UniversalLocation: Junctions = [GlobalConsensus(Local::get()), Parachain(1)].into(); + pub RemoteUniversalLocation: Junctions = [GlobalConsensus(Remote::get()), Parachain(1)].into(); } type TheBridge = TestBridge>; diff --git a/polkadot/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs b/polkadot/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs index 02c454bb2129..08a87b393689 100644 --- a/polkadot/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs +++ b/polkadot/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs @@ -21,8 +21,8 @@ use super::*; parameter_types! { - pub UniversalLocation: Junctions = X1(GlobalConsensus(Local::get())); - pub RemoteUniversalLocation: Junctions = X1(GlobalConsensus(Remote::get())); + pub UniversalLocation: Junctions = [GlobalConsensus(Local::get())].into(); + pub RemoteUniversalLocation: Junctions = [GlobalConsensus(Remote::get())].into(); } type TheBridge = TestBridge>; diff --git a/polkadot/xcm/xcm-builder/src/tests/bridging/mod.rs b/polkadot/xcm/xcm-builder/src/tests/bridging/mod.rs index 45630dbfc248..69f9732f68a2 100644 --- a/polkadot/xcm/xcm-builder/src/tests/bridging/mod.rs +++ b/polkadot/xcm/xcm-builder/src/tests/bridging/mod.rs @@ -36,7 +36,7 @@ mod remote_relay_relay; parameter_types! { pub Local: NetworkId = ByGenesis([0; 32]); pub Remote: NetworkId = ByGenesis([1; 32]); - pub Price: MultiAssets = MultiAssets::from((Here, 100u128)); + pub Price: Assets = Assets::from((Here, 100u128)); pub static UsingTopic: bool = false; } @@ -91,7 +91,7 @@ impl SendXcm for TestTopic { } } fn validate( - destination: &mut Option, + destination: &mut Option, message: &mut Option>, ) -> SendResult { Ok(if UsingTopic::get() { @@ -119,26 +119,26 @@ impl HaulBlob for TestBridge { } std::thread_local! { - static REMOTE_INCOMING_XCM: RefCell)>> = RefCell::new(Vec::new()); + static REMOTE_INCOMING_XCM: RefCell)>> = RefCell::new(Vec::new()); } struct TestRemoteIncomingRouter; impl SendXcm for TestRemoteIncomingRouter { - type Ticket = (MultiLocation, Xcm<()>); + type Ticket = (Location, Xcm<()>); fn validate( - dest: &mut Option, + dest: &mut Option, msg: &mut Option>, - ) -> SendResult<(MultiLocation, Xcm<()>)> { + ) -> SendResult<(Location, Xcm<()>)> { let pair = (dest.take().unwrap(), msg.take().unwrap()); - Ok((pair, MultiAssets::new())) + Ok((pair, Assets::new())) } - fn deliver(pair: (MultiLocation, Xcm<()>)) -> Result { + fn deliver(pair: (Location, Xcm<()>)) -> Result { let hash = fake_id(); REMOTE_INCOMING_XCM.with(|q| q.borrow_mut().push(pair)); Ok(hash) } } -fn take_received_remote_messages() -> Vec<(MultiLocation, Xcm<()>)> { +fn take_received_remote_messages() -> Vec<(Location, Xcm<()>)> { REMOTE_INCOMING_XCM.with(|r| r.replace(vec![])) } @@ -151,18 +151,18 @@ struct UnpaidExecutingRouter( fn price( n: NetworkId, c: u32, - s: &InteriorMultiLocation, - d: &InteriorMultiLocation, + s: &InteriorLocation, + d: &InteriorLocation, m: &Xcm<()>, -) -> Result { - Ok(validate_export::(n, c, *s, *d, m.clone())?.1) +) -> Result { + Ok(validate_export::(n, c, s.clone(), d.clone(), m.clone())?.1) } fn deliver( n: NetworkId, c: u32, - s: InteriorMultiLocation, - d: InteriorMultiLocation, + s: InteriorLocation, + d: InteriorLocation, m: Xcm<()>, ) -> Result { export_xcm::(n, c, s, d, m).map(|(hash, _)| hash) @@ -188,7 +188,7 @@ impl, Remote: Get, RemoteExporter: ExportXcm> S type Ticket = Xcm<()>; fn validate( - destination: &mut Option, + destination: &mut Option, message: &mut Option>, ) -> SendResult> { let expect_dest = Remote::get().relative_to(&Local::get()); @@ -196,7 +196,7 @@ impl, Remote: Get, RemoteExporter: ExportXcm> S return Err(NotApplicable) } let message = message.take().ok_or(MissingArgument)?; - Ok((message, MultiAssets::new())) + Ok((message, Assets::new())) } fn deliver(message: Xcm<()>) -> Result { @@ -205,7 +205,7 @@ impl, Remote: Get, RemoteExporter: ExportXcm> S // though it is `Remote`. ExecutorUniversalLocation::set(Remote::get()); let origin = Local::get().relative_to(&Remote::get()); - AllowUnpaidFrom::set(vec![origin]); + AllowUnpaidFrom::set(vec![origin.clone()]); set_exporter_override(price::, deliver::); // The we execute it: let mut id = fake_id(); @@ -221,9 +221,9 @@ impl, Remote: Get, RemoteExporter: ExportXcm> S let entry = LogEntry { local, remote, id, message, outcome: outcome.clone(), paid: false }; RoutingLog::mutate(|l| l.push(entry)); match outcome { - Outcome::Complete(..) => Ok(id), - Outcome::Incomplete(..) => Err(Transport("Error executing")), - Outcome::Error(..) => Err(Transport("Unable to execute")), + Outcome::Complete { .. } => Ok(id), + Outcome::Incomplete { .. } => Err(Transport("Error executing")), + Outcome::Error { .. } => Err(Transport("Unable to execute")), } } } @@ -238,7 +238,7 @@ impl, Remote: Get, RemoteExporter: ExportXcm> S type Ticket = Xcm<()>; fn validate( - destination: &mut Option, + destination: &mut Option, message: &mut Option>, ) -> SendResult> { let expect_dest = Remote::get().relative_to(&Local::get()); @@ -246,7 +246,7 @@ impl, Remote: Get, RemoteExporter: ExportXcm> S return Err(NotApplicable) } let message = message.take().ok_or(MissingArgument)?; - Ok((message, MultiAssets::new())) + Ok((message, Assets::new())) } fn deliver(message: Xcm<()>) -> Result { @@ -255,7 +255,7 @@ impl, Remote: Get, RemoteExporter: ExportXcm> S // though it is `Remote`. ExecutorUniversalLocation::set(Remote::get()); let origin = Local::get().relative_to(&Remote::get()); - AllowPaidFrom::set(vec![origin]); + AllowPaidFrom::set(vec![origin.clone()]); set_exporter_override(price::, deliver::); // Then we execute it: let mut id = fake_id(); @@ -271,9 +271,9 @@ impl, Remote: Get, RemoteExporter: ExportXcm> S let entry = LogEntry { local, remote, id, message, outcome: outcome.clone(), paid: true }; RoutingLog::mutate(|l| l.push(entry)); match outcome { - Outcome::Complete(..) => Ok(id), - Outcome::Incomplete(..) => Err(Transport("Error executing")), - Outcome::Error(..) => Err(Transport("Unable to execute")), + Outcome::Complete { .. } => Ok(id), + Outcome::Incomplete { .. } => Err(Transport("Error executing")), + Outcome::Error { .. } => Err(Transport("Unable to execute")), } } } diff --git a/polkadot/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs b/polkadot/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs index 45dc2d4a3b9a..d7849f98e04a 100644 --- a/polkadot/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs +++ b/polkadot/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs @@ -24,14 +24,14 @@ use super::*; parameter_types! { - pub UniversalLocation: Junctions = X2(GlobalConsensus(Local::get()), Parachain(100)); - pub RelayUniversalLocation: Junctions = X1(GlobalConsensus(Local::get())); - pub RemoteUniversalLocation: Junctions = X1(GlobalConsensus(Remote::get())); + pub UniversalLocation: Junctions = [GlobalConsensus(Local::get()), Parachain(100)].into(); + pub RelayUniversalLocation: Junctions = [GlobalConsensus(Local::get())].into(); + pub RemoteUniversalLocation: Junctions = [GlobalConsensus(Remote::get())].into(); pub BridgeTable: Vec = vec![ NetworkExportTableItem::new( Remote::get(), None, - MultiLocation::parent(), + Location::parent(), Some((Parent, 200u128 + if UsingTopic::get() { 20 } else { 0 }).into()) ) ]; @@ -62,7 +62,7 @@ type LocalRouter = TestTopic<(LocalInnerRouter, LocalBridgeRouter)>; #[test] fn sending_to_bridged_chain_works() { maybe_with_topic(|| { - let dest: MultiLocation = (Parent, Parent, Remote::get()).into(); + let dest: Location = (Parent, Parent, Remote::get()).into(); // Initialize the local relay so that our parachain has funds to pay for export. clear_assets(Parachain(100)); @@ -97,7 +97,7 @@ fn sending_to_bridged_chain_works() { message: xcm_with_topic( maybe_forward_id_for(&[0; 32]), vec![ - WithdrawAsset(MultiAsset::from((Here, price)).into()), + WithdrawAsset(Asset::from((Here, price)).into()), BuyExecution { fees: (Here, price).into(), weight_limit: Unlimited }, ExportMessage { network: ByGenesis([1; 32]), @@ -108,7 +108,7 @@ fn sending_to_bridged_chain_works() { DepositAsset { assets: Wild(All), beneficiary: Parachain(100).into() }, ], ), - outcome: Outcome::Complete(test_weight(5)), + outcome: Outcome::Complete { used: test_weight(5) }, paid: true, }; assert_eq!(RoutingLog::take(), vec![entry]); @@ -116,7 +116,7 @@ fn sending_to_bridged_chain_works() { } #[test] fn sending_to_bridged_chain_without_funds_fails() { - let dest: MultiLocation = (Parent, Parent, Remote::get()).into(); + let dest: Location = (Parent, Parent, Remote::get()).into(); // Routing won't work if we don't have enough funds. assert_eq!( send_xcm::(dest, Xcm(vec![Trap(1)])), @@ -137,7 +137,7 @@ fn sending_to_bridged_chain_without_funds_fails() { #[test] fn sending_to_parachain_of_bridged_chain_works() { maybe_with_topic(|| { - let dest: MultiLocation = (Parent, Parent, Remote::get(), Parachain(100)).into(); + let dest: Location = (Parent, Parent, Remote::get(), Parachain(100)).into(); // Initialize the local relay so that our parachain has funds to pay for export. clear_assets(Parachain(100)); @@ -172,7 +172,7 @@ fn sending_to_parachain_of_bridged_chain_works() { message: xcm_with_topic( maybe_forward_id_for(&[0; 32]), vec![ - WithdrawAsset(MultiAsset::from((Here, price)).into()), + WithdrawAsset(Asset::from((Here, price)).into()), BuyExecution { fees: (Here, price).into(), weight_limit: Unlimited }, ExportMessage { network: ByGenesis([1; 32]), @@ -183,7 +183,7 @@ fn sending_to_parachain_of_bridged_chain_works() { DepositAsset { assets: Wild(All), beneficiary: Parachain(100).into() }, ], ), - outcome: Outcome::Complete(test_weight(5)), + outcome: Outcome::Complete { used: test_weight(5) }, paid: true, }; assert_eq!(RoutingLog::take(), vec![entry]); @@ -191,7 +191,7 @@ fn sending_to_parachain_of_bridged_chain_works() { } #[test] fn sending_to_parachain_of_bridged_chain_without_funds_fails() { - let dest: MultiLocation = (Parent, Parent, Remote::get(), Parachain(100)).into(); + let dest: Location = (Parent, Parent, Remote::get(), Parachain(100)).into(); // Routing won't work if we don't have enough funds. assert_eq!( send_xcm::(dest, Xcm(vec![Trap(1)])), diff --git a/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs b/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs index f11143ab9f6f..929dc28d891c 100644 --- a/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs +++ b/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs @@ -21,9 +21,9 @@ use super::*; parameter_types! { - pub UniversalLocation: Junctions = X2(GlobalConsensus(Local::get()), Parachain(1000)); - pub ParaBridgeUniversalLocation: Junctions = X2(GlobalConsensus(Local::get()), Parachain(1)); - pub RemoteParaBridgeUniversalLocation: Junctions = X2(GlobalConsensus(Remote::get()), Parachain(1)); + pub UniversalLocation: Junctions = [GlobalConsensus(Local::get()), Parachain(1000)].into(); + pub ParaBridgeUniversalLocation: Junctions = [GlobalConsensus(Local::get()), Parachain(1)].into(); + pub RemoteParaBridgeUniversalLocation: Junctions = [GlobalConsensus(Remote::get()), Parachain(1)].into(); pub BridgeTable: Vec = vec![ NetworkExportTableItem::new( Remote::get(), @@ -61,7 +61,7 @@ fn sending_to_bridged_chain_works() { send_xcm::((Parent, Parent, Remote::get(), Parachain(1)).into(), msg) .unwrap() .1, - MultiAssets::new() + Assets::new() ); assert_eq!(TheBridge::service(), 1); assert_eq!( @@ -93,7 +93,7 @@ fn sending_to_bridged_chain_works() { }, ], ), - outcome: Outcome::Complete(test_weight(2)), + outcome: Outcome::Complete { used: test_weight(2) }, paid: false, }; assert_eq!(RoutingLog::take(), vec![entry]); @@ -115,7 +115,7 @@ fn sending_to_sibling_of_bridged_chain_works() { maybe_with_topic(|| { let msg = Xcm(vec![Trap(1)]); let dest = (Parent, Parent, Remote::get(), Parachain(1000)).into(); - assert_eq!(send_xcm::(dest, msg).unwrap().1, MultiAssets::new()); + assert_eq!(send_xcm::(dest, msg).unwrap().1, Assets::new()); assert_eq!(TheBridge::service(), 1); let expected = vec![( (Parent, Parachain(1000)).into(), @@ -144,7 +144,7 @@ fn sending_to_sibling_of_bridged_chain_works() { }, ], ), - outcome: Outcome::Complete(test_weight(2)), + outcome: Outcome::Complete { used: test_weight(2) }, paid: false, }; assert_eq!(RoutingLog::take(), vec![entry]); @@ -166,7 +166,7 @@ fn sending_to_relay_of_bridged_chain_works() { maybe_with_topic(|| { let msg = Xcm(vec![Trap(1)]); let dest = (Parent, Parent, Remote::get()).into(); - assert_eq!(send_xcm::(dest, msg).unwrap().1, MultiAssets::new()); + assert_eq!(send_xcm::(dest, msg).unwrap().1, Assets::new()); assert_eq!(TheBridge::service(), 1); let expected = vec![( Parent.into(), @@ -195,7 +195,7 @@ fn sending_to_relay_of_bridged_chain_works() { }, ], ), - outcome: Outcome::Complete(test_weight(2)), + outcome: Outcome::Complete { used: test_weight(2) }, paid: false, }; assert_eq!(RoutingLog::take(), vec![entry]); diff --git a/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs b/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs index 7218e0a04880..b5ff49ec6d68 100644 --- a/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs +++ b/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs @@ -21,9 +21,9 @@ use super::*; parameter_types! { - pub UniversalLocation: Junctions = X1(GlobalConsensus(Local::get())); - pub ParaBridgeUniversalLocation: Junctions = X2(GlobalConsensus(Local::get()), Parachain(1)); - pub RemoteParaBridgeUniversalLocation: Junctions = X2(GlobalConsensus(Remote::get()), Parachain(1)); + pub UniversalLocation: Junctions = [GlobalConsensus(Local::get())].into(); + pub ParaBridgeUniversalLocation: Junctions = [GlobalConsensus(Local::get()), Parachain(1)].into(); + pub RemoteParaBridgeUniversalLocation: Junctions = [GlobalConsensus(Remote::get()), Parachain(1)].into(); pub BridgeTable: Vec = vec![ NetworkExportTableItem::new( Remote::get(), @@ -61,7 +61,7 @@ fn sending_to_bridged_chain_works() { send_xcm::((Parent, Remote::get(), Parachain(1)).into(), msg) .unwrap() .1, - MultiAssets::new() + Assets::new() ); assert_eq!(TheBridge::service(), 1); let expected = vec![( @@ -84,7 +84,7 @@ fn sending_to_bridged_chain_works() { }, ], ), - outcome: Outcome::Complete(test_weight(2)), + outcome: Outcome::Complete { used: test_weight(2) }, paid: false, }; assert_eq!(RoutingLog::take(), vec![entry]); @@ -106,7 +106,7 @@ fn sending_to_sibling_of_bridged_chain_works() { maybe_with_topic(|| { let msg = Xcm(vec![Trap(1)]); let dest = (Parent, Remote::get(), Parachain(1000)).into(); - assert_eq!(send_xcm::(dest, msg).unwrap().1, MultiAssets::new()); + assert_eq!(send_xcm::(dest, msg).unwrap().1, Assets::new()); assert_eq!(TheBridge::service(), 1); let expected = vec![( (Parent, Parachain(1000)).into(), @@ -128,7 +128,7 @@ fn sending_to_sibling_of_bridged_chain_works() { }, ], ), - outcome: Outcome::Complete(test_weight(2)), + outcome: Outcome::Complete { used: test_weight(2) }, paid: false, }; assert_eq!(RoutingLog::take(), vec![entry]); @@ -150,7 +150,7 @@ fn sending_to_relay_of_bridged_chain_works() { maybe_with_topic(|| { let msg = Xcm(vec![Trap(1)]); let dest = (Parent, Remote::get()).into(); - assert_eq!(send_xcm::(dest, msg).unwrap().1, MultiAssets::new()); + assert_eq!(send_xcm::(dest, msg).unwrap().1, Assets::new()); assert_eq!(TheBridge::service(), 1); let expected = vec![( Parent.into(), @@ -172,7 +172,7 @@ fn sending_to_relay_of_bridged_chain_works() { }, ], ), - outcome: Outcome::Complete(test_weight(2)), + outcome: Outcome::Complete { used: test_weight(2) }, paid: false, }; assert_eq!(RoutingLog::take(), vec![entry]); diff --git a/polkadot/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs b/polkadot/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs index 45b5efbc44c5..19e3a86e2a7c 100644 --- a/polkadot/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs +++ b/polkadot/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs @@ -21,14 +21,14 @@ use super::*; parameter_types! { - pub UniversalLocation: Junctions = X2(GlobalConsensus(Local::get()), Parachain(1000)); - pub RelayUniversalLocation: Junctions = X1(GlobalConsensus(Local::get())); - pub RemoteUniversalLocation: Junctions = X1(GlobalConsensus(Remote::get())); + pub UniversalLocation: Junctions = [GlobalConsensus(Local::get()), Parachain(1000)].into(); + pub RelayUniversalLocation: Junctions = [GlobalConsensus(Local::get())].into(); + pub RemoteUniversalLocation: Junctions = [GlobalConsensus(Remote::get())].into(); pub BridgeTable: Vec = vec![ NetworkExportTableItem::new( Remote::get(), None, - MultiLocation::parent(), + Location::parent(), None ) ]; @@ -58,7 +58,7 @@ fn sending_to_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); assert_eq!( send_xcm::((Parent, Parent, Remote::get()).into(), msg).unwrap().1, - MultiAssets::new() + Assets::new() ); assert_eq!(TheBridge::service(), 1); assert_eq!( @@ -90,7 +90,7 @@ fn sending_to_bridged_chain_works() { }, ], ), - outcome: Outcome::Complete(test_weight(2)), + outcome: Outcome::Complete { used: test_weight(2) }, paid: false, }; assert_eq!(RoutingLog::take(), vec![entry]); @@ -112,7 +112,7 @@ fn sending_to_parachain_of_bridged_chain_works() { maybe_with_topic(|| { let msg = Xcm(vec![Trap(1)]); let dest = (Parent, Parent, Remote::get(), Parachain(1000)).into(); - assert_eq!(send_xcm::(dest, msg).unwrap().1, MultiAssets::new()); + assert_eq!(send_xcm::(dest, msg).unwrap().1, Assets::new()); assert_eq!(TheBridge::service(), 1); let expected = vec![( Parachain(1000).into(), @@ -141,7 +141,7 @@ fn sending_to_parachain_of_bridged_chain_works() { }, ], ), - outcome: Outcome::Complete(test_weight(2)), + outcome: Outcome::Complete { used: test_weight(2) }, paid: false, }; assert_eq!(RoutingLog::take(), vec![entry]); diff --git a/polkadot/xcm/xcm-builder/src/tests/expecting.rs b/polkadot/xcm/xcm-builder/src/tests/expecting.rs index 6d5e0ff47b51..82289de69484 100644 --- a/polkadot/xcm/xcm-builder/src/tests/expecting.rs +++ b/polkadot/xcm/xcm-builder/src/tests/expecting.rs @@ -18,7 +18,7 @@ use super::*; #[test] fn expect_pallet_should_work() { - AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); + AllowUnpaidFrom::set(vec![[Parachain(1)].into()]); // They want to transfer 100 of our native asset from sovereign account of parachain #1 into #2 // and let them know to hand it to account #3. let message = Xcm(vec![ExpectPallet { @@ -28,14 +28,15 @@ fn expect_pallet_should_work() { crate_major: 1, min_crate_minor: 42, }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); let message = Xcm(vec![ExpectPallet { index: 1, @@ -44,19 +45,20 @@ fn expect_pallet_should_work() { crate_major: 1, min_crate_minor: 41, }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); } #[test] fn expect_pallet_should_fail_correctly() { - AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); + AllowUnpaidFrom::set(vec![[Parachain(1)].into()]); let message = Xcm(vec![ExpectPallet { index: 1, name: b"Balances".as_ref().into(), @@ -64,14 +66,15 @@ fn expect_pallet_should_fail_correctly() { crate_major: 1, min_crate_minor: 60, }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::VersionIncompatible)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::VersionIncompatible }); let message = Xcm(vec![ExpectPallet { index: 1, @@ -80,14 +83,15 @@ fn expect_pallet_should_fail_correctly() { crate_major: 1, min_crate_minor: 42, }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::NameMismatch)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::NameMismatch }); let message = Xcm(vec![ExpectPallet { index: 1, @@ -96,14 +100,15 @@ fn expect_pallet_should_fail_correctly() { crate_major: 1, min_crate_minor: 42, }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::NameMismatch)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::NameMismatch }); let message = Xcm(vec![ExpectPallet { index: 0, @@ -112,14 +117,15 @@ fn expect_pallet_should_fail_correctly() { crate_major: 1, min_crate_minor: 42, }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::NameMismatch)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::NameMismatch }); let message = Xcm(vec![ExpectPallet { index: 2, @@ -128,14 +134,15 @@ fn expect_pallet_should_fail_correctly() { crate_major: 1, min_crate_minor: 42, }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::PalletNotFound)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::PalletNotFound }); let message = Xcm(vec![ExpectPallet { index: 1, @@ -144,14 +151,15 @@ fn expect_pallet_should_fail_correctly() { crate_major: 2, min_crate_minor: 42, }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::VersionIncompatible)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::VersionIncompatible }); let message = Xcm(vec![ExpectPallet { index: 1, @@ -160,14 +168,15 @@ fn expect_pallet_should_fail_correctly() { crate_major: 0, min_crate_minor: 42, }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::VersionIncompatible)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::VersionIncompatible }); let message = Xcm(vec![ExpectPallet { index: 1, @@ -176,12 +185,13 @@ fn expect_pallet_should_fail_correctly() { crate_major: 1, min_crate_minor: 43, }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::VersionIncompatible)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::VersionIncompatible }); } diff --git a/polkadot/xcm/xcm-builder/src/tests/locking.rs b/polkadot/xcm/xcm-builder/src/tests/locking.rs index f4ef618ac0e7..bc72ad458cdf 100644 --- a/polkadot/xcm/xcm-builder/src/tests/locking.rs +++ b/polkadot/xcm/xcm-builder/src/tests/locking.rs @@ -34,10 +34,10 @@ fn lock_roundtrip_should_work() { ), LockAsset { asset: (Parent, 100u128).into(), unlocker: (Parent, Parachain(1)).into() }, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let r = - XcmExecutor::::execute_xcm((3u64,), message, hash, Weight::from_parts(50, 50)); - assert_eq!(r, Outcome::Complete(Weight::from_parts(40, 40))); + XcmExecutor::::prepare_and_execute((3u64,), message, &mut hash, Weight::from_parts(50, 50), Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(40, 40) }); assert_eq!(asset_list((3u64,)), vec![(Parent, 990u128).into()]); let expected_msg = Xcm::<()>(vec![NoteUnlockable { @@ -58,14 +58,15 @@ fn lock_roundtrip_should_work() { // Now we'll unlock it. let message = Xcm(vec![UnlockAsset { asset: (Parent, 100u128).into(), target: (3u64,).into() }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( (Parent, Parachain(1)), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); } #[test] @@ -82,10 +83,10 @@ fn auto_fee_paying_should_work() { SetFeesMode { jit_withdraw: true }, LockAsset { asset: (Parent, 100u128).into(), unlocker: (Parent, Parachain(1)).into() }, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let r = - XcmExecutor::::execute_xcm((3u64,), message, hash, Weight::from_parts(50, 50)); - assert_eq!(r, Outcome::Complete(Weight::from_parts(20, 20))); + XcmExecutor::::prepare_and_execute((3u64,), message, &mut hash, Weight::from_parts(50, 50), Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(20, 20) }); assert_eq!(asset_list((3u64,)), vec![(Parent, 990u128).into()]); } @@ -100,10 +101,10 @@ fn lock_should_fail_correctly() { asset: (Parent, 100u128).into(), unlocker: (Parent, Parachain(1)).into(), }]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let r = - XcmExecutor::::execute_xcm((3u64,), message, hash, Weight::from_parts(50, 50)); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::LockError)); + XcmExecutor::::prepare_and_execute((3u64,), message, &mut hash, Weight::from_parts(50, 50), Weight::zero()); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::LockError }); assert_eq!(sent_xcm(), vec![]); assert_eq!(take_lock_trace(), vec![]); @@ -118,10 +119,10 @@ fn lock_should_fail_correctly() { asset: (Parent, 100u128).into(), unlocker: (Parent, Parachain(1)).into(), }]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let r = - XcmExecutor::::execute_xcm((3u64,), message, hash, Weight::from_parts(50, 50)); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::NotHoldingFees)); + XcmExecutor::::prepare_and_execute((3u64,), message, &mut hash, Weight::from_parts(50, 50), Weight::zero()); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::NotHoldingFees }); assert_eq!(sent_xcm(), vec![]); assert_eq!(take_lock_trace(), vec![]); } @@ -140,14 +141,15 @@ fn remote_unlock_roundtrip_should_work() { // This caused Parachain #1 to send us the NoteUnlockable instruction. let message = Xcm(vec![NoteUnlockable { asset: (Parent, 100u128).into(), owner: (3u64,).into() }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( (Parent, Parachain(1)), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); assert_eq!( take_lock_trace(), vec![Note { @@ -165,10 +167,10 @@ fn remote_unlock_roundtrip_should_work() { ), RequestUnlock { asset: (Parent, 100u128).into(), locker: (Parent, Parachain(1)).into() }, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let r = - XcmExecutor::::execute_xcm((3u64,), message, hash, Weight::from_parts(50, 50)); - assert_eq!(r, Outcome::Complete(Weight::from_parts(40, 40))); + XcmExecutor::::prepare_and_execute((3u64,), message, &mut hash, Weight::from_parts(50, 50), Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(40, 40) }); assert_eq!(asset_list((3u64,)), vec![(Parent, 990u128).into()]); let expected_msg = Xcm::<()>(vec![UnlockAsset { @@ -201,24 +203,25 @@ fn remote_unlock_should_fail_correctly() { asset: (Parent, 100u128).into(), locker: (Parent, Parachain(1)).into(), }]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let r = - XcmExecutor::::execute_xcm((3u64,), message, hash, Weight::from_parts(50, 50)); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::LockError)); + XcmExecutor::::prepare_and_execute((3u64,), message, &mut hash, Weight::from_parts(50, 50), Weight::zero()); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::LockError }); assert_eq!(sent_xcm(), vec![]); assert_eq!(take_lock_trace(), vec![]); // We have been told by Parachain #1 that Account #3 has locked funds which we can unlock. let message = Xcm(vec![NoteUnlockable { asset: (Parent, 100u128).into(), owner: (3u64,).into() }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( (Parent, Parachain(1)), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); let _discard = take_lock_trace(); // We want to unlock 100 of the native parent tokens which were locked for us on parachain. @@ -228,10 +231,10 @@ fn remote_unlock_should_fail_correctly() { asset: (Parent, 100u128).into(), locker: (Parent, Parachain(1)).into(), }]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let r = - XcmExecutor::::execute_xcm((3u64,), message, hash, Weight::from_parts(50, 50)); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::NotHoldingFees)); + XcmExecutor::::prepare_and_execute((3u64,), message, &mut hash, Weight::from_parts(50, 50), Weight::zero()); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::NotHoldingFees }); assert_eq!(sent_xcm(), vec![]); assert_eq!(take_lock_trace(), vec![]); diff --git a/polkadot/xcm/xcm-builder/src/tests/mock.rs b/polkadot/xcm/xcm-builder/src/tests/mock.rs index 189274eb5f5b..4d497735723e 100644 --- a/polkadot/xcm/xcm-builder/src/tests/mock.rs +++ b/polkadot/xcm/xcm-builder/src/tests/mock.rs @@ -30,7 +30,7 @@ pub use frame_support::{ dispatch::{ DispatchInfo, DispatchResultWithPostInfo, GetDispatchInfo, Parameter, PostDispatchInfo, }, - ensure, match_types, parameter_types, + ensure, parameter_types, sp_runtime::{traits::Dispatchable, DispatchError, DispatchErrorWithPostInfo}, traits::{ConstU32, Contains, Get, IsInVec}, }; @@ -49,7 +49,7 @@ pub use xcm_executor::{ AssetExchange, AssetLock, CheckSuspension, ConvertOrigin, Enact, ExportXcm, FeeManager, FeeReason, LockError, OnResponse, TransactAsset, }, - Assets, Config, + Config, AssetsInHolding, }; pub enum TestOrigin { @@ -113,52 +113,52 @@ impl GetDispatchInfo for TestCall { } thread_local! { - pub static SENT_XCM: RefCell, XcmHash)>> = RefCell::new(Vec::new()); + pub static SENT_XCM: RefCell, XcmHash)>> = RefCell::new(Vec::new()); pub static EXPORTED_XCM: RefCell< - Vec<(NetworkId, u32, InteriorMultiLocation, InteriorMultiLocation, Xcm<()>, XcmHash)> + Vec<(NetworkId, u32, InteriorLocation, InteriorLocation, Xcm<()>, XcmHash)> > = RefCell::new(Vec::new()); pub static EXPORTER_OVERRIDE: RefCell, - ) -> Result, + ) -> Result, fn( NetworkId, u32, - InteriorMultiLocation, - InteriorMultiLocation, + InteriorLocation, + InteriorLocation, Xcm<()>, ) -> Result, )>> = RefCell::new(None); - pub static SEND_PRICE: RefCell = RefCell::new(MultiAssets::new()); + pub static SEND_PRICE: RefCell = RefCell::new(Assets::new()); pub static SUSPENDED: Cell = Cell::new(false); } -pub fn sent_xcm() -> Vec<(MultiLocation, opaque::Xcm, XcmHash)> { +pub fn sent_xcm() -> Vec<(Location, opaque::Xcm, XcmHash)> { SENT_XCM.with(|q| (*q.borrow()).clone()) } -pub fn set_send_price(p: impl Into) { +pub fn set_send_price(p: impl Into) { SEND_PRICE.with(|l| l.replace(p.into().into())); } pub fn exported_xcm( -) -> Vec<(NetworkId, u32, InteriorMultiLocation, InteriorMultiLocation, opaque::Xcm, XcmHash)> { +) -> Vec<(NetworkId, u32, InteriorLocation, InteriorLocation, opaque::Xcm, XcmHash)> { EXPORTED_XCM.with(|q| (*q.borrow()).clone()) } pub fn set_exporter_override( price: fn( NetworkId, u32, - &InteriorMultiLocation, - &InteriorMultiLocation, + &InteriorLocation, + &InteriorLocation, &Xcm<()>, - ) -> Result, + ) -> Result, deliver: fn( NetworkId, u32, - InteriorMultiLocation, - InteriorMultiLocation, + InteriorLocation, + InteriorLocation, Xcm<()>, ) -> Result, ) { @@ -170,17 +170,17 @@ pub fn clear_exporter_override() { } pub struct TestMessageSender; impl SendXcm for TestMessageSender { - type Ticket = (MultiLocation, Xcm<()>, XcmHash); + type Ticket = (Location, Xcm<()>, XcmHash); fn validate( - dest: &mut Option, + dest: &mut Option, msg: &mut Option>, - ) -> SendResult<(MultiLocation, Xcm<()>, XcmHash)> { + ) -> SendResult<(Location, Xcm<()>, XcmHash)> { let msg = msg.take().unwrap(); let hash = fake_message_hash(&msg); let triplet = (dest.take().unwrap(), msg, hash); Ok((triplet, SEND_PRICE.with(|l| l.borrow().clone()))) } - fn deliver(triplet: (MultiLocation, Xcm<()>, XcmHash)) -> Result { + fn deliver(triplet: (Location, Xcm<()>, XcmHash)) -> Result { let hash = triplet.2; SENT_XCM.with(|q| q.borrow_mut().push(triplet)); Ok(hash) @@ -188,21 +188,20 @@ impl SendXcm for TestMessageSender { } pub struct TestMessageExporter; impl ExportXcm for TestMessageExporter { - type Ticket = (NetworkId, u32, InteriorMultiLocation, InteriorMultiLocation, Xcm<()>, XcmHash); + type Ticket = (NetworkId, u32, InteriorLocation, InteriorLocation, Xcm<()>, XcmHash); fn validate( network: NetworkId, channel: u32, - uni_src: &mut Option, - dest: &mut Option, + uni_src: &mut Option, + dest: &mut Option, msg: &mut Option>, - ) -> SendResult<(NetworkId, u32, InteriorMultiLocation, InteriorMultiLocation, Xcm<()>, XcmHash)> - { + ) -> SendResult<(NetworkId, u32, InteriorLocation, InteriorLocation, Xcm<()>, XcmHash)> { let (s, d, m) = (uni_src.take().unwrap(), dest.take().unwrap(), msg.take().unwrap()); - let r: Result = EXPORTER_OVERRIDE.with(|e| { + let r: Result = EXPORTER_OVERRIDE.with(|e| { if let Some((ref f, _)) = &*e.borrow() { f(network, channel, &s, &d, &m) } else { - Ok(MultiAssets::new()) + Ok(Assets::new()) } }); let h = fake_message_hash(&m); @@ -217,7 +216,7 @@ impl ExportXcm for TestMessageExporter { } } fn deliver( - tuple: (NetworkId, u32, InteriorMultiLocation, InteriorMultiLocation, Xcm<()>, XcmHash), + tuple: (NetworkId, u32, InteriorLocation, InteriorLocation, Xcm<()>, XcmHash), ) -> Result { EXPORTER_OVERRIDE.with(|e| { if let Some((_, ref f)) = &*e.borrow() { @@ -233,37 +232,42 @@ impl ExportXcm for TestMessageExporter { } thread_local! { - pub static ASSETS: RefCell> = RefCell::new(BTreeMap::new()); + pub static ASSETS: RefCell> = RefCell::new(BTreeMap::new()); } -pub fn assets(who: impl Into) -> Assets { +pub fn assets(who: impl Into) -> AssetsInHolding { ASSETS.with(|a| a.borrow().get(&who.into()).cloned()).unwrap_or_default() } -pub fn asset_list(who: impl Into) -> Vec { - MultiAssets::from(assets(who)).into_inner() +pub fn asset_list(who: impl Into) -> Vec { + Assets::from(assets(who)).into_inner() } -pub fn add_asset(who: impl Into, what: impl Into) { - ASSETS.with(|a| a.borrow_mut().entry(who.into()).or_insert(Assets::new()).subsume(what.into())); +pub fn add_asset(who: impl Into, what: impl Into) { + ASSETS.with(|a| { + a.borrow_mut() + .entry(who.into()) + .or_insert(AssetsInHolding::new()) + .subsume(what.into()) + }); } -pub fn clear_assets(who: impl Into) { +pub fn clear_assets(who: impl Into) { ASSETS.with(|a| a.borrow_mut().remove(&who.into())); } pub struct TestAssetTransactor; impl TransactAsset for TestAssetTransactor { fn deposit_asset( - what: &MultiAsset, - who: &MultiLocation, + what: &Asset, + who: &Location, _context: Option<&XcmContext>, ) -> Result<(), XcmError> { - add_asset(*who, what.clone()); + add_asset(who.clone(), what.clone()); Ok(()) } fn withdraw_asset( - what: &MultiAsset, - who: &MultiLocation, + what: &Asset, + who: &Location, _maybe_context: Option<&XcmContext>, - ) -> Result { + ) -> Result { ASSETS.with(|a| { a.borrow_mut() .get_mut(who) @@ -274,19 +278,20 @@ impl TransactAsset for TestAssetTransactor { } } -pub fn to_account(l: impl Into) -> Result { - Ok(match l.into() { +pub fn to_account(l: impl Into) -> Result { + let l = l.into(); + Ok(match l.unpack() { // Siblings at 2000+id - MultiLocation { parents: 1, interior: X1(Parachain(id)) } => 2000 + id as u64, + (1, [Parachain(id)]) => 2000 + *id as u64, // Accounts are their number - MultiLocation { parents: 0, interior: X1(AccountIndex64 { index, .. }) } => index, + (0, [AccountIndex64 { index, .. }]) => *index, // Children at 1000+id - MultiLocation { parents: 0, interior: X1(Parachain(id)) } => 1000 + id as u64, + (0, [Parachain(id)]) => 1000 + *id as u64, // Self at 3000 - MultiLocation { parents: 0, interior: Here } => 3000, + (0, []) => 3000, // Parent at 3001 - MultiLocation { parents: 1, interior: Here } => 3001, - l => { + (1, []) => 3001, + _ => { // Is it a foreign-consensus? let uni = ExecutorUniversalLocation::get(); if l.parents as usize != uni.len() { @@ -304,36 +309,35 @@ pub fn to_account(l: impl Into) -> Result { pub struct TestOriginConverter; impl ConvertOrigin for TestOriginConverter { fn convert_origin( - origin: impl Into, + origin: impl Into, kind: OriginKind, - ) -> Result { + ) -> Result { use OriginKind::*; - match (kind, origin.into()) { + let origin = origin.into(); + match (kind, origin.unpack()) { (Superuser, _) => Ok(TestOrigin::Root), - (SovereignAccount, l) => Ok(TestOrigin::Signed(to_account(l)?)), - (Native, MultiLocation { parents: 0, interior: X1(Parachain(id)) }) => - Ok(TestOrigin::Parachain(id)), - (Native, MultiLocation { parents: 1, interior: Here }) => Ok(TestOrigin::Relay), - (Native, MultiLocation { parents: 0, interior: X1(AccountIndex64 { index, .. }) }) => - Ok(TestOrigin::Signed(index)), - (_, origin) => Err(origin), + (SovereignAccount, _) => Ok(TestOrigin::Signed(to_account(origin)?)), + (Native, (0, [Parachain(id)])) => Ok(TestOrigin::Parachain(*id)), + (Native, (1, [])) => Ok(TestOrigin::Relay), + (Native, (0, [AccountIndex64 { index, .. }])) => Ok(TestOrigin::Signed(*index)), + _ => Err(origin), } } } thread_local! { - pub static IS_RESERVE: RefCell>> = RefCell::new(BTreeMap::new()); - pub static IS_TELEPORTER: RefCell>> = RefCell::new(BTreeMap::new()); - pub static UNIVERSAL_ALIASES: RefCell> = RefCell::new(BTreeSet::new()); + pub static IS_RESERVE: RefCell>> = RefCell::new(BTreeMap::new()); + pub static IS_TELEPORTER: RefCell>> = RefCell::new(BTreeMap::new()); + pub static UNIVERSAL_ALIASES: RefCell> = RefCell::new(BTreeSet::new()); } -pub fn add_reserve(from: MultiLocation, asset: MultiAssetFilter) { +pub fn add_reserve(from: Location, asset: AssetFilter) { IS_RESERVE.with(|r| r.borrow_mut().entry(from).or_default().push(asset)); } #[allow(dead_code)] -pub fn add_teleporter(from: MultiLocation, asset: MultiAssetFilter) { +pub fn add_teleporter(from: Location, asset: AssetFilter) { IS_TELEPORTER.with(|r| r.borrow_mut().entry(from).or_default().push(asset)); } -pub fn add_universal_alias(bridge: impl Into, consensus: impl Into) { +pub fn add_universal_alias(bridge: impl Into, consensus: impl Into) { UNIVERSAL_ALIASES.with(|r| r.borrow_mut().insert((bridge.into(), consensus.into()))); } pub fn clear_universal_aliases() { @@ -341,29 +345,29 @@ pub fn clear_universal_aliases() { } pub struct TestIsReserve; -impl ContainsPair for TestIsReserve { - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool { +impl ContainsPair for TestIsReserve { + fn contains(asset: &Asset, origin: &Location) -> bool { IS_RESERVE .with(|r| r.borrow().get(origin).map_or(false, |v| v.iter().any(|a| a.matches(asset)))) } } pub struct TestIsTeleporter; -impl ContainsPair for TestIsTeleporter { - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool { +impl ContainsPair for TestIsTeleporter { + fn contains(asset: &Asset, origin: &Location) -> bool { IS_TELEPORTER .with(|r| r.borrow().get(origin).map_or(false, |v| v.iter().any(|a| a.matches(asset)))) } } pub struct TestUniversalAliases; -impl Contains<(MultiLocation, Junction)> for TestUniversalAliases { - fn contains(t: &(MultiLocation, Junction)) -> bool { +impl Contains<(Location, Junction)> for TestUniversalAliases { + fn contains(t: &(Location, Junction)) -> bool { UNIVERSAL_ALIASES.with(|r| r.borrow().contains(t)) } } pub enum ResponseSlot { - Expecting(MultiLocation), + Expecting(Location), Received(Response), } thread_local! { @@ -371,20 +375,16 @@ thread_local! { } pub struct TestResponseHandler; impl OnResponse for TestResponseHandler { - fn expecting_response( - origin: &MultiLocation, - query_id: u64, - _querier: Option<&MultiLocation>, - ) -> bool { + fn expecting_response(origin: &Location, query_id: u64, _querier: Option<&Location>) -> bool { QUERIES.with(|q| match q.borrow().get(&query_id) { Some(ResponseSlot::Expecting(ref l)) => l == origin, _ => false, }) } fn on_response( - _origin: &MultiLocation, + _origin: &Location, query_id: u64, - _querier: Option<&MultiLocation>, + _querier: Option<&Location>, response: xcm::latest::Response, _max_weight: Weight, _context: &XcmContext, @@ -399,7 +399,7 @@ impl OnResponse for TestResponseHandler { Weight::from_parts(10, 10) } } -pub fn expect_response(query_id: u64, from: MultiLocation) { +pub fn expect_response(query_id: u64, from: Location) { QUERIES.with(|q| q.borrow_mut().insert(query_id, ResponseSlot::Expecting(from))); } pub fn response(query_id: u64) -> Option { @@ -423,9 +423,9 @@ impl QueryHandler type UniversalLocation = T::UniversalLocation; fn new_query( - responder: impl Into, + responder: impl Into, _timeout: Self::BlockNumber, - _match_querier: impl Into, + _match_querier: impl Into, ) -> Self::QueryId { let query_id = 1; expect_response(query_id, responder.into()); @@ -434,7 +434,7 @@ impl QueryHandler fn report_outcome( message: &mut Xcm<()>, - responder: impl Into, + responder: impl Into, timeout: Self::BlockNumber, ) -> Result { let responder = responder.into(); @@ -469,16 +469,16 @@ impl QueryHandler } parameter_types! { - pub static ExecutorUniversalLocation: InteriorMultiLocation + pub static ExecutorUniversalLocation: InteriorLocation = (ByGenesis([0; 32]), Parachain(42)).into(); pub UnitWeightCost: Weight = Weight::from_parts(10, 10); } parameter_types! { // Nothing is allowed to be paid/unpaid by default. - pub static AllowExplicitUnpaidFrom: Vec = vec![]; - pub static AllowUnpaidFrom: Vec = vec![]; - pub static AllowPaidFrom: Vec = vec![]; - pub static AllowSubsFrom: Vec = vec![]; + pub static AllowExplicitUnpaidFrom: Vec = vec![]; + pub static AllowUnpaidFrom: Vec = vec![]; + pub static AllowPaidFrom: Vec = vec![]; + pub static AllowSubsFrom: Vec = vec![]; // 1_000_000_000_000 => 1 unit of asset for 1 unit of ref time weight. // 1024 * 1024 => 1 unit of asset for 1 unit of proof size weight. pub static WeightPrice: (AssetId, u128, u128) = @@ -489,7 +489,7 @@ parameter_types! { pub struct TestSuspender; impl CheckSuspension for TestSuspender { fn is_suspended( - _origin: &MultiLocation, + _origin: &Location, _instructions: &mut [Instruction], _max_weight: Weight, _properties: &mut Properties, @@ -523,34 +523,34 @@ pub fn set_fee_waiver(waived: Vec) { pub struct TestFeeManager; impl FeeManager for TestFeeManager { - fn is_waived(_: Option<&MultiLocation>, r: FeeReason) -> bool { + fn is_waived(_: Option<&Location>, r: FeeReason) -> bool { IS_WAIVED.with(|l| l.borrow().contains(&r)) } - fn handle_fee(_: MultiAssets, _: Option<&XcmContext>, _: FeeReason) {} + fn handle_fee(_: Assets, _: Option<&XcmContext>, _: FeeReason) {} } #[derive(Clone, Eq, PartialEq, Debug)] pub enum LockTraceItem { - Lock { unlocker: MultiLocation, asset: MultiAsset, owner: MultiLocation }, - Unlock { unlocker: MultiLocation, asset: MultiAsset, owner: MultiLocation }, - Note { locker: MultiLocation, asset: MultiAsset, owner: MultiLocation }, - Reduce { locker: MultiLocation, asset: MultiAsset, owner: MultiLocation }, + Lock { unlocker: Location, asset: Asset, owner: Location }, + Unlock { unlocker: Location, asset: Asset, owner: Location }, + Note { locker: Location, asset: Asset, owner: Location }, + Reduce { locker: Location, asset: Asset, owner: Location }, } thread_local! { pub static NEXT_INDEX: RefCell = RefCell::new(0); pub static LOCK_TRACE: RefCell> = RefCell::new(Vec::new()); - pub static ALLOWED_UNLOCKS: RefCell> = RefCell::new(BTreeMap::new()); - pub static ALLOWED_REQUEST_UNLOCKS: RefCell> = RefCell::new(BTreeMap::new()); + pub static ALLOWED_UNLOCKS: RefCell> = RefCell::new(BTreeMap::new()); + pub static ALLOWED_REQUEST_UNLOCKS: RefCell> = RefCell::new(BTreeMap::new()); } pub fn take_lock_trace() -> Vec { LOCK_TRACE.with(|l| l.replace(Vec::new())) } pub fn allow_unlock( - unlocker: impl Into, - asset: impl Into, - owner: impl Into, + unlocker: impl Into, + asset: impl Into, + owner: impl Into, ) { ALLOWED_UNLOCKS.with(|l| { l.borrow_mut() @@ -560,9 +560,9 @@ pub fn allow_unlock( }); } pub fn disallow_unlock( - unlocker: impl Into, - asset: impl Into, - owner: impl Into, + unlocker: impl Into, + asset: impl Into, + owner: impl Into, ) { ALLOWED_UNLOCKS.with(|l| { l.borrow_mut() @@ -571,17 +571,17 @@ pub fn disallow_unlock( .saturating_take(asset.into().into()) }); } -pub fn unlock_allowed(unlocker: &MultiLocation, asset: &MultiAsset, owner: &MultiLocation) -> bool { +pub fn unlock_allowed(unlocker: &Location, asset: &Asset, owner: &Location) -> bool { ALLOWED_UNLOCKS.with(|l| { l.borrow_mut() - .get(&(*owner, *unlocker)) + .get(&(owner.clone(), unlocker.clone())) .map_or(false, |x| x.contains_asset(asset)) }) } pub fn allow_request_unlock( - locker: impl Into, - asset: impl Into, - owner: impl Into, + locker: impl Into, + asset: impl Into, + owner: impl Into, ) { ALLOWED_REQUEST_UNLOCKS.with(|l| { l.borrow_mut() @@ -591,9 +591,9 @@ pub fn allow_request_unlock( }); } pub fn disallow_request_unlock( - locker: impl Into, - asset: impl Into, - owner: impl Into, + locker: impl Into, + asset: impl Into, + owner: impl Into, ) { ALLOWED_REQUEST_UNLOCKS.with(|l| { l.borrow_mut() @@ -602,14 +602,10 @@ pub fn disallow_request_unlock( .saturating_take(asset.into().into()) }); } -pub fn request_unlock_allowed( - locker: &MultiLocation, - asset: &MultiAsset, - owner: &MultiLocation, -) -> bool { +pub fn request_unlock_allowed(locker: &Location, asset: &Asset, owner: &Location) -> bool { ALLOWED_REQUEST_UNLOCKS.with(|l| { l.borrow_mut() - .get(&(*owner, *locker)) + .get(&(owner.clone(), locker.clone())) .map_or(false, |x| x.contains_asset(asset)) }) } @@ -619,11 +615,11 @@ impl Enact for TestTicket { fn enact(self) -> Result<(), LockError> { match &self.0 { LockTraceItem::Lock { unlocker, asset, owner } => - allow_unlock(*unlocker, asset.clone(), *owner), + allow_unlock(unlocker.clone(), asset.clone(), owner.clone()), LockTraceItem::Unlock { unlocker, asset, owner } => - disallow_unlock(*unlocker, asset.clone(), *owner), + disallow_unlock(unlocker.clone(), asset.clone(), owner.clone()), LockTraceItem::Reduce { locker, asset, owner } => - disallow_request_unlock(*locker, asset.clone(), *owner), + disallow_request_unlock(locker.clone(), asset.clone(), owner.clone()), _ => {}, } LOCK_TRACE.with(move |l| l.borrow_mut().push(self.0)); @@ -638,38 +634,34 @@ impl AssetLock for TestAssetLock { type ReduceTicket = TestTicket; fn prepare_lock( - unlocker: MultiLocation, - asset: MultiAsset, - owner: MultiLocation, + unlocker: Location, + asset: Asset, + owner: Location, ) -> Result { - ensure!(assets(owner).contains_asset(&asset), LockError::AssetNotOwned); + ensure!(assets(owner.clone()).contains_asset(&asset), LockError::AssetNotOwned); Ok(TestTicket(LockTraceItem::Lock { unlocker, asset, owner })) } fn prepare_unlock( - unlocker: MultiLocation, - asset: MultiAsset, - owner: MultiLocation, + unlocker: Location, + asset: Asset, + owner: Location, ) -> Result { ensure!(unlock_allowed(&unlocker, &asset, &owner), LockError::NotLocked); Ok(TestTicket(LockTraceItem::Unlock { unlocker, asset, owner })) } - fn note_unlockable( - locker: MultiLocation, - asset: MultiAsset, - owner: MultiLocation, - ) -> Result<(), LockError> { - allow_request_unlock(locker, asset.clone(), owner); + fn note_unlockable(locker: Location, asset: Asset, owner: Location) -> Result<(), LockError> { + allow_request_unlock(locker.clone(), asset.clone(), owner.clone()); let item = LockTraceItem::Note { locker, asset, owner }; LOCK_TRACE.with(move |l| l.borrow_mut().push(item)); Ok(()) } fn prepare_reduce_unlockable( - locker: MultiLocation, - asset: MultiAsset, - owner: MultiLocation, + locker: Location, + asset: Asset, + owner: Location, ) -> Result { ensure!(request_unlock_allowed(&locker, &asset, &owner), LockError::NotLocked); Ok(TestTicket(LockTraceItem::Reduce { locker, asset, owner })) @@ -677,26 +669,26 @@ impl AssetLock for TestAssetLock { } thread_local! { - pub static EXCHANGE_ASSETS: RefCell = RefCell::new(Assets::new()); + pub static EXCHANGE_ASSETS: RefCell = RefCell::new(AssetsInHolding::new()); } -pub fn set_exchange_assets(assets: impl Into) { +pub fn set_exchange_assets(assets: impl Into) { EXCHANGE_ASSETS.with(|a| a.replace(assets.into().into())); } -pub fn exchange_assets() -> MultiAssets { +pub fn exchange_assets() -> Assets { EXCHANGE_ASSETS.with(|a| a.borrow().clone().into()) } pub struct TestAssetExchange; impl AssetExchange for TestAssetExchange { fn exchange_asset( - _origin: Option<&MultiLocation>, - give: Assets, - want: &MultiAssets, + _origin: Option<&Location>, + give: AssetsInHolding, + want: &Assets, maximal: bool, - ) -> Result { + ) -> Result { let mut have = EXCHANGE_ASSETS.with(|l| l.borrow().clone()); ensure!(have.contains_assets(want), give); let get = if maximal { - std::mem::replace(&mut have, Assets::new()) + std::mem::replace(&mut have, AssetsInHolding::new()) } else { have.saturating_take(want.clone().into()) }; @@ -706,16 +698,25 @@ impl AssetExchange for TestAssetExchange { } } -match_types! { - pub type SiblingPrefix: impl Contains = { - MultiLocation { parents: 1, interior: X1(Parachain(_)) } - }; - pub type ChildPrefix: impl Contains = { - MultiLocation { parents: 0, interior: X1(Parachain(_)) } - }; - pub type ParentPrefix: impl Contains = { - MultiLocation { parents: 1, interior: Here } - }; +pub struct SiblingPrefix; +impl Contains for SiblingPrefix { + fn contains(loc: &Location) -> bool { + matches!(loc.unpack(), (1, [Parachain(_)])) + } +} + +pub struct ChildPrefix; +impl Contains for ChildPrefix { + fn contains(loc: &Location) -> bool { + matches!(loc.unpack(), (0, [Parachain(_)])) + } +} + +pub struct ParentPrefix; +impl Contains for ParentPrefix { + fn contains(loc: &Location) -> bool { + matches!(loc.unpack(), (1, [])) + } } pub struct TestConfig; @@ -746,7 +747,7 @@ impl Config for TestConfig { type Aliasers = AliasForeignAccountId32; } -pub fn fungible_multi_asset(location: MultiLocation, amount: u128) -> MultiAsset { +pub fn fungible_multi_asset(location: Location, amount: u128) -> Asset { (AssetId::from(location), Fungibility::Fungible(amount)).into() } diff --git a/polkadot/xcm/xcm-builder/src/tests/origins.rs b/polkadot/xcm/xcm-builder/src/tests/origins.rs index d3d6278eff8e..4d05afd80db8 100644 --- a/polkadot/xcm/xcm-builder/src/tests/origins.rs +++ b/polkadot/xcm/xcm-builder/src/tests/origins.rs @@ -18,7 +18,7 @@ use super::*; #[test] fn universal_origin_should_work() { - AllowUnpaidFrom::set(vec![X1(Parachain(1)).into(), X1(Parachain(2)).into()]); + AllowUnpaidFrom::set(vec![[Parachain(1)].into(), [Parachain(2)].into()]); clear_universal_aliases(); // Parachain 1 may represent Kusama to us add_universal_alias(Parachain(1), Kusama); @@ -29,48 +29,51 @@ fn universal_origin_should_work() { UniversalOrigin(GlobalConsensus(Kusama)), TransferAsset { assets: (Parent, 100u128).into(), beneficiary: Here.into() }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(2), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::InvalidLocation)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::InvalidLocation }); let message = Xcm(vec![ UniversalOrigin(GlobalConsensus(Kusama)), TransferAsset { assets: (Parent, 100u128).into(), beneficiary: Here.into() }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(20, 20), XcmError::NotWithdrawable)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(20, 20), error: XcmError::NotWithdrawable }); add_asset((Ancestor(2), GlobalConsensus(Kusama)), (Parent, 100)); let message = Xcm(vec![ UniversalOrigin(GlobalConsensus(Kusama)), TransferAsset { assets: (Parent, 100u128).into(), beneficiary: Here.into() }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(20, 20))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(20, 20) }); assert_eq!(asset_list((Ancestor(2), GlobalConsensus(Kusama))), vec![]); } #[test] fn export_message_should_work() { // Bridge chain (assumed to be Relay) lets Parachain #1 have message execution for free. - AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); + AllowUnpaidFrom::set(vec![[Parachain(1)].into()]); // Local parachain #1 issues a transfer asset on Polkadot Relay-chain, transfering 100 Planck to // Polkadot parachain #2. let expected_message = Xcm(vec![TransferAsset { @@ -83,14 +86,15 @@ fn export_message_should_work() { destination: Here, xcm: expected_message.clone(), }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); let uni_src = (ByGenesis([0; 32]), Parachain(42), Parachain(1)).into(); assert_eq!( exported_xcm(), @@ -101,40 +105,43 @@ fn export_message_should_work() { #[test] fn unpaid_execution_should_work() { // Bridge chain (assumed to be Relay) lets Parachain #1 have message execution for free. - AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); + AllowUnpaidFrom::set(vec![[Parachain(1)].into()]); // Bridge chain (assumed to be Relay) lets Parachain #2 have message execution for free if it // asks. - AllowExplicitUnpaidFrom::set(vec![X1(Parachain(2)).into()]); + AllowExplicitUnpaidFrom::set(vec![[Parachain(2)].into()]); // Asking for unpaid execution of up to 9 weight on the assumption it is origin of #2. let message = Xcm(vec![UnpaidExecution { weight_limit: Limited(Weight::from_parts(9, 9)), check_origin: Some(Parachain(2).into()), }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message.clone(), - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::BadOrigin)); - let r = XcmExecutor::::execute_xcm( + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::BadOrigin }); + let r = XcmExecutor::::prepare_and_execute( Parachain(2), message.clone(), - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Error(XcmError::Barrier)); + assert_eq!(r, Outcome::Error { error: XcmError::Barrier }); let message = Xcm(vec![UnpaidExecution { weight_limit: Limited(Weight::from_parts(10, 10)), check_origin: Some(Parachain(2).into()), }]); - let r = XcmExecutor::::execute_xcm( + let r = XcmExecutor::::prepare_and_execute( Parachain(2), message.clone(), - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); } diff --git a/polkadot/xcm/xcm-builder/src/tests/pay/mock.rs b/polkadot/xcm/xcm-builder/src/tests/pay/mock.rs index 78b9284c689f..01ff8c29f3da 100644 --- a/polkadot/xcm/xcm-builder/src/tests/pay/mock.rs +++ b/polkadot/xcm/xcm-builder/src/tests/pay/mock.rs @@ -115,14 +115,14 @@ impl pallet_assets::Config for Test { } parameter_types! { - pub const RelayLocation: MultiLocation = Here.into_location(); + pub const RelayLocation: Location = Here.into_location(); pub const AnyNetwork: Option = None; - pub UniversalLocation: InteriorMultiLocation = (ByGenesis([0; 32]), Parachain(42)).into(); + pub UniversalLocation: InteriorLocation = (ByGenesis([0; 32]), Parachain(42)).into(); pub UnitWeightCost: u64 = 1_000; pub static AdvertisedXcmVersion: u32 = 3; pub const BaseXcmWeight: Weight = Weight::from_parts(1_000, 1_000); - pub CurrencyPerSecondPerByte: (AssetId, u128, u128) = (Concrete(RelayLocation::get()), 1, 1); - pub TrustedAssets: (MultiAssetFilter, MultiLocation) = (All.into(), Here.into()); + pub CurrencyPerSecondPerByte: (AssetId, u128, u128) = (AssetId(RelayLocation::get()), 1, 1); + pub TrustedAssets: (AssetFilter, Location) = (All.into(), Here.into()); pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 64; pub CheckingAccount: AccountId = XcmPallet::check_account(); @@ -130,28 +130,25 @@ parameter_types! { type AssetIdForAssets = u128; -pub struct FromMultiLocationToAsset( - core::marker::PhantomData<(MultiLocation, AssetId)>, -); -impl MaybeEquivalence - for FromMultiLocationToAsset +pub struct FromLocationToAsset(core::marker::PhantomData<(Location, AssetId)>); +impl MaybeEquivalence + for FromLocationToAsset { - fn convert(value: &MultiLocation) -> Option { - match value { - MultiLocation { parents: 0, interior: Here } => Some(0 as AssetIdForAssets), - MultiLocation { parents: 1, interior: Here } => Some(1 as AssetIdForAssets), - MultiLocation { parents: 0, interior: X2(PalletInstance(1), GeneralIndex(index)) } - if ![0, 1].contains(index) => + fn convert(value: &Location) -> Option { + match value.unpack() { + (0, []) => Some(0 as AssetIdForAssets), + (1, []) => Some(1 as AssetIdForAssets), + (0, [PalletInstance(1), GeneralIndex(index)]) if ![0, 1].contains(index) => Some(*index as AssetIdForAssets), _ => None, } } - fn convert_back(value: &AssetIdForAssets) -> Option { + fn convert_back(value: &AssetIdForAssets) -> Option { match value { - 0u128 => Some(MultiLocation { parents: 1, interior: Here }), + 0u128 => Some(Location { parents: 1, interior: Here }), para_id @ 1..=1000 => - Some(MultiLocation { parents: 1, interior: X1(Parachain(*para_id as u32)) }), + Some(Location { parents: 1, interior: [Parachain(*para_id as u32)].into() }), _ => None, } } @@ -163,7 +160,7 @@ pub type LocalAssetsTransactor = FungiblesAdapter< ConvertedConcreteId< AssetIdForAssets, Balance, - FromMultiLocationToAsset, + FromLocationToAsset, JustTry, >, SovereignAccountOf, @@ -187,10 +184,10 @@ impl WeightTrader for DummyWeightTrader { fn buy_weight( &mut self, _weight: Weight, - _payment: xcm_executor::Assets, + _payment: xcm_executor::AssetsInHolding, _context: &XcmContext, - ) -> Result { - Ok(xcm_executor::Assets::default()) + ) -> Result { + Ok(xcm_executor::AssetsInHolding::default()) } } @@ -228,13 +225,10 @@ parameter_types! { pub struct TreasuryToAccount; impl ConvertLocation for TreasuryToAccount { - fn convert_location(location: &MultiLocation) -> Option { - match location { - MultiLocation { - parents: 1, - interior: - X2(Parachain(42), Plurality { id: BodyId::Treasury, part: BodyPart::Voice }), - } => Some(TreasuryAccountId::get()), // Hardcoded test treasury account id + fn convert_location(location: &Location) -> Option { + match location.unpack() { + (1, [Parachain(42), Plurality { id: BodyId::Treasury, part: BodyPart::Voice }]) => + Some(TreasuryAccountId::get()), // Hardcoded test treasury account id _ => None, } } @@ -277,7 +271,7 @@ pub const INITIAL_BALANCE: Balance = 100 * UNITS; pub const MINIMUM_BALANCE: Balance = 1 * UNITS; pub fn sibling_chain_account_id(para_id: u32, account: [u8; 32]) -> AccountId { - let location: MultiLocation = + let location: Location = (Parent, Parachain(para_id), Junction::AccountId32 { id: account, network: None }).into(); SovereignAccountOf::convert_location(&location).unwrap() } diff --git a/polkadot/xcm/xcm-builder/src/tests/pay/pay.rs b/polkadot/xcm/xcm-builder/src/tests/pay/pay.rs index 178b93842736..668ae8f1f30b 100644 --- a/polkadot/xcm/xcm-builder/src/tests/pay/pay.rs +++ b/polkadot/xcm/xcm-builder/src/tests/pay/pay.rs @@ -22,9 +22,9 @@ use frame_support::{assert_ok, traits::tokens::Pay}; /// Type representing both a location and an asset that is held at that location. /// The id of the held asset is relative to the location where it is being held. -#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq)] +#[derive(Encode, Decode, Clone, PartialEq, Eq)] pub struct AssetKind { - destination: MultiLocation, + destination: Location, asset_id: AssetId, } @@ -37,8 +37,8 @@ impl sp_runtime::traits::TryConvert for LocatableAs parameter_types! { pub SenderAccount: AccountId = AccountId::new([3u8; 32]); - pub InteriorAccount: InteriorMultiLocation = AccountId32 { id: SenderAccount::get().into(), network: None }.into(); - pub InteriorBody: InteriorMultiLocation = Plurality { id: BodyId::Treasury, part: BodyPart::Voice }.into(); + pub InteriorAccount: InteriorLocation = AccountId32 { id: SenderAccount::get().into(), network: None }.into(); + pub InteriorBody: InteriorLocation = Plurality { id: BodyId::Treasury, part: BodyPart::Voice }.into(); pub Timeout: BlockNumber = 5; // 5 blocks } @@ -91,13 +91,13 @@ fn pay_over_xcm_works() { vec![((Parent, Parachain(2)).into(), expected_message, expected_hash)] ); - let (_, message, hash) = sent_xcm()[0].clone(); + let (_, message, mut hash) = sent_xcm()[0].clone(); let message = Xcm::<::RuntimeCall>::from(message.clone()); // Execute message in parachain 2 with parachain 42's origin let origin = (Parent, Parachain(42)); - XcmExecutor::::execute_xcm(origin, message, hash, Weight::MAX); + XcmExecutor::::prepare_and_execute(origin, message, &mut hash, Weight::MAX, Weight::zero()); assert_eq!(mock::Assets::balance(0, &recipient), amount); }); } @@ -152,13 +152,13 @@ fn pay_over_xcm_governance_body() { vec![((Parent, Parachain(2)).into(), expected_message, expected_hash)] ); - let (_, message, hash) = sent_xcm()[0].clone(); + let (_, message, mut hash) = sent_xcm()[0].clone(); let message = Xcm::<::RuntimeCall>::from(message.clone()); // Execute message in parachain 2 with parachain 42's origin let origin = (Parent, Parachain(42)); - XcmExecutor::::execute_xcm(origin, message, hash, Weight::MAX); + XcmExecutor::::prepare_and_execute(origin, message, &mut hash, Weight::MAX, Weight::zero()); assert_eq!(mock::Assets::balance(relay_asset_index, &recipient), amount); }); } diff --git a/polkadot/xcm/xcm-builder/src/tests/pay/salary.rs b/polkadot/xcm/xcm-builder/src/tests/pay/salary.rs index e490fe326b37..70854866dc4a 100644 --- a/polkadot/xcm/xcm-builder/src/tests/pay/salary.rs +++ b/polkadot/xcm/xcm-builder/src/tests/pay/salary.rs @@ -25,9 +25,9 @@ use frame_support::{ use sp_runtime::{traits::ConvertToValue, DispatchResult}; parameter_types! { - pub Interior: InteriorMultiLocation = Plurality { id: BodyId::Treasury, part: BodyPart::Voice }.into(); + pub Interior: InteriorLocation = Plurality { id: BodyId::Treasury, part: BodyPart::Voice }.into(); pub Timeout: BlockNumber = 5; - pub AssetHub: MultiLocation = (Parent, Parachain(1)).into(); + pub AssetHub: Location = (Parent, Parachain(1)).into(); pub AssetIdGeneralIndex: u128 = 100; pub AssetHubAssetId: AssetId = (PalletInstance(1), GeneralIndex(AssetIdGeneralIndex::get())).into(); pub LocatableAsset: LocatableAssetId = LocatableAssetId { asset_id: AssetHubAssetId::get(), location: AssetHub::get() }; @@ -140,7 +140,7 @@ fn salary_pay_over_xcm_works() { assert_ok!(Salary::payout(RuntimeOrigin::signed(recipient.clone()))); // Get message from mock transport layer - let (_, message, hash) = sent_xcm()[0].clone(); + let (_, message, mut hash) = sent_xcm()[0].clone(); // Change type from `Xcm<()>` to `Xcm` to be able to execute later let message = Xcm::<::RuntimeCall>::from(message.clone()); @@ -164,7 +164,7 @@ fn salary_pay_over_xcm_works() { assert_eq!(message, expected_message); // Execute message as the asset hub - XcmExecutor::::execute_xcm((Parent, Parachain(42)), message, hash, Weight::MAX); + XcmExecutor::::prepare_and_execute((Parent, Parachain(42)), message, &mut hash, Weight::MAX, Weight::zero()); // Recipient receives the payment assert_eq!( diff --git a/polkadot/xcm/xcm-builder/src/tests/querying.rs b/polkadot/xcm/xcm-builder/src/tests/querying.rs index 8fbb55eb2542..28567c6e25c9 100644 --- a/polkadot/xcm/xcm-builder/src/tests/querying.rs +++ b/polkadot/xcm/xcm-builder/src/tests/querying.rs @@ -18,7 +18,7 @@ use super::*; #[test] fn pallet_query_should_work() { - AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); + AllowUnpaidFrom::set(vec![[Parachain(1)].into()]); // They want to transfer 100 of our native asset from sovereign account of parachain #1 into #2 // and let them know to hand it to account #3. let message = Xcm(vec![QueryPallet { @@ -29,14 +29,15 @@ fn pallet_query_should_work() { max_weight: Weight::from_parts(50, 50), }, }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); let expected_msg = Xcm::<()>(vec![QueryResponse { query_id: 1, @@ -50,7 +51,7 @@ fn pallet_query_should_work() { #[test] fn pallet_query_with_results_should_work() { - AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); + AllowUnpaidFrom::set(vec![[Parachain(1)].into()]); // They want to transfer 100 of our native asset from sovereign account of parachain #1 into #2 // and let them know to hand it to account #3. let message = Xcm(vec![QueryPallet { @@ -61,14 +62,15 @@ fn pallet_query_with_results_should_work() { max_weight: Weight::from_parts(50, 50), }, }]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( Parachain(1), message, - hash, + &mut hash, Weight::from_parts(50, 50), + Weight::zero(), ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); let expected_msg = Xcm::<()>(vec![QueryResponse { query_id: 1, @@ -106,15 +108,15 @@ fn prepaid_result_of_query_should_get_free_execution() { max_weight: Weight::from_parts(10, 10), querier: Some(Here.into()), }]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(10, 10); // First time the response gets through since we're expecting it... - let r = XcmExecutor::::execute_xcm(Parent, message.clone(), hash, weight_limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + let r = XcmExecutor::::prepare_and_execute(Parent, message.clone(), &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); assert_eq!(response(query_id).unwrap(), the_response); // Second time it doesn't, since we're not. - let r = XcmExecutor::::execute_xcm(Parent, message.clone(), hash, weight_limit); - assert_eq!(r, Outcome::Error(XcmError::Barrier)); + let r = XcmExecutor::::prepare_and_execute(Parent, message.clone(), &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Error { error: XcmError::Barrier }); } diff --git a/polkadot/xcm/xcm-builder/src/tests/transacting.rs b/polkadot/xcm/xcm-builder/src/tests/transacting.rs index 743ad7039f7f..b637ff62fdfe 100644 --- a/polkadot/xcm/xcm-builder/src/tests/transacting.rs +++ b/polkadot/xcm/xcm-builder/src/tests/transacting.rs @@ -25,10 +25,10 @@ fn transacting_should_work() { require_weight_at_most: Weight::from_parts(50, 50), call: TestCall::Any(Weight::from_parts(50, 50), None).encode().into(), }]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(60, 60); - let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(60, 60))); + let r = XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(60, 60) }); } #[test] @@ -40,10 +40,10 @@ fn transacting_should_respect_max_weight_requirement() { require_weight_at_most: Weight::from_parts(40, 40), call: TestCall::Any(Weight::from_parts(50, 50), None).encode().into(), }]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(60, 60); - let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(50, 50), XcmError::MaxWeightInvalid)); + let r = XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(50, 50), error: XcmError::MaxWeightInvalid }); } #[test] @@ -57,20 +57,20 @@ fn transacting_should_refund_weight() { .encode() .into(), }]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(60, 60); - let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(40, 40))); + let r = XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(40, 40) }); } #[test] fn paid_transacting_should_refund_payment_for_unused_weight() { - let one: MultiLocation = AccountIndex64 { index: 1, network: None }.into(); - AllowPaidFrom::set(vec![one]); + let one: Location = AccountIndex64 { index: 1, network: None }.into(); + AllowPaidFrom::set(vec![one.clone()]); add_asset(AccountIndex64 { index: 1, network: None }, (Parent, 200u128)); WeightPrice::set((Parent.into(), 1_000_000_000_000, 1024 * 1024)); - let origin = one; + let origin = one.clone(); let fees = (Parent, 200u128).into(); let message = Xcm::(vec![ WithdrawAsset((Parent, 200u128).into()), // enough for 200 units of weight. @@ -86,10 +86,10 @@ fn paid_transacting_should_refund_payment_for_unused_weight() { RefundSurplus, DepositAsset { assets: AllCounted(1).into(), beneficiary: one }, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(100, 100); - let r = XcmExecutor::::execute_xcm(origin, message, hash, weight_limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(60, 60))); + let r = XcmExecutor::::prepare_and_execute(origin, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(60, 60) }); assert_eq!( asset_list(AccountIndex64 { index: 1, network: None }), vec![(Parent, 80u128).into()] @@ -112,10 +112,10 @@ fn report_successful_transact_status_should_work() { max_weight: Weight::from_parts(5000, 5000), }), ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(70, 70); - let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(70, 70))); + let r = XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(70, 70) }); let expected_msg = Xcm(vec![QueryResponse { response: Response::DispatchResult(MaybeErrorCode::Success), query_id: 42, @@ -142,10 +142,10 @@ fn report_failed_transact_status_should_work() { max_weight: Weight::from_parts(5000, 5000), }), ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(70, 70); - let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(70, 70))); + let r = XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(70, 70) }); let expected_msg = Xcm(vec![QueryResponse { response: Response::DispatchResult(vec![2].into()), query_id: 42, @@ -168,10 +168,10 @@ fn expect_successful_transact_status_should_work() { }, ExpectTransactStatus(MaybeErrorCode::Success), ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(70, 70); - let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(70, 70))); + let r = XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(70, 70) }); let message = Xcm::(vec![ Transact { @@ -181,10 +181,10 @@ fn expect_successful_transact_status_should_work() { }, ExpectTransactStatus(MaybeErrorCode::Success), ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(70, 70); - let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(70, 70), XcmError::ExpectationFalse)); + let r = XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(70, 70), error: XcmError::ExpectationFalse }); } #[test] @@ -199,10 +199,10 @@ fn expect_failed_transact_status_should_work() { }, ExpectTransactStatus(vec![2].into()), ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(70, 70); - let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(70, 70))); + let r = XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(70, 70) }); let message = Xcm::(vec![ Transact { @@ -212,10 +212,10 @@ fn expect_failed_transact_status_should_work() { }, ExpectTransactStatus(vec![2].into()), ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(70, 70); - let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(70, 70), XcmError::ExpectationFalse)); + let r = XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(70, 70), error: XcmError::ExpectationFalse }); } #[test] @@ -235,10 +235,10 @@ fn clear_transact_status_should_work() { max_weight: Weight::from_parts(5000, 5000), }), ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(80, 80); - let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(80, 80))); + let r = XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(80, 80) }); let expected_msg = Xcm(vec![QueryResponse { response: Response::DispatchResult(MaybeErrorCode::Success), query_id: 42, diff --git a/polkadot/xcm/xcm-builder/src/tests/version_subscriptions.rs b/polkadot/xcm/xcm-builder/src/tests/version_subscriptions.rs index 44ab7d34c51b..0def31aac62e 100644 --- a/polkadot/xcm/xcm-builder/src/tests/version_subscriptions.rs +++ b/polkadot/xcm/xcm-builder/src/tests/version_subscriptions.rs @@ -25,23 +25,23 @@ fn simple_version_subscriptions_should_work() { SetAppendix(Xcm(vec![])), SubscribeVersion { query_id: 42, max_response_weight: Weight::from_parts(5000, 5000) }, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(20, 20); - let r = XcmExecutor::::execute_xcm(origin, message, hash, weight_limit); - assert_eq!(r, Outcome::Error(XcmError::Barrier)); + let r = XcmExecutor::::prepare_and_execute(origin, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Error { error: XcmError::Barrier }); let origin = Parachain(1000); let message = Xcm::(vec![SubscribeVersion { query_id: 42, max_response_weight: Weight::from_parts(5000, 5000), }]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(10, 10); - let r = XcmExecutor::::execute_xcm(origin, message.clone(), hash, weight_limit); - assert_eq!(r, Outcome::Error(XcmError::Barrier)); + let r = XcmExecutor::::prepare_and_execute(origin, message.clone(), &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Error { error: XcmError::Barrier }); - let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + let r = XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); assert_eq!( SubscriptionRequests::get(), @@ -53,33 +53,33 @@ fn simple_version_subscriptions_should_work() { fn version_subscription_instruction_should_work() { let origin = Parachain(1000); let message = Xcm::(vec![ - DescendOrigin(X1(AccountIndex64 { index: 1, network: None })), + DescendOrigin([AccountIndex64 { index: 1, network: None }].into()), SubscribeVersion { query_id: 42, max_response_weight: Weight::from_parts(5000, 5000) }, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(20, 20); - let r = XcmExecutor::::execute_xcm_in_credit( + let r = XcmExecutor::::prepare_and_execute( origin, message, - hash, + &mut hash, weight_limit, weight_limit, ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(20, 20), XcmError::BadOrigin)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(20, 20), error: XcmError::BadOrigin }); let message = Xcm::(vec![ SetAppendix(Xcm(vec![])), SubscribeVersion { query_id: 42, max_response_weight: Weight::from_parts(5000, 5000) }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm_in_credit( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( origin, message, - hash, + &mut hash, weight_limit, weight_limit, ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(20, 20))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(20, 20) }); assert_eq!( SubscriptionRequests::get(), @@ -93,20 +93,20 @@ fn simple_version_unsubscriptions_should_work() { let origin = Parachain(1000); let message = Xcm::(vec![SetAppendix(Xcm(vec![])), UnsubscribeVersion]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(20, 20); - let r = XcmExecutor::::execute_xcm(origin, message, hash, weight_limit); - assert_eq!(r, Outcome::Error(XcmError::Barrier)); + let r = XcmExecutor::::prepare_and_execute(origin, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Error { error: XcmError::Barrier }); let origin = Parachain(1000); let message = Xcm::(vec![UnsubscribeVersion]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(10, 10); - let r = XcmExecutor::::execute_xcm(origin, message.clone(), hash, weight_limit); - assert_eq!(r, Outcome::Error(XcmError::Barrier)); + let r = XcmExecutor::::prepare_and_execute(origin, message.clone(), &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Error { error: XcmError::Barrier }); - let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(10, 10))); + let r = XcmExecutor::::prepare_and_execute(Parent, message, &mut hash, weight_limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); assert_eq!(SubscriptionRequests::get(), vec![(Parent.into(), None)]); assert_eq!(sent_xcm(), vec![]); @@ -118,31 +118,31 @@ fn version_unsubscription_instruction_should_work() { // Not allowed to do it when origin has been changed. let message = Xcm::(vec![ - DescendOrigin(X1(AccountIndex64 { index: 1, network: None })), + DescendOrigin([AccountIndex64 { index: 1, network: None }].into()), UnsubscribeVersion, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight_limit = Weight::from_parts(20, 20); - let r = XcmExecutor::::execute_xcm_in_credit( + let r = XcmExecutor::::prepare_and_execute( origin, message, - hash, + &mut hash, weight_limit, weight_limit, ); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(20, 20), XcmError::BadOrigin)); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(20, 20), error: XcmError::BadOrigin }); // Fine to do it when origin is untouched. let message = Xcm::(vec![SetAppendix(Xcm(vec![])), UnsubscribeVersion]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm_in_credit( + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute( origin, message, - hash, + &mut hash, weight_limit, weight_limit, ); - assert_eq!(r, Outcome::Complete(Weight::from_parts(20, 20))); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(20, 20) }); assert_eq!(SubscriptionRequests::get(), vec![(Parachain(1000).into(), None)]); assert_eq!(sent_xcm(), vec![]); diff --git a/polkadot/xcm/xcm-builder/src/tests/weight.rs b/polkadot/xcm/xcm-builder/src/tests/weight.rs index a2fb265413f5..a01494dd0ccb 100644 --- a/polkadot/xcm/xcm-builder/src/tests/weight.rs +++ b/polkadot/xcm/xcm-builder/src/tests/weight.rs @@ -74,45 +74,45 @@ fn errors_should_return_unused_weight() { // First xfer results in an error on the last message only TransferAsset { assets: (Here, 1u128).into(), - beneficiary: X1(AccountIndex64 { index: 3, network: None }).into(), + beneficiary: [AccountIndex64 { index: 3, network: None }].into(), }, // Second xfer results in error third message and after TransferAsset { assets: (Here, 2u128).into(), - beneficiary: X1(AccountIndex64 { index: 3, network: None }).into(), + beneficiary: [AccountIndex64 { index: 3, network: None }].into(), }, // Third xfer results in error second message and after TransferAsset { assets: (Here, 4u128).into(), - beneficiary: X1(AccountIndex64 { index: 3, network: None }).into(), + beneficiary: [AccountIndex64 { index: 3, network: None }].into(), }, ]); // Weight limit of 70 is needed. let limit = ::Weigher::weight(&mut message).unwrap(); assert_eq!(limit, Weight::from_parts(30, 30)); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm(Here, message.clone(), hash, limit); - assert_eq!(r, Outcome::Complete(Weight::from_parts(30, 30))); + let r = XcmExecutor::::prepare_and_execute(Here, message.clone(), &mut hash, limit, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(30, 30) }); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 7u128).into()]); assert_eq!(asset_list(Here), vec![(Here, 4u128).into()]); assert_eq!(sent_xcm(), vec![]); - let r = XcmExecutor::::execute_xcm(Here, message.clone(), hash, limit); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(30, 30), XcmError::NotWithdrawable)); + let r = XcmExecutor::::prepare_and_execute(Here, message.clone(), &mut hash, limit, Weight::zero()); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(30, 30), error: XcmError::NotWithdrawable }); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 10u128).into()]); assert_eq!(asset_list(Here), vec![(Here, 1u128).into()]); assert_eq!(sent_xcm(), vec![]); - let r = XcmExecutor::::execute_xcm(Here, message.clone(), hash, limit); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(20, 20), XcmError::NotWithdrawable)); + let r = XcmExecutor::::prepare_and_execute(Here, message.clone(), &mut hash, limit, Weight::zero()); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(20, 20), error: XcmError::NotWithdrawable }); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 11u128).into()]); assert_eq!(asset_list(Here), vec![]); assert_eq!(sent_xcm(), vec![]); - let r = XcmExecutor::::execute_xcm(Here, message, hash, limit); - assert_eq!(r, Outcome::Incomplete(Weight::from_parts(10, 10), XcmError::NotWithdrawable)); + let r = XcmExecutor::::prepare_and_execute(Here, message, &mut hash, limit, Weight::zero()); + assert_eq!(r, Outcome::Incomplete { used: Weight::from_parts(10, 10), error: XcmError::NotWithdrawable }); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 11u128).into()]); assert_eq!(asset_list(Here), vec![]); assert_eq!(sent_xcm(), vec![]); @@ -148,8 +148,8 @@ fn weight_bounds_should_respect_instructions_limit() { #[test] fn weight_trader_tuple_should_work() { - let para_1: MultiLocation = Parachain(1).into(); - let para_2: MultiLocation = Parachain(2).into(); + let para_1: Location = Parachain(1).into(); + let para_2: Location = Parachain(2).into(); parameter_types! { pub static HereWeightPrice: (AssetId, u128, u128) = @@ -186,7 +186,11 @@ fn weight_trader_tuple_should_work() { let mut traders = Traders::new(); // trader one failed; trader two buys weight assert_eq!( - traders.buy_weight(Weight::from_parts(5, 5), fungible_multi_asset(para_1, 10).into(), &ctx), + traders.buy_weight( + Weight::from_parts(5, 5), + fungible_multi_asset(para_1.clone(), 10).into(), + &ctx + ), Ok(vec![].into()), ); // trader two refunds diff --git a/polkadot/xcm/xcm-builder/src/universal_exports.rs b/polkadot/xcm/xcm-builder/src/universal_exports.rs index dbe9571d461a..8fdc1c83c4ea 100644 --- a/polkadot/xcm/xcm-builder/src/universal_exports.rs +++ b/polkadot/xcm/xcm-builder/src/universal_exports.rs @@ -28,18 +28,18 @@ use SendError::*; /// chain, itself situated at `universal_local` within the consensus universe. If /// `dest` is not a location in remote consensus, then an error is returned. pub fn ensure_is_remote( - universal_local: impl Into, - dest: impl Into, -) -> Result<(NetworkId, InteriorMultiLocation), MultiLocation> { + universal_local: impl Into, + dest: impl Into, +) -> Result<(NetworkId, InteriorLocation), Location> { let dest = dest.into(); let universal_local = universal_local.into(); let local_net = match universal_local.global_consensus() { Ok(x) => x, Err(_) => return Err(dest), }; - let universal_destination: InteriorMultiLocation = universal_local + let universal_destination: InteriorLocation = universal_local .into_location() - .appended_with(dest) + .appended_with(dest.clone()) .map_err(|x| x.1)? .try_into()?; let (remote_dest, remote_net) = match universal_destination.split_first() { @@ -59,18 +59,18 @@ pub fn ensure_is_remote( pub struct UnpaidLocalExporter( PhantomData<(Exporter, UniversalLocation)>, ); -impl> SendXcm +impl> SendXcm for UnpaidLocalExporter { type Ticket = Exporter::Ticket; fn validate( - dest: &mut Option, + dest: &mut Option, xcm: &mut Option>, ) -> SendResult { let d = dest.take().ok_or(MissingArgument)?; let universal_source = UniversalLocation::get(); - let devolved = match ensure_is_remote(universal_source, d) { + let devolved = match ensure_is_remote(universal_source.clone(), d) { Ok(x) => x, Err(d) => { *dest = Some(d); @@ -96,18 +96,18 @@ pub trait ExporterFor { /// the bridge chain as well as payment for the use of the `ExportMessage` instruction. fn exporter_for( network: &NetworkId, - remote_location: &InteriorMultiLocation, + remote_location: &InteriorLocation, message: &Xcm<()>, - ) -> Option<(MultiLocation, Option)>; + ) -> Option<(Location, Option)>; } #[impl_trait_for_tuples::impl_for_tuples(30)] impl ExporterFor for Tuple { fn exporter_for( network: &NetworkId, - remote_location: &InteriorMultiLocation, + remote_location: &InteriorLocation, message: &Xcm<()>, - ) -> Option<(MultiLocation, Option)> { + ) -> Option<(Location, Option)> { for_tuples!( #( if let Some(r) = Tuple::exporter_for(network, remote_location, message) { return Some(r); @@ -125,21 +125,21 @@ pub struct NetworkExportTableItem { /// If `Some`, the requested remote location must be equal to one of the items in the vector. /// These are locations in the remote network. /// If `None`, then the check is skipped. - pub remote_location_filter: Option>, + pub remote_location_filter: Option>, /// Locally-routable bridge with bridging capabilities to the `remote_network` and /// `remote_location`. See [`ExporterFor`] for more details. - pub bridge: MultiLocation, + pub bridge: Location, /// The local payment. /// See [`ExporterFor`] for more details. - pub payment: Option, + pub payment: Option, } impl NetworkExportTableItem { pub fn new( remote_network: NetworkId, - remote_location_filter: Option>, - bridge: MultiLocation, - payment: Option, + remote_location_filter: Option>, + bridge: Location, + payment: Option, ) -> Self { Self { remote_network, remote_location_filter, bridge, payment } } @@ -152,9 +152,9 @@ pub struct NetworkExportTable(sp_std::marker::PhantomData); impl>> ExporterFor for NetworkExportTable { fn exporter_for( network: &NetworkId, - remote_location: &InteriorMultiLocation, + remote_location: &InteriorLocation, _: &Xcm<()>, - ) -> Option<(MultiLocation, Option)> { + ) -> Option<(Location, Option)> { T::get() .into_iter() .find(|item| { @@ -194,16 +194,16 @@ pub fn forward_id_for(original_id: &XcmHash) -> XcmHash { pub struct UnpaidRemoteExporter( PhantomData<(Bridges, Router, UniversalLocation)>, ); -impl> SendXcm +impl> SendXcm for UnpaidRemoteExporter { type Ticket = Router::Ticket; fn validate( - dest: &mut Option, + dest: &mut Option, msg: &mut Option>, ) -> SendResult { - let d = dest.ok_or(MissingArgument)?; + let d = dest.clone().ok_or(MissingArgument)?; let devolved = ensure_is_remote(UniversalLocation::get(), d).map_err(|_| NotApplicable)?; let (remote_network, remote_location) = devolved; let xcm = msg.take().ok_or(MissingArgument)?; @@ -261,17 +261,18 @@ impl( PhantomData<(Bridges, Router, UniversalLocation)>, ); -impl> SendXcm +impl> SendXcm for SovereignPaidRemoteExporter { type Ticket = Router::Ticket; fn validate( - dest: &mut Option, + dest: &mut Option, msg: &mut Option>, ) -> SendResult { - let d = *dest.as_ref().ok_or(MissingArgument)?; - let devolved = ensure_is_remote(UniversalLocation::get(), d).map_err(|_| NotApplicable)?; + let d = dest.as_ref().ok_or(MissingArgument)?; + let devolved = + ensure_is_remote(UniversalLocation::get(), d.clone()).map_err(|_| NotApplicable)?; let (remote_network, remote_location) = devolved; let xcm = msg.take().ok_or(MissingArgument)?; @@ -299,7 +300,7 @@ impl, } @@ -387,8 +388,8 @@ pub struct BridgeBlobDispatcher( ); impl< Router: SendXcm, - OurPlace: Get, - OurPlaceBridgeInstance: Get>, + OurPlace: Get, + OurPlaceBridgeInstance: Get>, > DispatchBlob for BridgeBlobDispatcher { fn dispatch_blob(blob: Vec) -> Result<(), DispatchBlobError> { @@ -397,7 +398,7 @@ impl< our_universal.global_consensus().map_err(|()| DispatchBlobError::Unbridgable)?; let BridgeMessage { universal_dest, message } = Decode::decode(&mut &blob[..]).map_err(|_| DispatchBlobError::InvalidEncoding)?; - let universal_dest: InteriorMultiLocation = universal_dest + let universal_dest: InteriorLocation = universal_dest .try_into() .map_err(|_| DispatchBlobError::UnsupportedLocationVersion)?; // `universal_dest` is the desired destination within the universe: first we need to check @@ -426,7 +427,7 @@ impl< pub struct HaulBlobExporter( PhantomData<(Bridge, BridgedNetwork, Price)>, ); -impl, Price: Get> ExportXcm +impl, Price: Get> ExportXcm for HaulBlobExporter { type Ticket = (Vec, XcmHash); @@ -434,10 +435,10 @@ impl, Price: Get> fn validate( network: NetworkId, _channel: u32, - universal_source: &mut Option, - destination: &mut Option, + universal_source: &mut Option, + destination: &mut Option, message: &mut Option>, - ) -> Result<((Vec, XcmHash), MultiAssets), SendError> { + ) -> Result<((Vec, XcmHash), Assets), SendError> { let bridged_network = BridgedNetwork::get(); ensure!(&network == &bridged_network, SendError::NotApplicable); // We don't/can't use the `channel` for this adapter. @@ -507,10 +508,10 @@ mod tests { type Ticket = (); fn validate( - _destination: &mut Option, + _destination: &mut Option, _message: &mut Option>, ) -> SendResult { - Ok(((), MultiAssets::new())) + Ok(((), Assets::new())) } fn deliver(_ticket: Self::Ticket) -> Result { @@ -521,10 +522,10 @@ mod tests { /// Generic test case asserting that dest and msg is not consumed by `validate` implementation /// of `SendXcm` in case of expected result. fn ensure_validate_does_not_consume_dest_or_msg( - dest: MultiLocation, + dest: Location, assert_result: impl Fn(SendResult), ) { - let mut dest_wrapper = Some(dest); + let mut dest_wrapper = Some(dest.clone()); let msg = Xcm::<()>::new(); let mut msg_wrapper = Some(msg.clone()); @@ -539,19 +540,19 @@ mod tests { fn remote_exporters_does_not_consume_dest_or_msg_on_not_applicable() { frame_support::parameter_types! { pub Local: NetworkId = ByGenesis([0; 32]); - pub UniversalLocation: InteriorMultiLocation = X2(GlobalConsensus(Local::get()), Parachain(1234)); + pub UniversalLocation: InteriorLocation = [GlobalConsensus(Local::get()), Parachain(1234)].into(); pub DifferentRemote: NetworkId = ByGenesis([22; 32]); // no routers pub BridgeTable: Vec = vec![]; } // check with local destination (should be remote) - let local_dest = (Parent, Parachain(5678)).into(); - assert!(ensure_is_remote(UniversalLocation::get(), local_dest).is_err()); + let local_dest: Location = (Parent, Parachain(5678)).into(); + assert!(ensure_is_remote(UniversalLocation::get(), local_dest.clone()).is_err()); ensure_validate_does_not_consume_dest_or_msg::< UnpaidRemoteExporter, OkSender, UniversalLocation>, - >(local_dest, |result| assert_eq!(Err(NotApplicable), result)); + >(local_dest.clone(), |result| assert_eq!(Err(NotApplicable), result)); ensure_validate_does_not_consume_dest_or_msg::< SovereignPaidRemoteExporter< @@ -562,12 +563,12 @@ mod tests { >(local_dest, |result| assert_eq!(Err(NotApplicable), result)); // check with not applicable destination - let remote_dest = (Parent, Parent, DifferentRemote::get()).into(); - assert!(ensure_is_remote(UniversalLocation::get(), remote_dest).is_ok()); + let remote_dest: Location = (Parent, Parent, DifferentRemote::get()).into(); + assert!(ensure_is_remote(UniversalLocation::get(), remote_dest.clone()).is_ok()); ensure_validate_does_not_consume_dest_or_msg::< UnpaidRemoteExporter, OkSender, UniversalLocation>, - >(remote_dest, |result| assert_eq!(Err(NotApplicable), result)); + >(remote_dest.clone(), |result| assert_eq!(Err(NotApplicable), result)); ensure_validate_does_not_consume_dest_or_msg::< SovereignPaidRemoteExporter< @@ -582,15 +583,15 @@ mod tests { fn network_export_table_works() { frame_support::parameter_types! { pub NetworkA: NetworkId = ByGenesis([0; 32]); - pub Parachain1000InNetworkA: InteriorMultiLocation = X1(Parachain(1000)); - pub Parachain2000InNetworkA: InteriorMultiLocation = X1(Parachain(2000)); + pub Parachain1000InNetworkA: InteriorLocation = [Parachain(1000)].into(); + pub Parachain2000InNetworkA: InteriorLocation = [Parachain(2000)].into(); pub NetworkB: NetworkId = ByGenesis([1; 32]); - pub BridgeToALocation: MultiLocation = MultiLocation::new(1, X1(Parachain(1234))); - pub BridgeToBLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(4321))); + pub BridgeToALocation: Location = Location::new(1, [Parachain(1234)]); + pub BridgeToBLocation: Location = Location::new(1, [Parachain(4321)]); - pub PaymentForNetworkAAndParachain2000: MultiAsset = (MultiLocation::parent(), 150).into(); + pub PaymentForNetworkAAndParachain2000: Asset = (Location::parent(), 150).into(); pub BridgeTable: sp_std::vec::Vec = sp_std::vec![ // NetworkA allows `Parachain(1000)` as remote location WITHOUT payment. @@ -617,19 +618,19 @@ mod tests { ]; } - let test_data = vec![ - (NetworkA::get(), X1(Parachain(1000)), Some((BridgeToALocation::get(), None))), - (NetworkA::get(), X2(Parachain(1000), GeneralIndex(1)), None), + let test_data: Vec<(NetworkId, InteriorLocation, Option<(Location, Option)>)> = vec![ + (NetworkA::get(), [Parachain(1000)].into(), Some((BridgeToALocation::get(), None))), + (NetworkA::get(), [Parachain(1000), GeneralIndex(1)].into(), None), ( NetworkA::get(), - X1(Parachain(2000)), + [Parachain(2000)].into(), Some((BridgeToALocation::get(), Some(PaymentForNetworkAAndParachain2000::get()))), ), - (NetworkA::get(), X2(Parachain(2000), GeneralIndex(1)), None), - (NetworkA::get(), X1(Parachain(3000)), None), - (NetworkB::get(), X1(Parachain(1000)), Some((BridgeToBLocation::get(), None))), - (NetworkB::get(), X1(Parachain(2000)), Some((BridgeToBLocation::get(), None))), - (NetworkB::get(), X1(Parachain(3000)), Some((BridgeToBLocation::get(), None))), + (NetworkA::get(), [Parachain(2000), GeneralIndex(1)].into(), None), + (NetworkA::get(), [Parachain(3000)].into(), None), + (NetworkB::get(), [Parachain(1000)].into(), Some((BridgeToBLocation::get(), None))), + (NetworkB::get(), [Parachain(2000)].into(), Some((BridgeToBLocation::get(), None))), + (NetworkB::get(), [Parachain(3000)].into(), Some((BridgeToBLocation::get(), None))), ]; for (network, remote_location, expected_result) in test_data { diff --git a/polkadot/xcm/xcm-builder/src/weight.rs b/polkadot/xcm/xcm-builder/src/weight.rs index c16c52939a38..5eed62b6b083 100644 --- a/polkadot/xcm/xcm-builder/src/weight.rs +++ b/polkadot/xcm/xcm-builder/src/weight.rs @@ -25,10 +25,12 @@ use frame_support::{ use parity_scale_codec::Decode; use sp_runtime::traits::{SaturatedConversion, Saturating, Zero}; use sp_std::{marker::PhantomData, result::Result}; -use xcm::latest::{prelude::*, Weight}; +use xcm::{ + latest::{prelude::*, Weight, GetWeight}, +}; use xcm_executor::{ traits::{WeightBounds, WeightTrader}, - Assets, + AssetsInHolding, }; pub struct FixedWeightBounds(PhantomData<(T, C, M)>); @@ -114,16 +116,16 @@ where } /// Function trait for handling some revenue. Similar to a negative imbalance (credit) handler, but -/// for a `MultiAsset`. Sensible implementations will deposit the asset in some known treasury or +/// for a `Asset`. Sensible implementations will deposit the asset in some known treasury or /// block-author account. pub trait TakeRevenue { - /// Do something with the given `revenue`, which is a single non-wildcard `MultiAsset`. - fn take_revenue(revenue: MultiAsset); + /// Do something with the given `revenue`, which is a single non-wildcard `Asset`. + fn take_revenue(revenue: Asset); } /// Null implementation just burns the revenue. impl TakeRevenue for () { - fn take_revenue(_revenue: MultiAsset) {} + fn take_revenue(_revenue: Asset) {} } /// Simple fee calculator that requires payment in a single fungible at a fixed rate. @@ -143,9 +145,9 @@ impl, R: TakeRevenue> WeightTrader for FixedRateOf fn buy_weight( &mut self, weight: Weight, - payment: Assets, + payment: AssetsInHolding, context: &XcmContext, - ) -> Result { + ) -> Result { log::trace!( target: "xcm::weight", "FixedRateOfFungible::buy_weight weight: {:?}, payment: {:?}, context: {:?}", @@ -165,7 +167,7 @@ impl, R: TakeRevenue> WeightTrader for FixedRateOf Ok(unused) } - fn refund_weight(&mut self, weight: Weight, context: &XcmContext) -> Option { + fn refund_weight(&mut self, weight: Weight, context: &XcmContext) -> Option { log::trace!(target: "xcm::weight", "FixedRateOfFungible::refund_weight weight: {:?}, context: {:?}", weight, context); let (id, units_per_second, units_per_mb) = T::get(); let weight = weight.min(self.0); @@ -194,22 +196,22 @@ impl, R: TakeRevenue> Drop for FixedRateOfFungible /// places any weight bought into the right account. pub struct UsingComponents< WeightToFee: WeightToFeeT, - AssetId: Get, + AssetIdValue: Get, AccountId, Currency: CurrencyT, OnUnbalanced: OnUnbalancedT, >( Weight, Currency::Balance, - PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>, + PhantomData<(WeightToFee, AssetIdValue, AccountId, Currency, OnUnbalanced)>, ); impl< WeightToFee: WeightToFeeT, - AssetId: Get, + AssetIdValue: Get, AccountId, Currency: CurrencyT, OnUnbalanced: OnUnbalancedT, - > WeightTrader for UsingComponents + > WeightTrader for UsingComponents { fn new() -> Self { Self(Weight::zero(), Zero::zero(), PhantomData) @@ -218,20 +220,20 @@ impl< fn buy_weight( &mut self, weight: Weight, - payment: Assets, + payment: AssetsInHolding, context: &XcmContext, - ) -> Result { + ) -> Result { log::trace!(target: "xcm::weight", "UsingComponents::buy_weight weight: {:?}, payment: {:?}, context: {:?}", weight, payment, context); let amount = WeightToFee::weight_to_fee(&weight); let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?; - let required = (Concrete(AssetId::get()), u128_amount).into(); + let required = (AssetId(AssetIdValue::get()), u128_amount).into(); let unused = payment.checked_sub(required).map_err(|_| XcmError::TooExpensive)?; self.0 = self.0.saturating_add(weight); self.1 = self.1.saturating_add(amount); Ok(unused) } - fn refund_weight(&mut self, weight: Weight, context: &XcmContext) -> Option { + fn refund_weight(&mut self, weight: Weight, context: &XcmContext) -> Option { log::trace!(target: "xcm::weight", "UsingComponents::refund_weight weight: {:?}, context: {:?}", weight, context); let weight = weight.min(self.0); let amount = WeightToFee::weight_to_fee(&weight); @@ -239,7 +241,7 @@ impl< self.1 = self.1.saturating_sub(amount); let amount: u128 = amount.saturated_into(); if amount > 0 { - Some((AssetId::get(), amount).into()) + Some((AssetIdValue::get(), amount).into()) } else { None } @@ -247,7 +249,7 @@ impl< } impl< WeightToFee: WeightToFeeT, - AssetId: Get, + AssetId: Get, AccountId, Currency: CurrencyT, OnUnbalanced: OnUnbalancedT, diff --git a/polkadot/xcm/xcm-builder/tests/mock/mod.rs b/polkadot/xcm/xcm-builder/tests/mock/mod.rs index 4f183c7a15b6..ebe6ac724bcc 100644 --- a/polkadot/xcm/xcm-builder/tests/mock/mod.rs +++ b/polkadot/xcm/xcm-builder/tests/mock/mod.rs @@ -44,24 +44,24 @@ pub type AccountId = AccountId32; pub type Balance = u128; thread_local! { - pub static SENT_XCM: RefCell> = RefCell::new(Vec::new()); + pub static SENT_XCM: RefCell> = RefCell::new(Vec::new()); } -pub fn sent_xcm() -> Vec<(MultiLocation, opaque::Xcm, XcmHash)> { +pub fn sent_xcm() -> Vec<(Location, opaque::Xcm, XcmHash)> { SENT_XCM.with(|q| (*q.borrow()).clone()) } pub struct TestSendXcm; impl SendXcm for TestSendXcm { - type Ticket = (MultiLocation, Xcm<()>, XcmHash); + type Ticket = (Location, Xcm<()>, XcmHash); fn validate( - dest: &mut Option, + dest: &mut Option, msg: &mut Option>, - ) -> SendResult<(MultiLocation, Xcm<()>, XcmHash)> { + ) -> SendResult<(Location, Xcm<()>, XcmHash)> { let msg = msg.take().unwrap(); let hash = fake_message_hash(&msg); let triplet = (dest.take().unwrap(), msg, hash); - Ok((triplet, MultiAssets::new())) + Ok((triplet, Assets::new())) } - fn deliver(triplet: (MultiLocation, Xcm<()>, XcmHash)) -> Result { + fn deliver(triplet: (Location, Xcm<()>, XcmHash)) -> Result { let hash = triplet.2; SENT_XCM.with(|q| q.borrow_mut().push(triplet)); Ok(hash) @@ -133,9 +133,9 @@ impl configuration::Config for Runtime { // aims to closely emulate the Kusama XcmConfig parameter_types! { - pub const KsmLocation: MultiLocation = MultiLocation::here(); + pub const KsmLocation: Location = Location::here(); pub const KusamaNetwork: NetworkId = NetworkId::Kusama; - pub UniversalLocation: InteriorMultiLocation = Here; + pub UniversalLocation: InteriorLocation = Here; pub CheckAccount: (AccountId, MintLocation) = (XcmPallet::check_account(), MintLocation::Local); } @@ -172,8 +172,8 @@ pub type Barrier = ( ); parameter_types! { - pub KusamaForAssetHub: (MultiAssetFilter, MultiLocation) = - (Wild(AllOf { id: Concrete(Here.into()), fun: WildFungible }), Parachain(1000).into()); + pub KusamaForAssetHub: (AssetFilter, Location) = + (Wild(AllOf { id: AssetId(Here.into()), fun: WildFungible }), Parachain(1000).into()); pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 4; } diff --git a/polkadot/xcm/xcm-builder/tests/scenarios.rs b/polkadot/xcm/xcm-builder/tests/scenarios.rs index 36780b9f0078..6721e1e5c53f 100644 --- a/polkadot/xcm/xcm-builder/tests/scenarios.rs +++ b/polkadot/xcm/xcm-builder/tests/scenarios.rs @@ -55,9 +55,9 @@ fn withdraw_and_deposit_works() { beneficiary: Parachain(other_para_id).into(), }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); - assert_eq!(r, Outcome::Complete(weight)); + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute(Parachain(PARA_ID), message, &mut hash, weight, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: weight }); let other_para_acc: AccountId = ParaId::from(other_para_id).into_account_truncating(); assert_eq!(Balances::free_balance(para_acc), INITIAL_BALANCE - amount); assert_eq!(Balances::free_balance(other_para_acc), amount); @@ -79,19 +79,19 @@ fn transfer_asset_works() { assets: (Here, amount).into(), beneficiary: AccountId32 { network: None, id: bob.clone().into() }.into(), }]); - let hash = fake_message_hash(&message); - // Use `execute_xcm_in_credit` here to pass through the barrier - let r = XcmExecutor::::execute_xcm_in_credit( + let mut hash = fake_message_hash(&message); + // Use `prepare_and_execute` here to pass through the barrier + let r = XcmExecutor::::prepare_and_execute( AccountId32 { network: None, id: ALICE.into() }, message, - hash, + &mut hash, weight, weight, ); System::assert_last_event( pallet_balances::Event::Transfer { from: ALICE, to: bob.clone(), amount }.into(), ); - assert_eq!(r, Outcome::Complete(weight)); + assert_eq!(r, Outcome::Complete { used: weight }); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE - amount); assert_eq!(Balances::free_balance(bob), INITIAL_BALANCE + amount); }); @@ -129,14 +129,14 @@ fn report_holding_works() { // is not triggered becasue the deposit fails ReportHolding { response_info: response_info.clone(), assets: All.into() }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute(Parachain(PARA_ID), message, &mut hash, weight, Weight::zero()); assert_eq!( r, - Outcome::Incomplete( - weight - BaseXcmWeight::get(), - XcmError::FailedToTransactAsset("AccountIdConversionFailed") - ) + Outcome::Incomplete { + used: weight - BaseXcmWeight::get(), + error: XcmError::FailedToTransactAsset("AccountIdConversionFailed") + } ); // there should be no query response sent for the failed deposit assert_eq!(mock::sent_xcm(), vec![]); @@ -153,9 +153,9 @@ fn report_holding_works() { // used to get a notification in case of success ReportHolding { response_info: response_info.clone(), assets: AllCounted(1).into() }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); - assert_eq!(r, Outcome::Complete(weight)); + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute(Parachain(PARA_ID), message, &mut hash, weight, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: weight }); let other_para_acc: AccountId = ParaId::from(other_para_id).into_account_truncating(); assert_eq!(Balances::free_balance(other_para_acc), amount); assert_eq!(Balances::free_balance(para_acc), INITIAL_BALANCE - 2 * amount); @@ -209,9 +209,9 @@ fn teleport_to_asset_hub_works() { xcm: Xcm(teleport_effects.clone()), }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); - assert_eq!(r, Outcome::Complete(weight)); + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute(Parachain(PARA_ID), message, &mut hash, weight, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: weight }); let expected_msg = Xcm(vec![ReceiveTeleportedAsset((Parent, amount).into()), ClearOrigin] .into_iter() .chain(teleport_effects.clone().into_iter()) @@ -232,9 +232,9 @@ fn teleport_to_asset_hub_works() { xcm: Xcm(teleport_effects.clone()), }, ]); - let hash = fake_message_hash(&message); - let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); - assert_eq!(r, Outcome::Complete(weight)); + let mut hash = fake_message_hash(&message); + let r = XcmExecutor::::prepare_and_execute(Parachain(PARA_ID), message, &mut hash, weight, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: weight }); // 2 * amount because of the other teleport above assert_eq!(Balances::free_balance(para_acc), INITIAL_BALANCE - 2 * amount); let expected_msg = Xcm(vec![ReceiveTeleportedAsset((Parent, amount).into()), ClearOrigin] @@ -282,10 +282,10 @@ fn reserve_based_transfer_works() { xcm: Xcm(transfer_effects.clone()), }, ]); - let hash = fake_message_hash(&message); + let mut hash = fake_message_hash(&message); let weight = BaseXcmWeight::get() * 3; - let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); - assert_eq!(r, Outcome::Complete(weight)); + let r = XcmExecutor::::prepare_and_execute(Parachain(PARA_ID), message, &mut hash, weight, Weight::zero()); + assert_eq!(r, Outcome::Complete { used: weight }); assert_eq!(Balances::free_balance(para_acc), INITIAL_BALANCE - amount); let expected_msg = Xcm(vec![ReserveAssetDeposited((Parent, amount).into()), ClearOrigin] .into_iter() diff --git a/polkadot/xcm/xcm-executor/integration-tests/src/lib.rs b/polkadot/xcm/xcm-executor/integration-tests/src/lib.rs index d8c77f8317e1..de5c06d3a5cb 100644 --- a/polkadot/xcm/xcm-executor/integration-tests/src/lib.rs +++ b/polkadot/xcm/xcm-executor/integration-tests/src/lib.rs @@ -65,7 +65,7 @@ fn basic_buy_fees_message_executes() { assert!(polkadot_test_runtime::System::events().iter().any(|r| matches!( r.event, polkadot_test_runtime::RuntimeEvent::Xcm(pallet_xcm::Event::Attempted { - outcome: Outcome::Complete(_) + outcome: Outcome::Complete { .. } }), ))); }); @@ -116,7 +116,7 @@ fn transact_recursion_limit_works() { assert!(polkadot_test_runtime::System::events().iter().any(|r| matches!( r.event, polkadot_test_runtime::RuntimeEvent::Xcm(pallet_xcm::Event::Attempted { - outcome: Outcome::Incomplete(_, XcmError::ExceedsStackLimit) + outcome: Outcome::Incomplete { used: _, error: XcmError::ExceedsStackLimit } }), ))); }); @@ -198,7 +198,7 @@ fn query_response_fires() { assert_eq!( polkadot_test_runtime::Xcm::query(query_id), Some(QueryStatus::Ready { - response: VersionedResponse::V3(Response::ExecutionResult(None)), + response: VersionedResponse::V4(Response::ExecutionResult(None)), at: 2u32.into() }), ) @@ -270,12 +270,12 @@ fn query_response_elicits_handler() { client.state_at(block_hash).expect("state should exist").inspect_state(|| { assert!(polkadot_test_runtime::System::events().iter().any(|r| matches!( - r.event, + &r.event, TestNotifier(ResponseReceived( - MultiLocation { parents: 0, interior: X1(Junction::AccountId32 { .. }) }, + location, q, Response::ExecutionResult(None), - )) if q == query_id, + )) if *q == query_id && matches!(location.unpack(), (0, [Junction::AccountId32 { .. }])), ))); }); } diff --git a/polkadot/xcm/xcm-executor/src/assets.rs b/polkadot/xcm/xcm-executor/src/assets.rs index 33f2ff218c73..56435ac5a112 100644 --- a/polkadot/xcm/xcm-executor/src/assets.rs +++ b/polkadot/xcm/xcm-executor/src/assets.rs @@ -21,16 +21,17 @@ use sp_std::{ prelude::*, }; use xcm::latest::{ - AssetId, AssetInstance, + Asset, AssetFilter, AssetId, AssetInstance, Assets, Fungibility::{Fungible, NonFungible}, - InteriorMultiLocation, MultiAsset, MultiAssetFilter, MultiAssets, MultiLocation, + InteriorLocation, Location, + WildAsset::{All, AllCounted, AllOf, AllOfCounted}, WildFungibility::{Fungible as WildFungible, NonFungible as WildNonFungible}, - WildMultiAsset::{All, AllCounted, AllOf, AllOfCounted}, + Reanchorable, }; -/// List of non-wildcard fungible and non-fungible assets. +/// Map of non-wildcard fungible and non-fungible assets held in the holding register. #[derive(Default, Clone, RuntimeDebug, Eq, PartialEq)] -pub struct Assets { +pub struct AssetsInHolding { /// The fungible assets. pub fungible: BTreeMap, @@ -40,16 +41,16 @@ pub struct Assets { pub non_fungible: BTreeSet<(AssetId, AssetInstance)>, } -impl From for Assets { - fn from(asset: MultiAsset) -> Assets { +impl From for AssetsInHolding { + fn from(asset: Asset) -> AssetsInHolding { let mut result = Self::default(); result.subsume(asset); result } } -impl From> for Assets { - fn from(assets: Vec) -> Assets { +impl From> for AssetsInHolding { + fn from(assets: Vec) -> AssetsInHolding { let mut result = Self::default(); for asset in assets.into_iter() { result.subsume(asset) @@ -58,21 +59,21 @@ impl From> for Assets { } } -impl From for Assets { - fn from(assets: MultiAssets) -> Assets { +impl From for AssetsInHolding { + fn from(assets: Assets) -> AssetsInHolding { assets.into_inner().into() } } -impl From for Vec { - fn from(a: Assets) -> Self { +impl From for Vec { + fn from(a: AssetsInHolding) -> Self { a.into_assets_iter().collect() } } -impl From for MultiAssets { - fn from(a: Assets) -> Self { - a.into_assets_iter().collect::>().into() +impl From for Assets { + fn from(a: AssetsInHolding) -> Self { + a.into_assets_iter().collect::>().into() } } @@ -80,10 +81,10 @@ impl From for MultiAssets { #[derive(Debug)] pub enum TakeError { /// There was an attempt to take an asset without saturating (enough of) which did not exist. - AssetUnderflow(MultiAsset), + AssetUnderflow(Asset), } -impl Assets { +impl AssetsInHolding { /// New value, containing no assets. pub fn new() -> Self { Self::default() @@ -100,41 +101,41 @@ impl Assets { } /// A borrowing iterator over the fungible assets. - pub fn fungible_assets_iter(&self) -> impl Iterator + '_ { + pub fn fungible_assets_iter(&self) -> impl Iterator + '_ { self.fungible .iter() - .map(|(id, &amount)| MultiAsset { fun: Fungible(amount), id: *id }) + .map(|(id, &amount)| Asset { fun: Fungible(amount), id: id.clone() }) } /// A borrowing iterator over the non-fungible assets. - pub fn non_fungible_assets_iter(&self) -> impl Iterator + '_ { + pub fn non_fungible_assets_iter(&self) -> impl Iterator + '_ { self.non_fungible .iter() - .map(|(id, instance)| MultiAsset { fun: NonFungible(*instance), id: *id }) + .map(|(id, instance)| Asset { fun: NonFungible(*instance), id: id.clone() }) } /// A consuming iterator over all assets. - pub fn into_assets_iter(self) -> impl Iterator { + pub fn into_assets_iter(self) -> impl Iterator { self.fungible .into_iter() - .map(|(id, amount)| MultiAsset { fun: Fungible(amount), id }) + .map(|(id, amount)| Asset { fun: Fungible(amount), id }) .chain( self.non_fungible .into_iter() - .map(|(id, instance)| MultiAsset { fun: NonFungible(instance), id }), + .map(|(id, instance)| Asset { fun: NonFungible(instance), id }), ) } /// A borrowing iterator over all assets. - pub fn assets_iter(&self) -> impl Iterator + '_ { + pub fn assets_iter(&self) -> impl Iterator + '_ { self.fungible_assets_iter().chain(self.non_fungible_assets_iter()) } /// Mutate `self` to contain all given `assets`, saturating if necessary. /// - /// NOTE: [`Assets`] are always sorted, allowing us to optimize this function from `O(n^2)` to - /// `O(n)`. - pub fn subsume_assets(&mut self, mut assets: Assets) { + /// NOTE: [`AssetsInHolding`] are always sorted, allowing us to optimize this function from + /// `O(n^2)` to `O(n)`. + pub fn subsume_assets(&mut self, mut assets: AssetsInHolding) { let mut f_iter = assets.fungible.iter_mut(); let mut g_iter = self.fungible.iter_mut(); if let (Some(mut f), Some(mut g)) = (f_iter.next(), g_iter.next()) { @@ -166,7 +167,7 @@ impl Assets { /// Mutate `self` to contain the given `asset`, saturating if necessary. /// /// Wildcard values of `asset` do nothing. - pub fn subsume(&mut self, asset: MultiAsset) { + pub fn subsume(&mut self, asset: Asset) { match asset.fun { Fungible(amount) => { self.fungible @@ -180,18 +181,18 @@ impl Assets { } } - /// Swaps two mutable Assets, without deinitializing either one. - pub fn swapped(&mut self, mut with: Assets) -> Self { + /// Swaps two mutable AssetsInHolding, without deinitializing either one. + pub fn swapped(&mut self, mut with: AssetsInHolding) -> Self { mem::swap(&mut *self, &mut with); with } - /// Alter any concretely identified assets by prepending the given `MultiLocation`. + /// Alter any concretely identified assets by prepending the given `Location`. /// /// WARNING: For now we consider this infallible and swallow any errors. It is thus the caller's /// responsibility to ensure that any internal asset IDs are able to be prepended without /// overflow. - pub fn prepend_location(&mut self, prepend: &MultiLocation) { + pub fn prepend_location(&mut self, prepend: &Location) { let mut fungible = Default::default(); mem::swap(&mut self.fungible, &mut fungible); self.fungible = fungible @@ -218,8 +219,8 @@ impl Assets { /// Any assets which were unable to be reanchored are introduced into `failed_bin`. pub fn reanchor( &mut self, - target: &MultiLocation, - context: InteriorMultiLocation, + target: &Location, + context: &InteriorLocation, mut maybe_failed_bin: Option<&mut Self>, ) { let mut fungible = Default::default(); @@ -249,22 +250,22 @@ impl Assets { } /// Returns `true` if `asset` is contained within `self`. - pub fn contains_asset(&self, asset: &MultiAsset) -> bool { + pub fn contains_asset(&self, asset: &Asset) -> bool { match asset { - MultiAsset { fun: Fungible(amount), id } => + Asset { fun: Fungible(amount), id } => self.fungible.get(id).map_or(false, |a| a >= amount), - MultiAsset { fun: NonFungible(instance), id } => - self.non_fungible.contains(&(*id, *instance)), + Asset { fun: NonFungible(instance), id } => + self.non_fungible.contains(&(id.clone(), *instance)), } } /// Returns `true` if all `assets` are contained within `self`. - pub fn contains_assets(&self, assets: &MultiAssets) -> bool { + pub fn contains_assets(&self, assets: &Assets) -> bool { assets.inner().iter().all(|a| self.contains_asset(a)) } /// Returns `true` if all `assets` are contained within `self`. - pub fn contains(&self, assets: &Assets) -> bool { + pub fn contains(&self, assets: &AssetsInHolding) -> bool { assets .fungible .iter() @@ -274,16 +275,16 @@ impl Assets { /// Returns an error unless all `assets` are contained in `self`. In the case of an error, the /// first asset in `assets` which is not wholly in `self` is returned. - pub fn ensure_contains(&self, assets: &MultiAssets) -> Result<(), TakeError> { + pub fn ensure_contains(&self, assets: &Assets) -> Result<(), TakeError> { for asset in assets.inner().iter() { match asset { - MultiAsset { fun: Fungible(amount), id } => { + Asset { fun: Fungible(amount), id } => { if self.fungible.get(id).map_or(true, |a| a < amount) { - return Err(TakeError::AssetUnderflow((*id, *amount).into())) + return Err(TakeError::AssetUnderflow((id.clone(), *amount).into())) } }, - MultiAsset { fun: NonFungible(instance), id } => { - let id_instance = (*id, *instance); + Asset { fun: NonFungible(instance), id } => { + let id_instance = (id.clone(), *instance); if !self.non_fungible.contains(&id_instance) { return Err(TakeError::AssetUnderflow(id_instance.into())) } @@ -308,16 +309,16 @@ impl Assets { /// of) a definite asset to be removed. fn general_take( &mut self, - mask: MultiAssetFilter, + mask: AssetFilter, saturate: bool, - ) -> Result { - let mut taken = Assets::new(); + ) -> Result { + let mut taken = AssetsInHolding::new(); let maybe_limit = mask.limit().map(|x| x as usize); match mask { // TODO: Counted variants where we define `limit`. - MultiAssetFilter::Wild(All) | MultiAssetFilter::Wild(AllCounted(_)) => { + AssetFilter::Wild(All) | AssetFilter::Wild(AllCounted(_)) => { if maybe_limit.map_or(true, |l| self.len() <= l) { - return Ok(self.swapped(Assets::new())) + return Ok(self.swapped(AssetsInHolding::new())) } else { let fungible = mem::replace(&mut self.fungible, Default::default()); fungible.into_iter().for_each(|(c, amount)| { @@ -337,15 +338,15 @@ impl Assets { }); } }, - MultiAssetFilter::Wild(AllOfCounted { fun: WildFungible, id, .. }) | - MultiAssetFilter::Wild(AllOf { fun: WildFungible, id }) => + AssetFilter::Wild(AllOfCounted { fun: WildFungible, id, .. }) | + AssetFilter::Wild(AllOf { fun: WildFungible, id }) => if maybe_limit.map_or(true, |l| l >= 1) { if let Some((id, amount)) = self.fungible.remove_entry(&id) { taken.fungible.insert(id, amount); } }, - MultiAssetFilter::Wild(AllOfCounted { fun: WildNonFungible, id, .. }) | - MultiAssetFilter::Wild(AllOf { fun: WildNonFungible, id }) => { + AssetFilter::Wild(AllOfCounted { fun: WildNonFungible, id, .. }) | + AssetFilter::Wild(AllOf { fun: WildNonFungible, id }) => { let non_fungible = mem::replace(&mut self.non_fungible, Default::default()); non_fungible.into_iter().for_each(|(c, instance)| { if c == id && maybe_limit.map_or(true, |l| taken.len() < l) { @@ -355,13 +356,13 @@ impl Assets { } }); }, - MultiAssetFilter::Definite(assets) => { + AssetFilter::Definite(assets) => { if !saturate { self.ensure_contains(&assets)?; } for asset in assets.into_inner().into_iter() { match asset { - MultiAsset { fun: Fungible(amount), id } => { + Asset { fun: Fungible(amount), id } => { let (remove, amount) = match self.fungible.get_mut(&id) { Some(self_amount) => { let amount = amount.min(*self_amount); @@ -374,10 +375,10 @@ impl Assets { self.fungible.remove(&id); } if amount > 0 { - taken.subsume(MultiAsset::from((id, amount)).into()); + taken.subsume(Asset::from((id, amount)).into()); } }, - MultiAsset { fun: NonFungible(instance), id } => { + Asset { fun: NonFungible(instance), id } => { let id_instance = (id, instance); if self.non_fungible.remove(&id_instance) { taken.subsume(id_instance.into()) @@ -395,7 +396,7 @@ impl Assets { /// /// Returns `Ok` with the non-wildcard equivalence of `mask` taken and mutates `self` to its /// value minus `mask` if `self` contains `asset`, and return `Err` otherwise. - pub fn saturating_take(&mut self, asset: MultiAssetFilter) -> Assets { + pub fn saturating_take(&mut self, asset: AssetFilter) -> AssetsInHolding { self.general_take(asset, true) .expect("general_take never results in error when saturating") } @@ -405,13 +406,13 @@ impl Assets { /// /// Returns `Ok` with the non-wildcard equivalence of `asset` taken and mutates `self` to its /// value minus `asset` if `self` contains `asset`, and return `Err` otherwise. - pub fn try_take(&mut self, mask: MultiAssetFilter) -> Result { + pub fn try_take(&mut self, mask: AssetFilter) -> Result { self.general_take(mask, false) } /// Consumes `self` and returns its original value excluding `asset` iff it contains at least /// `asset`. - pub fn checked_sub(mut self, asset: MultiAsset) -> Result { + pub fn checked_sub(mut self, asset: Asset) -> Result { match asset.fun { Fungible(amount) => { let remove = if let Some(balance) = self.fungible.get_mut(&asset.id) { @@ -446,66 +447,66 @@ impl Assets { /// Example: /// /// ``` - /// use staging_xcm_executor::Assets; + /// use staging_xcm_executor::AssetsInHolding; /// use xcm::latest::prelude::*; - /// let assets_i_have: Assets = vec![ (Here, 100).into(), ([0; 32], 100).into() ].into(); - /// let assets_they_want: MultiAssetFilter = vec![ (Here, 200).into(), ([0; 32], 50).into() ].into(); + /// let assets_i_have: AssetsInHolding = vec![ (Here, 100).into(), (Junctions::from([GeneralIndex(0)]), 100).into() ].into(); + /// let assets_they_want: AssetFilter = vec![ (Here, 200).into(), (Junctions::from([GeneralIndex(0)]), 50).into() ].into(); /// - /// let assets_we_can_trade: Assets = assets_i_have.min(&assets_they_want); + /// let assets_we_can_trade: AssetsInHolding = assets_i_have.min(&assets_they_want); /// assert_eq!(assets_we_can_trade.into_assets_iter().collect::>(), vec![ - /// (Here, 100).into(), ([0; 32], 50).into(), + /// (Here, 100).into(), (Junctions::from([GeneralIndex(0)]), 50).into(), /// ]); /// ``` - pub fn min(&self, mask: &MultiAssetFilter) -> Assets { - let mut masked = Assets::new(); + pub fn min(&self, mask: &AssetFilter) -> AssetsInHolding { + let mut masked = AssetsInHolding::new(); let maybe_limit = mask.limit().map(|x| x as usize); if maybe_limit.map_or(false, |l| l == 0) { return masked } match mask { - MultiAssetFilter::Wild(All) | MultiAssetFilter::Wild(AllCounted(_)) => { + AssetFilter::Wild(All) | AssetFilter::Wild(AllCounted(_)) => { if maybe_limit.map_or(true, |l| self.len() <= l) { return self.clone() } else { - for (&c, &amount) in self.fungible.iter() { - masked.fungible.insert(c, amount); + for (c, &amount) in self.fungible.iter() { + masked.fungible.insert(c.clone(), amount); if maybe_limit.map_or(false, |l| masked.len() >= l) { return masked } } for (c, instance) in self.non_fungible.iter() { - masked.non_fungible.insert((*c, *instance)); + masked.non_fungible.insert((c.clone(), *instance)); if maybe_limit.map_or(false, |l| masked.len() >= l) { return masked } } } }, - MultiAssetFilter::Wild(AllOfCounted { fun: WildFungible, id, .. }) | - MultiAssetFilter::Wild(AllOf { fun: WildFungible, id }) => + AssetFilter::Wild(AllOfCounted { fun: WildFungible, id, .. }) | + AssetFilter::Wild(AllOf { fun: WildFungible, id }) => if let Some(&amount) = self.fungible.get(&id) { - masked.fungible.insert(*id, amount); + masked.fungible.insert(id.clone(), amount); }, - MultiAssetFilter::Wild(AllOfCounted { fun: WildNonFungible, id, .. }) | - MultiAssetFilter::Wild(AllOf { fun: WildNonFungible, id }) => + AssetFilter::Wild(AllOfCounted { fun: WildNonFungible, id, .. }) | + AssetFilter::Wild(AllOf { fun: WildNonFungible, id }) => for (c, instance) in self.non_fungible.iter() { if c == id { - masked.non_fungible.insert((*c, *instance)); + masked.non_fungible.insert((c.clone(), *instance)); if maybe_limit.map_or(false, |l| masked.len() >= l) { return masked } } }, - MultiAssetFilter::Definite(assets) => + AssetFilter::Definite(assets) => for asset in assets.inner().iter() { match asset { - MultiAsset { fun: Fungible(amount), id } => { + Asset { fun: Fungible(amount), id } => { if let Some(m) = self.fungible.get(id) { - masked.subsume((*id, Fungible(*amount.min(m))).into()); + masked.subsume((id.clone(), Fungible(*amount.min(m))).into()); } }, - MultiAsset { fun: NonFungible(instance), id } => { - let id_instance = (*id, *instance); + Asset { fun: NonFungible(instance), id } => { + let id_instance = (id.clone(), *instance); if self.non_fungible.contains(&id_instance) { masked.subsume(id_instance.into()); } @@ -522,30 +523,18 @@ mod tests { use super::*; use xcm::latest::prelude::*; #[allow(non_snake_case)] - /// Abstract fungible constructor - fn AF(id: u8, amount: u128) -> MultiAsset { - ([id; 32], amount).into() - } - #[allow(non_snake_case)] - /// Abstract non-fungible constructor - fn ANF(class: u8, instance_id: u8) -> MultiAsset { - ([class; 32], [instance_id; 4]).into() - } - #[allow(non_snake_case)] /// Concrete fungible constructor - fn CF(amount: u128) -> MultiAsset { + fn CF(amount: u128) -> Asset { (Here, amount).into() } #[allow(non_snake_case)] /// Concrete non-fungible constructor - fn CNF(instance_id: u8) -> MultiAsset { + fn CNF(instance_id: u8) -> Asset { (Here, [instance_id; 4]).into() } - fn test_assets() -> Assets { - let mut assets = Assets::new(); - assets.subsume(AF(1, 100)); - assets.subsume(ANF(2, 20)); + fn test_assets() -> AssetsInHolding { + let mut assets = AssetsInHolding::new(); assets.subsume(CF(300)); assets.subsume(CNF(40)); assets @@ -554,9 +543,7 @@ mod tests { #[test] fn subsume_assets_works() { let t1 = test_assets(); - let mut t2 = Assets::new(); - t2.subsume(AF(1, 50)); - t2.subsume(ANF(2, 10)); + let mut t2 = AssetsInHolding::new(); t2.subsume(CF(300)); t2.subsume(CNF(50)); let mut r1 = t1.clone(); @@ -571,63 +558,48 @@ mod tests { #[test] fn checked_sub_works() { let t = test_assets(); - let t = t.checked_sub(AF(1, 50)).unwrap(); - let t = t.checked_sub(AF(1, 51)).unwrap_err(); - let t = t.checked_sub(AF(1, 50)).unwrap(); - let t = t.checked_sub(AF(1, 1)).unwrap_err(); let t = t.checked_sub(CF(150)).unwrap(); let t = t.checked_sub(CF(151)).unwrap_err(); let t = t.checked_sub(CF(150)).unwrap(); let t = t.checked_sub(CF(1)).unwrap_err(); - let t = t.checked_sub(ANF(2, 21)).unwrap_err(); - let t = t.checked_sub(ANF(2, 20)).unwrap(); - let t = t.checked_sub(ANF(2, 20)).unwrap_err(); let t = t.checked_sub(CNF(41)).unwrap_err(); let t = t.checked_sub(CNF(40)).unwrap(); let t = t.checked_sub(CNF(40)).unwrap_err(); - assert_eq!(t, Assets::new()); + assert_eq!(t, AssetsInHolding::new()); } #[test] fn into_assets_iter_works() { let assets = test_assets(); let mut iter = assets.into_assets_iter(); - // Order defined by implementation: CF, AF, CNF, ANF + // Order defined by implementation: CF, CNF assert_eq!(Some(CF(300)), iter.next()); - assert_eq!(Some(AF(1, 100)), iter.next()); assert_eq!(Some(CNF(40)), iter.next()); - assert_eq!(Some(ANF(2, 20)), iter.next()); assert_eq!(None, iter.next()); } #[test] fn assets_into_works() { - let mut assets_vec: Vec = Vec::new(); - assets_vec.push(AF(1, 100)); - assets_vec.push(ANF(2, 20)); + let mut assets_vec: Vec = Vec::new(); assets_vec.push(CF(300)); assets_vec.push(CNF(40)); // Push same group of tokens again - assets_vec.push(AF(1, 100)); - assets_vec.push(ANF(2, 20)); assets_vec.push(CF(300)); assets_vec.push(CNF(40)); - let assets: Assets = assets_vec.into(); + let assets: AssetsInHolding = assets_vec.into(); let mut iter = assets.into_assets_iter(); // Fungibles add assert_eq!(Some(CF(600)), iter.next()); - assert_eq!(Some(AF(1, 200)), iter.next()); // Non-fungibles collapse assert_eq!(Some(CNF(40)), iter.next()); - assert_eq!(Some(ANF(2, 20)), iter.next()); assert_eq!(None, iter.next()); } #[test] fn min_all_and_none_works() { let assets = test_assets(); - let none = MultiAssets::new().into(); + let none = Assets::new().into(); let all = All.into(); let none_min = assets.min(&none); @@ -638,43 +610,15 @@ mod tests { #[test] fn min_counted_works() { - let mut assets = Assets::new(); - assets.subsume(AF(1, 100)); - assets.subsume(ANF(2, 20)); + let mut assets = AssetsInHolding::new(); assets.subsume(CNF(40)); - assets.subsume(AF(10, 50)); - assets.subsume(ANF(2, 40)); - assets.subsume(ANF(2, 30)); assets.subsume(CF(3000)); assets.subsume(CNF(80)); - assets.subsume(ANF(3, 10)); - let fungible = WildMultiAsset::from(([1u8; 32], WildFungible)).counted(2).into(); - let non_fungible = WildMultiAsset::from(([2u8; 32], WildNonFungible)).counted(2).into(); - let all = WildMultiAsset::AllCounted(6).into(); + let all = WildAsset::AllCounted(6).into(); - let fungible = assets.min(&fungible); - let fungible = fungible.assets_iter().collect::>(); - assert_eq!(fungible, vec![AF(1, 100)]); - let non_fungible = assets.min(&non_fungible); - let non_fungible = non_fungible.assets_iter().collect::>(); - assert_eq!(non_fungible, vec![ANF(2, 20), ANF(2, 30)]); let all = assets.min(&all); let all = all.assets_iter().collect::>(); - assert_eq!(all, vec![CF(3000), AF(1, 100), AF(10, 50), CNF(40), CNF(80), ANF(2, 20),]); - } - - #[test] - fn min_all_abstract_works() { - let assets = test_assets(); - let fungible = Wild(([1u8; 32], WildFungible).into()); - let non_fungible = Wild(([2u8; 32], WildNonFungible).into()); - - let fungible = assets.min(&fungible); - let fungible = fungible.assets_iter().collect::>(); - assert_eq!(fungible, vec![AF(1, 100)]); - let non_fungible = assets.min(&non_fungible); - let non_fungible = non_fungible.assets_iter().collect::>(); - assert_eq!(non_fungible, vec![ANF(2, 20)]); + assert_eq!(all, vec![CF(3000), CNF(40), CNF(80)]); } #[test] @@ -695,20 +639,16 @@ mod tests { fn min_basic_works() { let assets1 = test_assets(); - let mut assets2 = Assets::new(); - // This is less than 100, so it will decrease to 50 - assets2.subsume(AF(1, 50)); - // This asset does not exist, so not included - assets2.subsume(ANF(2, 40)); + let mut assets2 = AssetsInHolding::new(); // This is more then 300, so it should stay at 300 assets2.subsume(CF(600)); // This asset should be included assets2.subsume(CNF(40)); - let assets2: MultiAssets = assets2.into(); + let assets2: Assets = assets2.into(); let assets_min = assets1.min(&assets2.into()); let assets_min = assets_min.into_assets_iter().collect::>(); - assert_eq!(assets_min, vec![CF(300), AF(1, 50), CNF(40)]); + assert_eq!(assets_min, vec![CF(300), CNF(40)]); } #[test] @@ -724,23 +664,6 @@ mod tests { assert!(all_iter.eq(test_assets().assets_iter())); } - #[test] - fn saturating_take_all_abstract_works() { - let mut assets = test_assets(); - let fungible = Wild(([1u8; 32], WildFungible).into()); - let non_fungible = Wild(([2u8; 32], WildNonFungible).into()); - - let fungible = assets.saturating_take(fungible); - let fungible = fungible.assets_iter().collect::>(); - assert_eq!(fungible, vec![AF(1, 100)]); - let non_fungible = assets.saturating_take(non_fungible); - let non_fungible = non_fungible.assets_iter().collect::>(); - assert_eq!(non_fungible, vec![ANF(2, 20)]); - // Assets drained of abstract - let final_assets = assets.assets_iter().collect::>(); - assert_eq!(final_assets, vec![CF(300), CNF(40)]); - } - #[test] fn saturating_take_all_concrete_works() { let mut assets = test_assets(); @@ -753,102 +676,49 @@ mod tests { let non_fungible = assets.saturating_take(non_fungible); let non_fungible = non_fungible.assets_iter().collect::>(); assert_eq!(non_fungible, vec![CNF(40)]); - // Assets drained of concrete - let assets = assets.assets_iter().collect::>(); - assert_eq!(assets, vec![AF(1, 100), ANF(2, 20)]); } #[test] fn saturating_take_basic_works() { let mut assets1 = test_assets(); - let mut assets2 = Assets::new(); - // We should take 50 - assets2.subsume(AF(1, 50)); - // This asset should not be taken - assets2.subsume(ANF(2, 40)); + let mut assets2 = AssetsInHolding::new(); // This is more then 300, so it takes everything assets2.subsume(CF(600)); // This asset should be taken assets2.subsume(CNF(40)); - let assets2: MultiAssets = assets2.into(); + let assets2: Assets = assets2.into(); let taken = assets1.saturating_take(assets2.into()); let taken = taken.into_assets_iter().collect::>(); - assert_eq!(taken, vec![CF(300), AF(1, 50), CNF(40)]); - - let assets = assets1.into_assets_iter().collect::>(); - assert_eq!(assets, vec![AF(1, 50), ANF(2, 20)]); + assert_eq!(taken, vec![CF(300), CNF(40)]); } #[test] fn try_take_all_counted_works() { - let mut assets = Assets::new(); - assets.subsume(AF(1, 100)); - assets.subsume(ANF(2, 20)); + let mut assets = AssetsInHolding::new(); assets.subsume(CNF(40)); - assets.subsume(AF(10, 50)); - assets.subsume(ANF(2, 40)); - assets.subsume(ANF(2, 30)); assets.subsume(CF(3000)); assets.subsume(CNF(80)); - assets.subsume(ANF(3, 10)); - let all = assets.try_take(WildMultiAsset::AllCounted(6).into()).unwrap(); - assert_eq!( - MultiAssets::from(all).inner(), - &vec![CF(3000), AF(1, 100), AF(10, 50), CNF(40), CNF(80), ANF(2, 20),] - ); - assert_eq!(MultiAssets::from(assets).inner(), &vec![ANF(2, 30), ANF(2, 40), ANF(3, 10),]); + let all = assets.try_take(WildAsset::AllCounted(6).into()).unwrap(); + assert_eq!(Assets::from(all).inner(), &vec![CF(3000), CNF(40), CNF(80)]); } #[test] fn try_take_fungibles_counted_works() { - let mut assets = Assets::new(); - assets.subsume(AF(1, 100)); - assets.subsume(ANF(2, 20)); + let mut assets = AssetsInHolding::new(); assets.subsume(CNF(40)); - assets.subsume(AF(10, 50)); - assets.subsume(ANF(2, 40)); - assets.subsume(ANF(2, 30)); assets.subsume(CF(3000)); assets.subsume(CNF(80)); - assets.subsume(ANF(3, 10)); - let mask = WildMultiAsset::from(([1u8; 32], WildFungible)).counted(2).into(); - let taken = assets.try_take(mask).unwrap(); - assert_eq!(MultiAssets::from(taken).inner(), &vec![AF(1, 100)]); - assert_eq!( - MultiAssets::from(assets).inner(), - &vec![ - CF(3000), - AF(10, 50), - CNF(40), - CNF(80), - ANF(2, 20), - ANF(2, 30), - ANF(2, 40), - ANF(3, 10), - ] - ); + assert_eq!(Assets::from(assets).inner(), &vec![CF(3000), CNF(40), CNF(80),]); } #[test] fn try_take_non_fungibles_counted_works() { - let mut assets = Assets::new(); - assets.subsume(AF(1, 100)); - assets.subsume(ANF(2, 20)); + let mut assets = AssetsInHolding::new(); assets.subsume(CNF(40)); - assets.subsume(AF(10, 50)); - assets.subsume(ANF(2, 40)); - assets.subsume(ANF(2, 30)); assets.subsume(CF(3000)); assets.subsume(CNF(80)); - assets.subsume(ANF(3, 10)); - let mask = WildMultiAsset::from(([2u8; 32], WildNonFungible)).counted(2).into(); - let taken = assets.try_take(mask).unwrap(); - assert_eq!(MultiAssets::from(taken).inner(), &vec![ANF(2, 20), ANF(2, 30),]); - assert_eq!( - MultiAssets::from(assets).inner(), - &vec![CF(3000), AF(1, 100), AF(10, 50), CNF(40), CNF(80), ANF(2, 40), ANF(3, 10),] - ); + assert_eq!(Assets::from(assets).inner(), &vec![CF(3000), CNF(40), CNF(80)]); } } diff --git a/polkadot/xcm/xcm-executor/src/config.rs b/polkadot/xcm/xcm-executor/src/config.rs index 2ff12cd7a539..3f1ea6d1fb8e 100644 --- a/polkadot/xcm/xcm-executor/src/config.rs +++ b/polkadot/xcm/xcm-executor/src/config.rs @@ -41,17 +41,17 @@ pub trait Config { type OriginConverter: ConvertOrigin<::RuntimeOrigin>; /// Combinations of (Asset, Location) pairs which we trust as reserves. - type IsReserve: ContainsPair; + type IsReserve: ContainsPair; /// Combinations of (Asset, Location) pairs which we trust as teleporters. - type IsTeleporter: ContainsPair; + type IsTeleporter: ContainsPair; /// A list of (Origin, Target) pairs allowing a given Origin to be substituted with its /// corresponding Target pair. - type Aliasers: ContainsPair; + type Aliasers: ContainsPair; /// This chain's Universal Location. - type UniversalLocation: Get; + type UniversalLocation: Get; /// Whether we should execute the given XCM at all. type Barrier: ShouldExecute; @@ -98,7 +98,7 @@ pub trait Config { /// The origin locations and specific universal junctions to which they are allowed to elevate /// themselves. - type UniversalAliases: Contains<(MultiLocation, Junction)>; + type UniversalAliases: Contains<(Location, Junction)>; /// The call dispatcher used by XCM. /// diff --git a/polkadot/xcm/xcm-executor/src/lib.rs b/polkadot/xcm/xcm-executor/src/lib.rs index ac256ea14899..b36de9527af9 100644 --- a/polkadot/xcm/xcm-executor/src/lib.rs +++ b/polkadot/xcm/xcm-executor/src/lib.rs @@ -36,7 +36,7 @@ use traits::{ }; mod assets; -pub use assets::Assets; +pub use assets::AssetsInHolding; mod config; pub use config::Config; @@ -56,10 +56,10 @@ environmental::environmental!(recursion_count: u8); /// The XCM executor. pub struct XcmExecutor { - holding: Assets, + holding: AssetsInHolding, holding_limit: usize, context: XcmContext, - original_origin: MultiLocation, + original_origin: Location, trader: Config::Trader, /// The most recent error result and instruction index into the fragment in which it occurred, /// if any. @@ -81,10 +81,10 @@ pub struct XcmExecutor { #[cfg(feature = "runtime-benchmarks")] impl XcmExecutor { - pub fn holding(&self) -> &Assets { + pub fn holding(&self) -> &AssetsInHolding { &self.holding } - pub fn set_holding(&mut self, v: Assets) { + pub fn set_holding(&mut self, v: AssetsInHolding) { self.holding = v } pub fn holding_limit(&self) -> &usize { @@ -93,16 +93,16 @@ impl XcmExecutor { pub fn set_holding_limit(&mut self, v: usize) { self.holding_limit = v } - pub fn origin(&self) -> &Option { + pub fn origin(&self) -> &Option { &self.context.origin } - pub fn set_origin(&mut self, v: Option) { + pub fn set_origin(&mut self, v: Option) { self.context.origin = v } - pub fn original_origin(&self) -> &MultiLocation { + pub fn original_origin(&self) -> &Location { &self.original_origin } - pub fn set_original_origin(&mut self, v: MultiLocation) { + pub fn set_original_origin(&mut self, v: Location) { self.original_origin = v } pub fn trader(&self) -> &Config::Trader { @@ -191,14 +191,14 @@ impl ExecuteXcm for XcmExecutor, + origin: impl Into, WeighedMessage(xcm_weight, mut message): WeighedMessage, id: &mut XcmHash, weight_credit: Weight, ) -> Outcome { let origin = origin.into(); log::trace!( - target: "xcm::execute_xcm_in_credit", + target: "xcm::execute", "origin: {:?}, message: {:?}, weight_credit: {:?}", origin, message, @@ -212,14 +212,14 @@ impl ExecuteXcm for XcmExecutor ExecuteXcm for XcmExecutor ExecuteXcm for XcmExecutor, fees: MultiAssets) -> XcmResult { + fn charge_fees(origin: impl Into, fees: Assets) -> XcmResult { let origin = origin.into(); if !Config::FeeManager::is_waived(Some(&origin), FeeReason::ChargeFees) { for asset in fees.inner() { @@ -281,12 +281,12 @@ impl From for frame_benchmarking::BenchmarkError { } impl XcmExecutor { - pub fn new(origin: impl Into, message_id: XcmHash) -> Self { + pub fn new(origin: impl Into, message_id: XcmHash) -> Self { let origin = origin.into(); Self { - holding: Assets::new(), + holding: AssetsInHolding::new(), holding_limit: Config::MaxAssetsIntoHolding::get() as usize, - context: XcmContext { origin: Some(origin), message_id, topic: None }, + context: XcmContext { origin: Some(origin.clone()), message_id, topic: None }, original_origin: origin, trader: Config::Trader::new(), error: None, @@ -374,7 +374,7 @@ impl XcmExecutor { if !self.holding.is_empty() { log::trace!( - target: "xcm::execute_xcm_in_credit", + target: "xcm::post_process", "Trapping assets in holding register: {:?}, context: {:?} (original_origin: {:?})", self.holding, self.context, self.original_origin, ); @@ -385,28 +385,28 @@ impl XcmExecutor { }; match self.error { - None => Outcome::Complete(weight_used), + None => Outcome::Complete { used: weight_used }, // TODO: #2841 #REALWEIGHT We should deduct the cost of any instructions following // the error which didn't end up being executed. Some((_i, e)) => { - log::trace!(target: "xcm::execute_xcm_in_credit", "Execution errored at {:?}: {:?} (original_origin: {:?})", _i, e, self.original_origin); - Outcome::Incomplete(weight_used, e) + log::trace!(target: "xcm::post_process", "Execution errored at {:?}: {:?} (original_origin: {:?})", _i, e, self.original_origin); + Outcome::Incomplete { used: weight_used, error: e } }, } } - fn origin_ref(&self) -> Option<&MultiLocation> { + fn origin_ref(&self) -> Option<&Location> { self.context.origin.as_ref() } - fn cloned_origin(&self) -> Option { - self.context.origin + fn cloned_origin(&self) -> Option { + self.context.origin.clone() } /// Send an XCM, charging fees from Holding as needed. fn send( &mut self, - dest: MultiLocation, + dest: Location, msg: Xcm<()>, reason: FeeReason, ) -> Result { @@ -438,14 +438,14 @@ impl XcmExecutor { r } - fn subsume_asset(&mut self, asset: MultiAsset) -> Result<(), XcmError> { + fn subsume_asset(&mut self, asset: Asset) -> Result<(), XcmError> { // worst-case, holding.len becomes 2 * holding_limit. ensure!(self.holding.len() < self.holding_limit * 2, XcmError::HoldingWouldOverflow); self.holding.subsume(asset); Ok(()) } - fn subsume_assets(&mut self, assets: Assets) -> Result<(), XcmError> { + fn subsume_assets(&mut self, assets: AssetsInHolding) -> Result<(), XcmError> { // worst-case, holding.len becomes 2 * holding_limit. // this guarantees that if holding.len() == holding_limit and you have holding_limit more // items (which has a best case outcome of holding.len() == holding_limit), then you'll @@ -480,8 +480,8 @@ impl XcmExecutor { ); match instr { WithdrawAsset(assets) => { + let origin = self.cloned_origin().ok_or(XcmError::BadOrigin)?; // Take `assets` from the origin account (on-chain) and place in holding. - let origin = *self.origin_ref().ok_or(XcmError::BadOrigin)?; for asset in assets.into_inner().into_iter() { Config::AssetTransactor::withdraw_asset(&asset, &origin, Some(&self.context))?; self.subsume_asset(asset)?; @@ -490,8 +490,8 @@ impl XcmExecutor { }, ReserveAssetDeposited(assets) => { // check whether we trust origin to be our reserve location for this asset. - let origin = *self.origin_ref().ok_or(XcmError::BadOrigin)?; for asset in assets.into_inner().into_iter() { + let origin = self.cloned_origin().ok_or(XcmError::BadOrigin)?; // Must ensure that we recognise the asset as being managed by the origin. ensure!( Config::IsReserve::contains(&asset, &origin), @@ -521,14 +521,14 @@ impl XcmExecutor { Config::AssetTransactor::transfer_asset(asset, origin, &dest, &self.context)?; } let reanchor_context = Config::UniversalLocation::get(); - assets.reanchor(&dest, reanchor_context).map_err(|()| XcmError::LocationFull)?; + assets.reanchor(&dest, &reanchor_context).map_err(|()| XcmError::LocationFull)?; let mut message = vec![ReserveAssetDeposited(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); self.send(dest, Xcm(message), FeeReason::TransferReserveAsset)?; Ok(()) }, ReceiveTeleportedAsset(assets) => { - let origin = *self.origin_ref().ok_or(XcmError::BadOrigin)?; + let origin = self.cloned_origin().ok_or(XcmError::BadOrigin)?; // check whether we trust origin to teleport this asset to us via config trait. for asset in assets.inner() { // We only trust the origin to send us assets that they identify as their @@ -544,6 +544,7 @@ impl XcmExecutor { Config::AssetTransactor::can_check_in(&origin, asset, &self.context)?; } for asset in assets.into_inner().into_iter() { + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; Config::AssetTransactor::check_in(&origin, &asset, &self.context); self.subsume_asset(asset)?; } @@ -551,7 +552,7 @@ impl XcmExecutor { }, Transact { origin_kind, require_weight_at_most, mut call } => { // We assume that the Relay-chain is allowed to use transact on this parachain. - let origin = *self.origin_ref().ok_or(XcmError::BadOrigin)?; + let origin = self.cloned_origin().ok_or(XcmError::BadOrigin)?; // TODO: #2841 #TRANSACTFILTER allow the trait to issue filters for the relay-chain let message_call = call.take_decoded().map_err(|_| XcmError::FailedToDecode)?; @@ -822,12 +823,12 @@ impl XcmExecutor { UniversalOrigin(new_global) => { let universal_location = Config::UniversalLocation::get(); ensure!(universal_location.first() != Some(&new_global), XcmError::InvalidLocation); - let origin = *self.origin_ref().ok_or(XcmError::BadOrigin)?; + let origin = self.cloned_origin().ok_or(XcmError::BadOrigin)?; let origin_xform = (origin, new_global); let ok = Config::UniversalAliases::contains(&origin_xform); ensure!(ok, XcmError::InvalidLocation); let (_, new_global) = origin_xform; - let new_origin = X1(new_global).relative_to(&universal_location); + let new_origin = Junctions::from([new_global]).relative_to(&universal_location); self.context.origin = Some(new_origin); Ok(()) }, @@ -841,7 +842,7 @@ impl XcmExecutor { // // This only works because the remote chain empowers the bridge // to speak for the local network. - let origin = self.context.origin.ok_or(XcmError::BadOrigin)?; + let origin = self.context.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); let universal_source = Config::UniversalLocation::get() .within_global(origin) .map_err(|()| XcmError::Unanchored)?; @@ -854,7 +855,7 @@ impl XcmExecutor { network, channel, universal_source, - destination, + destination.clone(), xcm, )?; self.take_fee(fee, FeeReason::Export { network, destination })?; @@ -862,11 +863,12 @@ impl XcmExecutor { Ok(()) }, LockAsset { asset, unlocker } => { - let origin = *self.origin_ref().ok_or(XcmError::BadOrigin)?; + let origin = self.cloned_origin().ok_or(XcmError::BadOrigin)?; let (remote_asset, context) = Self::try_reanchor(asset.clone(), &unlocker)?; - let lock_ticket = Config::AssetLocker::prepare_lock(unlocker, asset, origin)?; + let lock_ticket = + Config::AssetLocker::prepare_lock(unlocker.clone(), asset, origin.clone())?; let owner = - origin.reanchored(&unlocker, context).map_err(|_| XcmError::ReanchorFailed)?; + origin.reanchored(&unlocker, &context).map_err(|_| XcmError::ReanchorFailed)?; let msg = Xcm::<()>(vec![NoteUnlockable { asset: remote_asset, owner }]); let (ticket, price) = validate_send::(unlocker, msg)?; self.take_fee(price, FeeReason::LockAsset)?; @@ -875,21 +877,24 @@ impl XcmExecutor { Ok(()) }, UnlockAsset { asset, target } => { - let origin = *self.origin_ref().ok_or(XcmError::BadOrigin)?; + let origin = self.cloned_origin().ok_or(XcmError::BadOrigin)?; Config::AssetLocker::prepare_unlock(origin, asset, target)?.enact()?; Ok(()) }, NoteUnlockable { asset, owner } => { - let origin = *self.origin_ref().ok_or(XcmError::BadOrigin)?; + let origin = self.cloned_origin().ok_or(XcmError::BadOrigin)?; Config::AssetLocker::note_unlockable(origin, asset, owner)?; Ok(()) }, RequestUnlock { asset, locker } => { - let origin = *self.origin_ref().ok_or(XcmError::BadOrigin)?; + let origin = self.cloned_origin().ok_or(XcmError::BadOrigin)?; let remote_asset = Self::try_reanchor(asset.clone(), &locker)?.0; - let remote_target = Self::try_reanchor_multilocation(origin, &locker)?.0; - let reduce_ticket = - Config::AssetLocker::prepare_reduce_unlockable(locker, asset, origin)?; + let remote_target = Self::try_reanchor(origin.clone(), &locker)?.0; + let reduce_ticket = Config::AssetLocker::prepare_reduce_unlockable( + locker.clone(), + asset, + origin.clone(), + )?; let msg = Xcm::<()>(vec![UnlockAsset { asset: remote_asset, target: remote_target }]); let (ticket, price) = validate_send::(locker, msg)?; @@ -947,8 +952,8 @@ impl XcmExecutor { } } - fn take_fee(&mut self, fee: MultiAssets, reason: FeeReason) -> XcmResult { - if Config::FeeManager::is_waived(self.origin_ref(), reason) { + fn take_fee(&mut self, fee: Assets, reason: FeeReason) -> XcmResult { + if Config::FeeManager::is_waived(self.origin_ref(), reason.clone()) { return Ok(()) } log::trace!( @@ -974,13 +979,13 @@ impl XcmExecutor { /// Calculates what `local_querier` would be from the perspective of `destination`. fn to_querier( - local_querier: Option, - destination: &MultiLocation, - ) -> Result, XcmError> { + local_querier: Option, + destination: &Location, + ) -> Result, XcmError> { Ok(match local_querier { None => None, Some(q) => Some( - q.reanchored(&destination, Config::UniversalLocation::get()) + q.reanchored(&destination, &Config::UniversalLocation::get()) .map_err(|_| XcmError::ReanchorFailed)?, ), }) @@ -991,7 +996,7 @@ impl XcmExecutor { /// The `local_querier` argument is the querier (if any) specified from the *local* perspective. fn respond( &mut self, - local_querier: Option, + local_querier: Option, response: Response, info: QueryResponseInfo, fee_reason: FeeReason, @@ -1003,36 +1008,25 @@ impl XcmExecutor { self.send(destination, message, fee_reason) } - fn try_reanchor( - asset: MultiAsset, - destination: &MultiLocation, - ) -> Result<(MultiAsset, InteriorMultiLocation), XcmError> { - let reanchor_context = Config::UniversalLocation::get(); - let asset = asset - .reanchored(&destination, reanchor_context) - .map_err(|()| XcmError::ReanchorFailed)?; - Ok((asset, reanchor_context)) - } - - fn try_reanchor_multilocation( - location: MultiLocation, - destination: &MultiLocation, - ) -> Result<(MultiLocation, InteriorMultiLocation), XcmError> { + fn try_reanchor( + reanchorable: T, + destination: &Location, + ) -> Result<(T, InteriorLocation), XcmError> { let reanchor_context = Config::UniversalLocation::get(); - let location = location - .reanchored(&destination, reanchor_context) + let reanchored = reanchorable + .reanchored(&destination, &reanchor_context) .map_err(|_| XcmError::ReanchorFailed)?; - Ok((location, reanchor_context)) + Ok((reanchored, reanchor_context)) } /// NOTE: Any assets which were unable to be reanchored are introduced into `failed_bin`. fn reanchored( - mut assets: Assets, - dest: &MultiLocation, - maybe_failed_bin: Option<&mut Assets>, - ) -> MultiAssets { + mut assets: AssetsInHolding, + dest: &Location, + maybe_failed_bin: Option<&mut AssetsInHolding>, + ) -> Assets { let reanchor_context = Config::UniversalLocation::get(); - assets.reanchor(dest, reanchor_context, maybe_failed_bin); + assets.reanchor(dest, &reanchor_context, maybe_failed_bin); assets.into_assets_iter().collect::>().into() } } diff --git a/polkadot/xcm/xcm-executor/src/traits/asset_exchange.rs b/polkadot/xcm/xcm-executor/src/traits/asset_exchange.rs index 0cb188d348de..432a7498ed4c 100644 --- a/polkadot/xcm/xcm-executor/src/traits/asset_exchange.rs +++ b/polkadot/xcm/xcm-executor/src/traits/asset_exchange.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use crate::Assets; +use crate::AssetsInHolding; use xcm::prelude::*; /// A service for exchanging assets. @@ -32,21 +32,21 @@ pub trait AssetExchange { /// least want must be in the set. Some assets originally in `give` may also be in this set. In /// the case of returning an `Err`, then `give` is returned. fn exchange_asset( - origin: Option<&MultiLocation>, - give: Assets, - want: &MultiAssets, + origin: Option<&Location>, + give: AssetsInHolding, + want: &Assets, maximal: bool, - ) -> Result; + ) -> Result; } #[impl_trait_for_tuples::impl_for_tuples(30)] impl AssetExchange for Tuple { fn exchange_asset( - origin: Option<&MultiLocation>, - give: Assets, - want: &MultiAssets, + origin: Option<&Location>, + give: AssetsInHolding, + want: &Assets, maximal: bool, - ) -> Result { + ) -> Result { for_tuples!( #( let give = match Tuple::exchange_asset(origin, give, want, maximal) { Ok(r) => return Ok(r), diff --git a/polkadot/xcm/xcm-executor/src/traits/asset_lock.rs b/polkadot/xcm/xcm-executor/src/traits/asset_lock.rs index b5a2b22f5fc5..b6270c529452 100644 --- a/polkadot/xcm/xcm-executor/src/traits/asset_lock.rs +++ b/polkadot/xcm/xcm-executor/src/traits/asset_lock.rs @@ -79,9 +79,9 @@ pub trait AssetLock { /// WARNING: Don't call this with an undropped instance of `Self::LockTicket` or /// `Self::UnlockTicket`. fn prepare_lock( - unlocker: MultiLocation, - asset: MultiAsset, - owner: MultiLocation, + unlocker: Location, + asset: Asset, + owner: Location, ) -> Result; /// Prepare to unlock an asset. On success, a `Self::UnlockTicket` it returned, which can be @@ -90,9 +90,9 @@ pub trait AssetLock { /// WARNING: Don't call this with an undropped instance of `Self::LockTicket` or /// `Self::UnlockTicket`. fn prepare_unlock( - locker: MultiLocation, - asset: MultiAsset, - owner: MultiLocation, + locker: Location, + asset: Asset, + owner: Location, ) -> Result; /// Handler for when a location reports to us that an asset has been locked for us to unlock @@ -102,11 +102,7 @@ pub trait AssetLock { /// sending chain can ensure the lock does not remain. /// /// We should only act upon this message if we believe that the `origin` is honest. - fn note_unlockable( - locker: MultiLocation, - asset: MultiAsset, - owner: MultiLocation, - ) -> Result<(), LockError>; + fn note_unlockable(locker: Location, asset: Asset, owner: Location) -> Result<(), LockError>; /// Handler for when an owner wishes to unlock an asset on a remote chain. /// @@ -115,9 +111,9 @@ pub trait AssetLock { /// /// WARNING: Don't call this with an undropped instance of `Self::ReduceTicket`. fn prepare_reduce_unlockable( - locker: MultiLocation, - asset: MultiAsset, - owner: MultiLocation, + locker: Location, + asset: Asset, + owner: Location, ) -> Result; } @@ -125,27 +121,19 @@ impl AssetLock for () { type LockTicket = Infallible; type UnlockTicket = Infallible; type ReduceTicket = Infallible; - fn prepare_lock( - _: MultiLocation, - _: MultiAsset, - _: MultiLocation, - ) -> Result { + fn prepare_lock(_: Location, _: Asset, _: Location) -> Result { Err(LockError::NotApplicable) } - fn prepare_unlock( - _: MultiLocation, - _: MultiAsset, - _: MultiLocation, - ) -> Result { + fn prepare_unlock(_: Location, _: Asset, _: Location) -> Result { Err(LockError::NotApplicable) } - fn note_unlockable(_: MultiLocation, _: MultiAsset, _: MultiLocation) -> Result<(), LockError> { + fn note_unlockable(_: Location, _: Asset, _: Location) -> Result<(), LockError> { Err(LockError::NotApplicable) } fn prepare_reduce_unlockable( - _: MultiLocation, - _: MultiAsset, - _: MultiLocation, + _: Location, + _: Asset, + _: Location, ) -> Result { Err(LockError::NotApplicable) } diff --git a/polkadot/xcm/xcm-executor/src/traits/asset_transfer.rs b/polkadot/xcm/xcm-executor/src/traits/asset_transfer.rs index 5fdc9b15e015..1fca84f36e22 100644 --- a/polkadot/xcm/xcm-executor/src/traits/asset_transfer.rs +++ b/polkadot/xcm/xcm-executor/src/traits/asset_transfer.rs @@ -30,7 +30,7 @@ pub enum Error { } /// Specify which type of asset transfer is required for a particular `(asset, dest)` combination. -#[derive(Copy, Clone, PartialEq, Debug)] +#[derive(Clone, PartialEq, Debug)] pub enum TransferType { /// should teleport `asset` to `dest` Teleport, @@ -38,8 +38,8 @@ pub enum TransferType { LocalReserve, /// should reserve-transfer `asset` to `dest`, using `dest` as reserve DestinationReserve, - /// should reserve-transfer `asset` to `dest`, using remote chain `MultiLocation` as reserve - RemoteReserve(MultiLocation), + /// should reserve-transfer `asset` to `dest`, using remote chain `Location` as reserve + RemoteReserve(Location), } /// A trait for identifying asset transfer type based on `IsTeleporter` and `IsReserve` @@ -47,17 +47,17 @@ pub enum TransferType { pub trait XcmAssetTransfers { /// Combinations of (Asset, Location) pairs which we trust as reserves. Meaning /// reserve-based-transfers are to be used for assets matching this filter. - type IsReserve: ContainsPair; + type IsReserve: ContainsPair; /// Combinations of (Asset, Location) pairs which we trust as teleporters. Meaning teleports are /// to be used for assets matching this filter. - type IsTeleporter: ContainsPair; + type IsTeleporter: ContainsPair; /// How to withdraw and deposit an asset. type AssetTransactor: TransactAsset; /// Determine transfer type to be used for transferring `asset` from local chain to `dest`. - fn determine_for(asset: &MultiAsset, dest: &MultiLocation) -> Result { + fn determine_for(asset: &Asset, dest: &Location) -> Result { if Self::IsTeleporter::contains(asset, dest) { // we trust destination for teleporting asset return Ok(TransferType::Teleport) @@ -67,11 +67,8 @@ pub trait XcmAssetTransfers { } // try to determine reserve location based on asset id/location - let asset_location = match asset.id { - Concrete(location) => Ok(location.chain_location()), - _ => Err(Error::NotConcrete), - }?; - if asset_location == MultiLocation::here() || + let asset_location = asset.id.0.chain_location(); + if asset_location == Location::here() || Self::IsTeleporter::contains(asset, &asset_location) { // if the asset is local, then it's a local reserve diff --git a/polkadot/xcm/xcm-executor/src/traits/conversion.rs b/polkadot/xcm/xcm-executor/src/traits/conversion.rs index 1fcdf2140578..9e2f4c83997a 100644 --- a/polkadot/xcm/xcm-executor/src/traits/conversion.rs +++ b/polkadot/xcm/xcm-executor/src/traits/conversion.rs @@ -22,12 +22,12 @@ use xcm::latest::prelude::*; /// Means of converting a location into an account identifier. pub trait ConvertLocation { /// Convert the `location` into `Some` account ID, or `None` if not possible. - fn convert_location(location: &MultiLocation) -> Option; + fn convert_location(location: &Location) -> Option; } #[impl_trait_for_tuples::impl_for_tuples(30)] impl ConvertLocation for Tuple { - fn convert_location(l: &MultiLocation) -> Option { + fn convert_location(l: &Location) -> Option { for_tuples!( #( match Tuple::convert_location(l) { Some(result) => return Some(result), @@ -45,15 +45,15 @@ impl ConvertLocation for Tuple { /// different `origin` of type `Origin` which is passed to the next convert item. /// /// ```rust -/// # use xcm::latest::{MultiLocation, Junctions, Junction, OriginKind}; +/// # use xcm::latest::{Location, Junctions, Junction, OriginKind}; /// # use staging_xcm_executor::traits::ConvertOrigin; /// // A convertor that will bump the para id and pass it to the next one. /// struct BumpParaId; /// impl ConvertOrigin for BumpParaId { -/// fn convert_origin(origin: impl Into, _: OriginKind) -> Result { -/// match origin.into() { -/// MultiLocation { parents: 0, interior: Junctions::X1(Junction::Parachain(id)) } => { -/// Err(Junctions::X1(Junction::Parachain(id + 1)).into()) +/// fn convert_origin(origin: impl Into, _: OriginKind) -> Result { +/// match origin.into().unpack() { +/// (0, [Junction::Parachain(id)]) => { +/// Err([Junction::Parachain(id + 1)].into()) /// } /// _ => unreachable!() /// } @@ -62,17 +62,18 @@ impl ConvertLocation for Tuple { /// /// struct AcceptPara7; /// impl ConvertOrigin for AcceptPara7 { -/// fn convert_origin(origin: impl Into, _: OriginKind) -> Result { -/// match origin.into() { -/// MultiLocation { parents: 0, interior: Junctions::X1(Junction::Parachain(id)) } if id == 7 => { +/// fn convert_origin(origin: impl Into, _: OriginKind) -> Result { +/// let origin = origin.into(); +/// match origin.unpack() { +/// (0, [Junction::Parachain(id)]) if *id == 7 => { /// Ok(7) /// } -/// o => Err(o) +/// _ => Err(origin) /// } /// } /// } /// # fn main() { -/// let origin: MultiLocation = Junctions::X1(Junction::Parachain(6)).into(); +/// let origin: Location = [Junction::Parachain(6)].into(); /// assert!( /// <(BumpParaId, AcceptPara7) as ConvertOrigin>::convert_origin(origin, OriginKind::Native) /// .is_ok() @@ -81,18 +82,12 @@ impl ConvertLocation for Tuple { /// ``` pub trait ConvertOrigin { /// Attempt to convert `origin` to the generic `Origin` whilst consuming it. - fn convert_origin( - origin: impl Into, - kind: OriginKind, - ) -> Result; + fn convert_origin(origin: impl Into, kind: OriginKind) -> Result; } #[impl_trait_for_tuples::impl_for_tuples(30)] impl ConvertOrigin for Tuple { - fn convert_origin( - origin: impl Into, - kind: OriginKind, - ) -> Result { + fn convert_origin(origin: impl Into, kind: OriginKind) -> Result { for_tuples!( #( let origin = match Tuple::convert_origin(origin, kind) { Err(o) => o, diff --git a/polkadot/xcm/xcm-executor/src/traits/drop_assets.rs b/polkadot/xcm/xcm-executor/src/traits/drop_assets.rs index 9753f3a4213f..339d485d9795 100644 --- a/polkadot/xcm/xcm-executor/src/traits/drop_assets.rs +++ b/polkadot/xcm/xcm-executor/src/traits/drop_assets.rs @@ -14,28 +14,28 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use crate::Assets; +use crate::AssetsInHolding; use core::marker::PhantomData; use frame_support::traits::Contains; -use xcm::latest::{MultiAssets, MultiLocation, Weight, XcmContext}; +use xcm::latest::{Assets, Location, Weight, XcmContext}; -/// Define a handler for when some non-empty `Assets` value should be dropped. +/// Define a handler for when some non-empty `AssetsInHolding` value should be dropped. pub trait DropAssets { /// Handler for receiving dropped assets. Returns the weight consumed by this operation. - fn drop_assets(origin: &MultiLocation, assets: Assets, context: &XcmContext) -> Weight; + fn drop_assets(origin: &Location, assets: AssetsInHolding, context: &XcmContext) -> Weight; } impl DropAssets for () { - fn drop_assets(_origin: &MultiLocation, _assets: Assets, _context: &XcmContext) -> Weight { + fn drop_assets(_origin: &Location, _assets: AssetsInHolding, _context: &XcmContext) -> Weight { Weight::zero() } } /// Morph a given `DropAssets` implementation into one which can filter based on assets. This can -/// be used to ensure that `Assets` values which hold no value are ignored. +/// be used to ensure that `AssetsInHolding` values which hold no value are ignored. pub struct FilterAssets(PhantomData<(D, A)>); -impl> DropAssets for FilterAssets { - fn drop_assets(origin: &MultiLocation, assets: Assets, context: &XcmContext) -> Weight { +impl> DropAssets for FilterAssets { + fn drop_assets(origin: &Location, assets: AssetsInHolding, context: &XcmContext) -> Weight { if A::contains(&assets) { D::drop_assets(origin, assets, context) } else { @@ -49,8 +49,8 @@ impl> DropAssets for FilterAssets { /// asset trap facility don't get to use it. pub struct FilterOrigin(PhantomData<(D, O)>); -impl> DropAssets for FilterOrigin { - fn drop_assets(origin: &MultiLocation, assets: Assets, context: &XcmContext) -> Weight { +impl> DropAssets for FilterOrigin { + fn drop_assets(origin: &Location, assets: AssetsInHolding, context: &XcmContext) -> Weight { if O::contains(origin) { D::drop_assets(origin, assets, context) } else { @@ -64,9 +64,9 @@ pub trait ClaimAssets { /// Claim any assets available to `origin` and return them in a single `Assets` value, together /// with the weight used by this operation. fn claim_assets( - origin: &MultiLocation, - ticket: &MultiLocation, - what: &MultiAssets, + origin: &Location, + ticket: &Location, + what: &Assets, context: &XcmContext, ) -> bool; } @@ -74,9 +74,9 @@ pub trait ClaimAssets { #[impl_trait_for_tuples::impl_for_tuples(30)] impl ClaimAssets for Tuple { fn claim_assets( - origin: &MultiLocation, - ticket: &MultiLocation, - what: &MultiAssets, + origin: &Location, + ticket: &Location, + what: &Assets, context: &XcmContext, ) -> bool { for_tuples!( #( diff --git a/polkadot/xcm/xcm-executor/src/traits/export.rs b/polkadot/xcm/xcm-executor/src/traits/export.rs index 7aeccd44566a..78aa68ce2644 100644 --- a/polkadot/xcm/xcm-executor/src/traits/export.rs +++ b/polkadot/xcm/xcm-executor/src/traits/export.rs @@ -51,8 +51,8 @@ pub trait ExportXcm { fn validate( network: NetworkId, channel: u32, - universal_source: &mut Option, - destination: &mut Option, + universal_source: &mut Option, + destination: &mut Option, message: &mut Option>, ) -> SendResult; @@ -71,11 +71,11 @@ impl ExportXcm for Tuple { fn validate( network: NetworkId, channel: u32, - universal_source: &mut Option, - destination: &mut Option, + universal_source: &mut Option, + destination: &mut Option, message: &mut Option>, ) -> SendResult { - let mut maybe_cost: Option = None; + let mut maybe_cost: Option = None; let one_ticket: Self::Ticket = (for_tuples! { #( if maybe_cost.is_some() { None @@ -112,8 +112,8 @@ impl ExportXcm for Tuple { pub fn validate_export( network: NetworkId, channel: u32, - universal_source: InteriorMultiLocation, - dest: InteriorMultiLocation, + universal_source: InteriorLocation, + dest: InteriorLocation, msg: Xcm<()>, ) -> SendResult { T::validate(network, channel, &mut Some(universal_source), &mut Some(dest), &mut Some(msg)) @@ -130,10 +130,10 @@ pub fn validate_export( pub fn export_xcm( network: NetworkId, channel: u32, - universal_source: InteriorMultiLocation, - dest: InteriorMultiLocation, + universal_source: InteriorLocation, + dest: InteriorLocation, msg: Xcm<()>, -) -> Result<(XcmHash, MultiAssets), SendError> { +) -> Result<(XcmHash, Assets), SendError> { let (ticket, price) = T::validate( network, channel, diff --git a/polkadot/xcm/xcm-executor/src/traits/fee_manager.rs b/polkadot/xcm/xcm-executor/src/traits/fee_manager.rs index d7146457f3b9..b6e303daaad8 100644 --- a/polkadot/xcm/xcm-executor/src/traits/fee_manager.rs +++ b/polkadot/xcm/xcm-executor/src/traits/fee_manager.rs @@ -19,15 +19,15 @@ use xcm::prelude::*; /// Handle stuff to do with taking fees in certain XCM instructions. pub trait FeeManager { /// Determine if a fee should be waived. - fn is_waived(origin: Option<&MultiLocation>, r: FeeReason) -> bool; + fn is_waived(origin: Option<&Location>, r: FeeReason) -> bool; /// Do something with the fee which has been paid. Doing nothing here silently burns the /// fees. - fn handle_fee(fee: MultiAssets, context: Option<&XcmContext>, r: FeeReason); + fn handle_fee(fee: Assets, context: Option<&XcmContext>, r: FeeReason); } /// Context under which a fee is paid. -#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq)] pub enum FeeReason { /// When a reporting instruction is called. Report, @@ -42,7 +42,7 @@ pub enum FeeReason { /// When the `QueryPallet` instruction is called. QueryPallet, /// When the `ExportMessage` instruction is called (and includes the network ID). - Export { network: NetworkId, destination: InteriorMultiLocation }, + Export { network: NetworkId, destination: InteriorLocation }, /// The `charge_fees` API. ChargeFees, /// When the `LockAsset` instruction is called. @@ -52,9 +52,9 @@ pub enum FeeReason { } impl FeeManager for () { - fn is_waived(_: Option<&MultiLocation>, _: FeeReason) -> bool { + fn is_waived(_: Option<&Location>, _: FeeReason) -> bool { false } - fn handle_fee(_: MultiAssets, _: Option<&XcmContext>, _: FeeReason) {} + fn handle_fee(_: Assets, _: Option<&XcmContext>, _: FeeReason) {} } diff --git a/polkadot/xcm/xcm-executor/src/traits/filter_asset_location.rs b/polkadot/xcm/xcm-executor/src/traits/filter_asset_location.rs index b162a8b0729d..5d0c32890be9 100644 --- a/polkadot/xcm/xcm-executor/src/traits/filter_asset_location.rs +++ b/polkadot/xcm/xcm-executor/src/traits/filter_asset_location.rs @@ -15,21 +15,21 @@ // along with Polkadot. If not, see . use frame_support::traits::ContainsPair; -use xcm::latest::{MultiAsset, MultiLocation}; +use xcm::latest::{Asset, Location}; /// Filters assets/location pairs. /// /// Can be amalgamated into tuples. If any item returns `true`, it short-circuits, else `false` is /// returned. -#[deprecated = "Use `frame_support::traits::ContainsPair` instead"] +#[deprecated = "Use `frame_support::traits::ContainsPair` instead"] pub trait FilterAssetLocation { /// A filter to distinguish between asset/location pairs. - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool; + fn contains(asset: &Asset, origin: &Location) -> bool; } #[allow(deprecated)] -impl> FilterAssetLocation for T { - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool { +impl> FilterAssetLocation for T { + fn contains(asset: &Asset, origin: &Location) -> bool { T::contains(asset, origin) } } diff --git a/polkadot/xcm/xcm-executor/src/traits/on_response.rs b/polkadot/xcm/xcm-executor/src/traits/on_response.rs index ea41f242a97d..952bd2d0040a 100644 --- a/polkadot/xcm/xcm-executor/src/traits/on_response.rs +++ b/polkadot/xcm/xcm-executor/src/traits/on_response.rs @@ -24,42 +24,34 @@ use parity_scale_codec::{Decode, Encode, FullCodec, MaxEncodedLen}; use sp_arithmetic::traits::Zero; use sp_std::fmt::Debug; use xcm::latest::{ - Error as XcmError, InteriorMultiLocation, MultiLocation, QueryId, Response, - Result as XcmResult, Weight, XcmContext, + Error as XcmError, InteriorLocation, Location, QueryId, Response, Result as XcmResult, Weight, + XcmContext, }; /// Define what needs to be done upon receiving a query response. pub trait OnResponse { /// Returns `true` if we are expecting a response from `origin` for query `query_id` that was /// queried by `querier`. - fn expecting_response( - origin: &MultiLocation, - query_id: u64, - querier: Option<&MultiLocation>, - ) -> bool; + fn expecting_response(origin: &Location, query_id: u64, querier: Option<&Location>) -> bool; /// Handler for receiving a `response` from `origin` relating to `query_id` initiated by /// `querier`. fn on_response( - origin: &MultiLocation, + origin: &Location, query_id: u64, - querier: Option<&MultiLocation>, + querier: Option<&Location>, response: Response, max_weight: Weight, context: &XcmContext, ) -> Weight; } impl OnResponse for () { - fn expecting_response( - _origin: &MultiLocation, - _query_id: u64, - _querier: Option<&MultiLocation>, - ) -> bool { + fn expecting_response(_origin: &Location, _query_id: u64, _querier: Option<&Location>) -> bool { false } fn on_response( - _origin: &MultiLocation, + _origin: &Location, _query_id: u64, - _querier: Option<&MultiLocation>, + _querier: Option<&Location>, _response: Response, _max_weight: Weight, _context: &XcmContext, @@ -79,7 +71,7 @@ pub trait VersionChangeNotifier { /// If the `location` has an ongoing notification and when this function is called, then an /// error should be returned. fn start( - location: &MultiLocation, + location: &Location, query_id: QueryId, max_weight: Weight, context: &XcmContext, @@ -87,20 +79,20 @@ pub trait VersionChangeNotifier { /// Stop notifying `location` should the XCM change. Returns an error if there is no existing /// notification set up. - fn stop(location: &MultiLocation, context: &XcmContext) -> XcmResult; + fn stop(location: &Location, context: &XcmContext) -> XcmResult; /// Return true if a location is subscribed to XCM version changes. - fn is_subscribed(location: &MultiLocation) -> bool; + fn is_subscribed(location: &Location) -> bool; } impl VersionChangeNotifier for () { - fn start(_: &MultiLocation, _: QueryId, _: Weight, _: &XcmContext) -> XcmResult { + fn start(_: &Location, _: QueryId, _: Weight, _: &XcmContext) -> XcmResult { Err(XcmError::Unimplemented) } - fn stop(_: &MultiLocation, _: &XcmContext) -> XcmResult { + fn stop(_: &Location, _: &XcmContext) -> XcmResult { Err(XcmError::Unimplemented) } - fn is_subscribed(_: &MultiLocation) -> bool { + fn is_subscribed(_: &Location) -> bool { false } } @@ -134,13 +126,13 @@ pub trait QueryHandler { + Copy; type BlockNumber: Zero + Encode; type Error; - type UniversalLocation: Get; + type UniversalLocation: Get; /// Attempt to create a new query ID and register it as a query that is yet to respond. fn new_query( - responder: impl Into, + responder: impl Into, timeout: Self::BlockNumber, - match_querier: impl Into, + match_querier: impl Into, ) -> QueryId; /// Consume `message` and return another which is equivalent to it except that it reports @@ -157,7 +149,7 @@ pub trait QueryHandler { /// The response can be queried with `take_response`. fn report_outcome( message: &mut Xcm<()>, - responder: impl Into, + responder: impl Into, timeout: Self::BlockNumber, ) -> result::Result; @@ -170,7 +162,7 @@ pub trait QueryHandler { } parameter_types! { - pub UniversalLocation: InteriorMultiLocation = Here; + pub UniversalLocation: InteriorLocation = Here; } impl QueryHandler for () { @@ -183,16 +175,16 @@ impl QueryHandler for () { QueryResponseStatus::NotFound } fn new_query( - _responder: impl Into, + _responder: impl Into, _timeout: Self::BlockNumber, - _match_querier: impl Into, + _match_querier: impl Into, ) -> Self::QueryId { 0u64 } fn report_outcome( _message: &mut Xcm<()>, - _responder: impl Into, + _responder: impl Into, _timeout: Self::BlockNumber, ) -> Result { Err(()) diff --git a/polkadot/xcm/xcm-executor/src/traits/should_execute.rs b/polkadot/xcm/xcm-executor/src/traits/should_execute.rs index d85458b54709..449e82b5a6e2 100644 --- a/polkadot/xcm/xcm-executor/src/traits/should_execute.rs +++ b/polkadot/xcm/xcm-executor/src/traits/should_execute.rs @@ -16,7 +16,7 @@ use frame_support::traits::ProcessMessageError; use sp_std::result::Result; -use xcm::latest::{Instruction, MultiLocation, Weight, XcmHash}; +use xcm::latest::{Instruction, Location, Weight, XcmHash}; /// Properyies of an XCM message and its imminent execution. #[derive(Clone, Eq, PartialEq, Debug)] @@ -43,7 +43,7 @@ pub trait ShouldExecute { /// - `properties`: Various pre-established properties of the message which may be mutated by /// this API. fn should_execute( - origin: &MultiLocation, + origin: &Location, instructions: &mut [Instruction], max_weight: Weight, properties: &mut Properties, @@ -53,7 +53,7 @@ pub trait ShouldExecute { #[impl_trait_for_tuples::impl_for_tuples(30)] impl ShouldExecute for Tuple { fn should_execute( - origin: &MultiLocation, + origin: &Location, instructions: &mut [Instruction], max_weight: Weight, properties: &mut Properties, @@ -87,7 +87,7 @@ impl ShouldExecute for Tuple { /// if any of the tuple elements returns true. pub trait CheckSuspension { fn is_suspended( - origin: &MultiLocation, + origin: &Location, instructions: &mut [Instruction], max_weight: Weight, properties: &mut Properties, @@ -97,7 +97,7 @@ pub trait CheckSuspension { #[impl_trait_for_tuples::impl_for_tuples(30)] impl CheckSuspension for Tuple { fn is_suspended( - origin: &MultiLocation, + origin: &Location, instruction: &mut [Instruction], max_weight: Weight, properties: &mut Properties, diff --git a/polkadot/xcm/xcm-executor/src/traits/token_matching.rs b/polkadot/xcm/xcm-executor/src/traits/token_matching.rs index ad65a8630217..e9a7e3ad845d 100644 --- a/polkadot/xcm/xcm-executor/src/traits/token_matching.rs +++ b/polkadot/xcm/xcm-executor/src/traits/token_matching.rs @@ -18,12 +18,12 @@ use sp_std::result; use xcm::latest::prelude::*; pub trait MatchesFungible { - fn matches_fungible(a: &MultiAsset) -> Option; + fn matches_fungible(a: &Asset) -> Option; } #[impl_trait_for_tuples::impl_for_tuples(30)] impl MatchesFungible for Tuple { - fn matches_fungible(a: &MultiAsset) -> Option { + fn matches_fungible(a: &Asset) -> Option { for_tuples!( #( match Tuple::matches_fungible(a) { o @ Some(_) => return o, _ => () } )* ); @@ -33,12 +33,12 @@ impl MatchesFungible for Tuple { } pub trait MatchesNonFungible { - fn matches_nonfungible(a: &MultiAsset) -> Option; + fn matches_nonfungible(a: &Asset) -> Option; } #[impl_trait_for_tuples::impl_for_tuples(30)] impl MatchesNonFungible for Tuple { - fn matches_nonfungible(a: &MultiAsset) -> Option { + fn matches_nonfungible(a: &Asset) -> Option { for_tuples!( #( match Tuple::matches_nonfungible(a) { o @ Some(_) => return o, _ => () } )* ); @@ -52,11 +52,11 @@ impl MatchesNonFungible for Tuple { pub enum Error { /// The given asset is not handled. (According to [`XcmError::AssetNotFound`]) AssetNotHandled, - /// `MultiLocation` to `AccountId` conversion failed. + /// `Location` to `AccountId` conversion failed. AccountIdConversionFailed, /// `u128` amount to currency `Balance` conversion failed. AmountToBalanceConversionFailed, - /// `MultiLocation` to `AssetId`/`ClassId` conversion failed. + /// `Location` to `AssetId`/`ClassId` conversion failed. AssetIdConversionFailed, /// `AssetInstance` to non-fungibles instance ID conversion failed. InstanceConversionFailed, @@ -77,12 +77,12 @@ impl From for XcmError { } pub trait MatchesFungibles { - fn matches_fungibles(a: &MultiAsset) -> result::Result<(AssetId, Balance), Error>; + fn matches_fungibles(a: &Asset) -> result::Result<(AssetId, Balance), Error>; } #[impl_trait_for_tuples::impl_for_tuples(30)] impl MatchesFungibles for Tuple { - fn matches_fungibles(a: &MultiAsset) -> result::Result<(AssetId, Balance), Error> { + fn matches_fungibles(a: &Asset) -> result::Result<(AssetId, Balance), Error> { for_tuples!( #( match Tuple::matches_fungibles(a) { o @ Ok(_) => return o, _ => () } )* ); @@ -92,12 +92,12 @@ impl MatchesFungibles for Tuple { } pub trait MatchesNonFungibles { - fn matches_nonfungibles(a: &MultiAsset) -> result::Result<(AssetId, Instance), Error>; + fn matches_nonfungibles(a: &Asset) -> result::Result<(AssetId, Instance), Error>; } #[impl_trait_for_tuples::impl_for_tuples(30)] impl MatchesNonFungibles for Tuple { - fn matches_nonfungibles(a: &MultiAsset) -> result::Result<(AssetId, Instance), Error> { + fn matches_nonfungibles(a: &Asset) -> result::Result<(AssetId, Instance), Error> { for_tuples!( #( match Tuple::matches_nonfungibles(a) { o @ Ok(_) => return o, _ => () } )* ); diff --git a/polkadot/xcm/xcm-executor/src/traits/transact_asset.rs b/polkadot/xcm/xcm-executor/src/traits/transact_asset.rs index c51befff88a6..f58eaf0bc471 100644 --- a/polkadot/xcm/xcm-executor/src/traits/transact_asset.rs +++ b/polkadot/xcm/xcm-executor/src/traits/transact_asset.rs @@ -14,14 +14,14 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use crate::Assets; +use crate::AssetsInHolding; use sp_std::result::Result; -use xcm::latest::{Error as XcmError, MultiAsset, MultiLocation, Result as XcmResult, XcmContext}; +use xcm::latest::{Asset, Error as XcmError, Location, Result as XcmResult, XcmContext}; /// Facility for asset transacting. /// /// This should work with as many asset/location combinations as possible. Locations to support may -/// include non-account locations such as a `MultiLocation::X1(Junction::Parachain)`. Different +/// include non-account locations such as a `[Junction::Parachain]`. Different /// chains may handle them in different ways. /// /// Can be amalgamated as a tuple of items that implement this trait. In such executions, if any of @@ -31,11 +31,7 @@ pub trait TransactAsset { /// Ensure that `check_in` will do as expected. /// /// When composed as a tuple, all type-items are called and at least one must result in `Ok`. - fn can_check_in( - _origin: &MultiLocation, - _what: &MultiAsset, - _context: &XcmContext, - ) -> XcmResult { + fn can_check_in(_origin: &Location, _what: &Asset, _context: &XcmContext) -> XcmResult { Err(XcmError::Unimplemented) } @@ -56,16 +52,12 @@ pub trait TransactAsset { /// When composed as a tuple, all type-items are called. It is up to the implementer that there /// exists no value for `_what` which can cause side-effects for more than one of the /// type-items. - fn check_in(_origin: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {} + fn check_in(_origin: &Location, _what: &Asset, _context: &XcmContext) {} /// Ensure that `check_out` will do as expected. /// /// When composed as a tuple, all type-items are called and at least one must result in `Ok`. - fn can_check_out( - _dest: &MultiLocation, - _what: &MultiAsset, - _context: &XcmContext, - ) -> XcmResult { + fn can_check_out(_dest: &Location, _what: &Asset, _context: &XcmContext) -> XcmResult { Err(XcmError::Unimplemented) } @@ -82,15 +74,15 @@ pub trait TransactAsset { /// When composed as a tuple, all type-items are called. It is up to the implementer that there /// exists no value for `_what` which can cause side-effects for more than one of the /// type-items. - fn check_out(_dest: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {} + fn check_out(_dest: &Location, _what: &Asset, _context: &XcmContext) {} /// Deposit the `what` asset into the account of `who`. /// /// Implementations should return `XcmError::FailedToTransactAsset` if deposit failed. fn deposit_asset( - _what: &MultiAsset, - _who: &MultiLocation, - _context: Option<&XcmContext>, + _what: &Asset, + _who: &Location, + _context: Option<&XcmContext> ) -> XcmResult { Err(XcmError::Unimplemented) } @@ -104,10 +96,10 @@ pub trait TransactAsset { /// /// Implementations should return `XcmError::FailedToTransactAsset` if withdraw failed. fn withdraw_asset( - _what: &MultiAsset, - _who: &MultiLocation, + _what: &Asset, + _who: &Location, _maybe_context: Option<&XcmContext>, - ) -> Result { + ) -> Result { Err(XcmError::Unimplemented) } @@ -121,11 +113,11 @@ pub trait TransactAsset { /// turn has a default implementation that calls `internal_transfer_asset`. As such, **please /// do not call this method directly unless you know what you're doing**. fn internal_transfer_asset( - _asset: &MultiAsset, - _from: &MultiLocation, - _to: &MultiLocation, + _asset: &Asset, + _from: &Location, + _to: &Location, _context: &XcmContext, - ) -> Result { + ) -> Result { Err(XcmError::Unimplemented) } @@ -134,11 +126,11 @@ pub trait TransactAsset { /// Attempts to use `internal_transfer_asset` and if not available then falls back to using a /// two-part withdraw/deposit. fn transfer_asset( - asset: &MultiAsset, - from: &MultiLocation, - to: &MultiLocation, + asset: &Asset, + from: &Location, + to: &Location, context: &XcmContext, - ) -> Result { + ) -> Result { match Self::internal_transfer_asset(asset, from, to, context) { Err(XcmError::AssetNotFound | XcmError::Unimplemented) => { let assets = Self::withdraw_asset(asset, from, Some(context))?; @@ -153,7 +145,7 @@ pub trait TransactAsset { #[impl_trait_for_tuples::impl_for_tuples(30)] impl TransactAsset for Tuple { - fn can_check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { + fn can_check_in(origin: &Location, what: &Asset, context: &XcmContext) -> XcmResult { for_tuples!( #( match Tuple::can_check_in(origin, what, context) { Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (), @@ -170,13 +162,13 @@ impl TransactAsset for Tuple { Err(XcmError::AssetNotFound) } - fn check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) { + fn check_in(origin: &Location, what: &Asset, context: &XcmContext) { for_tuples!( #( Tuple::check_in(origin, what, context); )* ); } - fn can_check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { + fn can_check_out(dest: &Location, what: &Asset, context: &XcmContext) -> XcmResult { for_tuples!( #( match Tuple::can_check_out(dest, what, context) { Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (), @@ -193,16 +185,16 @@ impl TransactAsset for Tuple { Err(XcmError::AssetNotFound) } - fn check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) { + fn check_out(dest: &Location, what: &Asset, context: &XcmContext) { for_tuples!( #( Tuple::check_out(dest, what, context); )* ); } fn deposit_asset( - what: &MultiAsset, - who: &MultiLocation, - context: Option<&XcmContext>, + what: &Asset, + who: &Location, + context: Option<&XcmContext> ) -> XcmResult { for_tuples!( #( match Tuple::deposit_asset(what, who, context) { @@ -221,10 +213,10 @@ impl TransactAsset for Tuple { } fn withdraw_asset( - what: &MultiAsset, - who: &MultiLocation, + what: &Asset, + who: &Location, maybe_context: Option<&XcmContext>, - ) -> Result { + ) -> Result { for_tuples!( #( match Tuple::withdraw_asset(what, who, maybe_context) { Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (), @@ -242,11 +234,11 @@ impl TransactAsset for Tuple { } fn internal_transfer_asset( - what: &MultiAsset, - from: &MultiLocation, - to: &MultiLocation, + what: &Asset, + from: &Location, + to: &Location, context: &XcmContext, - ) -> Result { + ) -> Result { for_tuples!( #( match Tuple::internal_transfer_asset(what, from, to, context) { Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (), @@ -275,133 +267,109 @@ mod tests { pub struct NotFoundTransactor; impl TransactAsset for NotFoundTransactor { - fn can_check_in( - _origin: &MultiLocation, - _what: &MultiAsset, - _context: &XcmContext, - ) -> XcmResult { + fn can_check_in(_origin: &Location, _what: &Asset, _context: &XcmContext) -> XcmResult { Err(XcmError::AssetNotFound) } - fn can_check_out( - _dest: &MultiLocation, - _what: &MultiAsset, - _context: &XcmContext, - ) -> XcmResult { + fn can_check_out(_dest: &Location, _what: &Asset, _context: &XcmContext) -> XcmResult { Err(XcmError::AssetNotFound) } fn deposit_asset( - _what: &MultiAsset, - _who: &MultiLocation, + _what: &Asset, + _who: &Location, _context: Option<&XcmContext>, ) -> XcmResult { Err(XcmError::AssetNotFound) } fn withdraw_asset( - _what: &MultiAsset, - _who: &MultiLocation, + _what: &Asset, + _who: &Location, _context: Option<&XcmContext>, - ) -> Result { + ) -> Result { Err(XcmError::AssetNotFound) } fn internal_transfer_asset( - _what: &MultiAsset, - _from: &MultiLocation, - _to: &MultiLocation, + _what: &Asset, + _from: &Location, + _to: &Location, _context: &XcmContext, - ) -> Result { + ) -> Result { Err(XcmError::AssetNotFound) } } pub struct OverflowTransactor; impl TransactAsset for OverflowTransactor { - fn can_check_in( - _origin: &MultiLocation, - _what: &MultiAsset, - _context: &XcmContext, - ) -> XcmResult { + fn can_check_in(_origin: &Location, _what: &Asset, _context: &XcmContext) -> XcmResult { Err(XcmError::Overflow) } - fn can_check_out( - _dest: &MultiLocation, - _what: &MultiAsset, - _context: &XcmContext, - ) -> XcmResult { + fn can_check_out(_dest: &Location, _what: &Asset, _context: &XcmContext) -> XcmResult { Err(XcmError::Overflow) } fn deposit_asset( - _what: &MultiAsset, - _who: &MultiLocation, + _what: &Asset, + _who: &Location, _context: Option<&XcmContext>, ) -> XcmResult { Err(XcmError::Overflow) } fn withdraw_asset( - _what: &MultiAsset, - _who: &MultiLocation, + _what: &Asset, + _who: &Location, _context: Option<&XcmContext>, - ) -> Result { + ) -> Result { Err(XcmError::Overflow) } fn internal_transfer_asset( - _what: &MultiAsset, - _from: &MultiLocation, - _to: &MultiLocation, + _what: &Asset, + _from: &Location, + _to: &Location, _context: &XcmContext, - ) -> Result { + ) -> Result { Err(XcmError::Overflow) } } pub struct SuccessfulTransactor; impl TransactAsset for SuccessfulTransactor { - fn can_check_in( - _origin: &MultiLocation, - _what: &MultiAsset, - _context: &XcmContext, - ) -> XcmResult { + fn can_check_in(_origin: &Location, _what: &Asset, _context: &XcmContext) -> XcmResult { Ok(()) } - fn can_check_out( - _dest: &MultiLocation, - _what: &MultiAsset, - _context: &XcmContext, - ) -> XcmResult { + fn can_check_out(_dest: &Location, _what: &Asset, _context: &XcmContext) -> XcmResult { Ok(()) } fn deposit_asset( - _what: &MultiAsset, - _who: &MultiLocation, + _what: &Asset, + _who: &Location, _context: Option<&XcmContext>, ) -> XcmResult { Ok(()) } fn withdraw_asset( - _what: &MultiAsset, - _who: &MultiLocation, + _what: &Asset, + _who: &Location, _context: Option<&XcmContext>, - ) -> Result { - Ok(Assets::default()) + ) -> Result { + Ok(AssetsInHolding::default()) } fn internal_transfer_asset( - _what: &MultiAsset, - _from: &MultiLocation, - _to: &MultiLocation, + _what: &Asset, + _from: &Location, + _to: &Location, _context: &XcmContext, - ) -> Result { - Ok(Assets::default()) + ) -> Result { + Ok(AssetsInHolding::default()) } } diff --git a/polkadot/xcm/xcm-executor/src/traits/weight.rs b/polkadot/xcm/xcm-executor/src/traits/weight.rs index bc40c10074f5..efb9a2dfb6ef 100644 --- a/polkadot/xcm/xcm-executor/src/traits/weight.rs +++ b/polkadot/xcm/xcm-executor/src/traits/weight.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use crate::Assets; +use crate::AssetsInHolding; use sp_std::result::Result; use xcm::latest::{prelude::*, Weight}; @@ -33,7 +33,7 @@ pub trait WeightBounds { /// message. pub trait UniversalWeigher { /// Get the upper limit of weight required for `dest` to execute `message`. - fn weigh(dest: impl Into, message: Xcm<()>) -> Result; + fn weigh(dest: impl Into, message: Xcm<()>) -> Result; } /// Charge for weight in order to execute XCM. @@ -52,15 +52,15 @@ pub trait WeightTrader: Sized { fn buy_weight( &mut self, weight: Weight, - payment: Assets, + payment: AssetsInHolding, context: &XcmContext, - ) -> Result; + ) -> Result; /// Attempt a refund of `weight` into some asset. The caller does not guarantee that the weight /// was purchased using `buy_weight`. /// /// Default implementation refunds nothing. - fn refund_weight(&mut self, _weight: Weight, _context: &XcmContext) -> Option { + fn refund_weight(&mut self, _weight: Weight, _context: &XcmContext) -> Option { None } } @@ -74,9 +74,9 @@ impl WeightTrader for Tuple { fn buy_weight( &mut self, weight: Weight, - payment: Assets, + payment: AssetsInHolding, context: &XcmContext, - ) -> Result { + ) -> Result { let mut too_expensive_error_found = false; let mut last_error = None; for_tuples!( #( @@ -102,7 +102,7 @@ impl WeightTrader for Tuple { }) } - fn refund_weight(&mut self, weight: Weight, context: &XcmContext) -> Option { + fn refund_weight(&mut self, weight: Weight, context: &XcmContext) -> Option { for_tuples!( #( if let Some(asset) = Tuple.refund_weight(weight, context) { return Some(asset); diff --git a/polkadot/xcm/xcm-simulator/example/src/lib.rs b/polkadot/xcm/xcm-simulator/example/src/lib.rs index 03e7c19a9148..d3cd1e6f1f8b 100644 --- a/polkadot/xcm/xcm-simulator/example/src/lib.rs +++ b/polkadot/xcm/xcm-simulator/example/src/lib.rs @@ -148,7 +148,7 @@ mod tests { use xcm_simulator::TestExt; // Helper function for forming buy execution message - fn buy_execution(fees: impl Into) -> Instruction { + fn buy_execution(fees: impl Into) -> Instruction { BuyExecution { fees: fees.into(), weight_limit: Unlimited } } @@ -642,7 +642,7 @@ mod tests { parachain::MsgQueue::received_dmp(), vec![Xcm(vec![QueryResponse { query_id: query_id_set, - response: Response::Assets(MultiAssets::new()), + response: Response::Assets(Assets::new()), max_weight: Weight::from_parts(1_000_000_000, 1024 * 1024), querier: Some(Here.into()), }])], @@ -651,21 +651,8 @@ mod tests { } #[test] - fn builder_pattern_works() { - let asset: MultiAsset = (Here, 100u128).into(); - let beneficiary: MultiLocation = AccountId32 { id: [0u8; 32], network: None }.into(); - let message: Xcm<()> = Xcm::builder() - .withdraw_asset(asset.clone().into()) - .buy_execution(asset.clone(), Unlimited) - .deposit_asset(asset.clone().into(), beneficiary) - .build(); - assert_eq!( - message, - Xcm(vec![ - WithdrawAsset(asset.clone().into()), - BuyExecution { fees: asset.clone(), weight_limit: Unlimited }, - DepositAsset { assets: asset.into(), beneficiary }, - ]) - ); + fn location_conversion_functions() { + let location: Location = (Parent, Parachain(1000), PalletInstance(50), GeneralIndex(1984)).into(); + assert_eq!(location, Location::new(1, [Parachain(1000), PalletInstance(50), GeneralIndex(1984)])); } } diff --git a/polkadot/xcm/xcm-simulator/example/src/parachain.rs b/polkadot/xcm/xcm-simulator/example/src/parachain.rs index 9f0411970ce7..34216d18dff7 100644 --- a/polkadot/xcm/xcm-simulator/example/src/parachain.rs +++ b/polkadot/xcm/xcm-simulator/example/src/parachain.rs @@ -115,8 +115,8 @@ impl pallet_balances::Config for Runtime { #[cfg(feature = "runtime-benchmarks")] pub struct UniquesHelper; #[cfg(feature = "runtime-benchmarks")] -impl pallet_uniques::BenchmarkHelper for UniquesHelper { - fn collection(i: u16) -> MultiLocation { +impl pallet_uniques::BenchmarkHelper for UniquesHelper { + fn collection(i: u16) -> Location { GeneralIndex(i as u128).into() } fn item(i: u16) -> AssetInstance { @@ -126,7 +126,7 @@ impl pallet_uniques::BenchmarkHelper for UniquesHe impl pallet_uniques::Config for Runtime { type RuntimeEvent = RuntimeEvent; - type CollectionId = MultiLocation; + type CollectionId = Location; type ItemId = AssetInstance; type Currency = Balances; type CreateOrigin = ForeignCreators; @@ -148,12 +148,12 @@ impl pallet_uniques::Config for Runtime { // `EnsureOriginWithArg` impl for `CreateOrigin` which allows only XCM origins // which are locations containing the class location. pub struct ForeignCreators; -impl EnsureOriginWithArg for ForeignCreators { +impl EnsureOriginWithArg for ForeignCreators { type Success = AccountId; fn try_origin( o: RuntimeOrigin, - a: &MultiLocation, + a: &Location, ) -> sp_std::result::Result { let origin_location = pallet_xcm::EnsureXcm::::try_origin(o.clone())?; if !a.starts_with(&origin_location) { @@ -163,7 +163,7 @@ impl EnsureOriginWithArg for ForeignCreators { } #[cfg(feature = "runtime-benchmarks")] - fn try_successful_origin(a: &MultiLocation) -> Result { + fn try_successful_origin(a: &Location) -> Result { Ok(pallet_xcm::Origin::Xcm(a.clone()).into()) } } @@ -174,9 +174,9 @@ parameter_types! { } parameter_types! { - pub const KsmLocation: MultiLocation = MultiLocation::parent(); + pub const KsmLocation: Location = Location::parent(); pub const RelayNetwork: NetworkId = NetworkId::Kusama; - pub UniversalLocation: InteriorMultiLocation = Parachain(MsgQueue::parachain_id().into()).into(); + pub UniversalLocation: InteriorLocation = Parachain(MsgQueue::parachain_id().into()).into(); } pub type LocationToAccountId = ( @@ -194,17 +194,17 @@ pub type XcmOriginToCallOrigin = ( parameter_types! { pub const UnitWeightCost: Weight = Weight::from_parts(1, 1); - pub KsmPerSecondPerByte: (AssetId, u128, u128) = (Concrete(Parent.into()), 1, 1); + pub KsmPerSecondPerByte: (AssetId, u128, u128) = (AssetId(Parent.into()), 1, 1); pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 64; - pub ForeignPrefix: MultiLocation = (Parent,).into(); + pub ForeignPrefix: Location = (Parent,).into(); } pub type LocalAssetTransactor = ( XcmCurrencyAdapter, LocationToAccountId, AccountId, ()>, NonFungiblesAdapter< ForeignUniques, - ConvertedConcreteId, + ConvertedConcreteId, SovereignAccountOf, AccountId, NoChecking, @@ -216,9 +216,9 @@ pub type XcmRouter = super::ParachainXcmRouter; pub type Barrier = AllowUnpaidExecutionFrom; parameter_types! { - pub NftCollectionOne: MultiAssetFilter - = Wild(AllOf { fun: WildNonFungible, id: Concrete((Parent, GeneralIndex(1)).into()) }); - pub NftCollectionOneForRelay: (MultiAssetFilter, MultiLocation) + pub NftCollectionOne: AssetFilter + = Wild(AllOf { fun: WildNonFungible, id: AssetId((Parent, GeneralIndex(1)).into()) }); + pub NftCollectionOneForRelay: (AssetFilter, Location) = (NftCollectionOne::get(), (Parent,).into()); } pub type TrustedTeleporters = xcm_builder::Case; @@ -321,16 +321,16 @@ pub mod mock_msg_queue { max_weight: Weight, ) -> Result { let hash = Encode::using_encoded(&xcm, T::Hashing::hash); - let message_hash = Encode::using_encoded(&xcm, sp_io::hashing::blake2_256); + let mut message_hash = Encode::using_encoded(&xcm, sp_io::hashing::blake2_256); let (result, event) = match Xcm::::try_from(xcm) { Ok(xcm) => { let location = (Parent, Parachain(sender.into())); - match T::XcmExecutor::execute_xcm(location, xcm, message_hash, max_weight) { - Outcome::Error(e) => (Err(e), Event::Fail(Some(hash), e)), - Outcome::Complete(w) => (Ok(w), Event::Success(Some(hash))), + match T::XcmExecutor::prepare_and_execute(location, xcm, &mut message_hash, max_weight, Weight::zero()) { + 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(w, e) => (Ok(w), Event::Fail(Some(hash), e)), + Outcome::Incomplete { used, error } => (Ok(used), Event::Fail(Some(hash), error)), } }, Err(()) => (Err(XcmError::UnhandledXcmVersion), Event::BadVersion(Some(hash))), @@ -371,7 +371,7 @@ pub mod mock_msg_queue { limit: Weight, ) -> Weight { for (_i, (_sent_at, data)) in iter.enumerate() { - let id = sp_io::hashing::blake2_256(&data[..]); + let mut id = sp_io::hashing::blake2_256(&data[..]); let maybe_versioned = VersionedXcm::::decode(&mut &data[..]); match maybe_versioned { Err(_) => { @@ -380,7 +380,7 @@ pub mod mock_msg_queue { Ok(versioned) => match Xcm::try_from(versioned) { Err(()) => Self::deposit_event(Event::UnsupportedVersion(id)), Ok(x) => { - let outcome = T::XcmExecutor::execute_xcm(Parent, x.clone(), id, limit); + let outcome = T::XcmExecutor::prepare_and_execute(Parent, x.clone(), &mut id, limit, Weight::zero()); >::append(x); Self::deposit_event(Event::ExecutedDownward(id, outcome)); }, @@ -400,17 +400,15 @@ impl mock_msg_queue::Config for Runtime { pub type LocalOriginToLocation = SignedToAccountId32; pub struct TrustedLockerCase(PhantomData); -impl> ContainsPair - for TrustedLockerCase -{ - fn contains(origin: &MultiLocation, asset: &MultiAsset) -> bool { +impl> ContainsPair for TrustedLockerCase { + fn contains(origin: &Location, asset: &Asset) -> bool { let (o, a) = T::get(); a.matches(asset) && &o == origin } } parameter_types! { - pub RelayTokenForRelay: (MultiLocation, MultiAssetFilter) = (Parent.into(), Wild(AllOf { id: Concrete(Parent.into()), fun: WildFungible })); + pub RelayTokenForRelay: (Location, AssetFilter) = (Parent.into(), Wild(AllOf { id: AssetId(Parent.into()), fun: WildFungible })); } pub type TrustedLockers = TrustedLockerCase; diff --git a/polkadot/xcm/xcm-simulator/example/src/relay_chain.rs b/polkadot/xcm/xcm-simulator/example/src/relay_chain.rs index bdd7ff6d3eaf..6a50045380eb 100644 --- a/polkadot/xcm/xcm-simulator/example/src/relay_chain.rs +++ b/polkadot/xcm/xcm-simulator/example/src/relay_chain.rs @@ -126,10 +126,10 @@ impl configuration::Config for Runtime { } parameter_types! { - pub const TokenLocation: MultiLocation = Here.into_location(); + pub const TokenLocation: Location = Here.into_location(); pub RelayNetwork: NetworkId = ByGenesis([0; 32]); pub const AnyNetwork: Option = None; - pub UniversalLocation: InteriorMultiLocation = Here; + pub UniversalLocation: InteriorLocation = Here; pub UnitWeightCost: u64 = 1_000; } @@ -161,7 +161,7 @@ type LocalOriginConverter = ( parameter_types! { pub const BaseXcmWeight: Weight = Weight::from_parts(1_000, 1_000); pub TokensPerSecondPerByte: (AssetId, u128, u128) = - (Concrete(TokenLocation::get()), 1_000_000_000_000, 1024 * 1024); + (AssetId(TokenLocation::get()), 1_000_000_000_000, 1024 * 1024); pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 64; } diff --git a/polkadot/xcm/xcm-simulator/fuzzer/src/fuzz.rs b/polkadot/xcm/xcm-simulator/fuzzer/src/fuzz.rs index 0893c7c086f8..7026d5467c8b 100644 --- a/polkadot/xcm/xcm-simulator/fuzzer/src/fuzz.rs +++ b/polkadot/xcm/xcm-simulator/fuzzer/src/fuzz.rs @@ -158,7 +158,7 @@ fn run_input(xcm_messages: [XcmMessage; 5]) { if xcm_message.source % 4 == 0 { // We get the destination for the message let parachain_id = (xcm_message.destination % 3) + 1; - let destination: MultiLocation = Parachain(parachain_id).into(); + let destination: Location = Parachain(parachain_id).into(); #[cfg(not(fuzzing))] { println!(" source: Relay Chain"); @@ -176,7 +176,7 @@ fn run_input(xcm_messages: [XcmMessage; 5]) { _ => ParaC::execute_with, }; // We get the destination for the message - let destination: MultiLocation = match xcm_message.destination % 4 { + let destination: Location = match xcm_message.destination % 4 { n @ 1..=3 => (Parent, Parachain(n)).into(), _ => Parent.into(), }; diff --git a/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs b/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs index 41234837aca0..e8a7c5d0aeb7 100644 --- a/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs +++ b/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs @@ -107,9 +107,9 @@ parameter_types! { } parameter_types! { - pub const KsmLocation: MultiLocation = MultiLocation::parent(); + pub const KsmLocation: Location = Location::parent(); pub const RelayNetwork: NetworkId = NetworkId::Kusama; - pub UniversalLocation: InteriorMultiLocation = Parachain(MsgQueue::parachain_id().into()).into(); + pub UniversalLocation: InteriorLocation = Parachain(MsgQueue::parachain_id().into()).into(); } pub type LocationToAccountId = ( @@ -126,7 +126,7 @@ pub type XcmOriginToCallOrigin = ( parameter_types! { pub const UnitWeightCost: Weight = Weight::from_parts(1, 1); - pub KsmPerSecondPerByte: (AssetId, u128, u128) = (Concrete(Parent.into()), 1, 1); + pub KsmPerSecondPerByte: (AssetId, u128, u128) = (AssetId(Parent.into()), 1, 1); pub const MaxInstructions: u32 = 100; pub const MaxAssetsIntoHolding: u32 = 64; } @@ -234,16 +234,16 @@ pub mod mock_msg_queue { max_weight: Weight, ) -> Result { let hash = Encode::using_encoded(&xcm, T::Hashing::hash); - let message_hash = xcm.using_encoded(sp_io::hashing::blake2_256); + let mut message_hash = xcm.using_encoded(sp_io::hashing::blake2_256); let (result, event) = match Xcm::::try_from(xcm) { Ok(xcm) => { - let location = MultiLocation::new(1, X1(Parachain(sender.into()))); - match T::XcmExecutor::execute_xcm(location, xcm, message_hash, max_weight) { - Outcome::Error(e) => (Err(e), Event::Fail(Some(hash), e)), - Outcome::Complete(w) => (Ok(w), Event::Success(Some(hash))), + let location = Location::new(1, [Parachain(sender.into())]); + match T::XcmExecutor::prepare_and_execute(location, xcm, &mut message_hash, max_weight, Weight::zero()) { + 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(w, e) => (Ok(w), Event::Fail(Some(hash), e)), + Outcome::Incomplete { used, error } => (Ok(used), Event::Fail(Some(hash), error)), } }, Err(()) => (Err(XcmError::UnhandledXcmVersion), Event::BadVersion(Some(hash))), @@ -284,7 +284,7 @@ pub mod mock_msg_queue { limit: Weight, ) -> Weight { for (_i, (_sent_at, data)) in iter.enumerate() { - let id = sp_io::hashing::blake2_256(&data[..]); + let mut id = sp_io::hashing::blake2_256(&data[..]); let maybe_msg = VersionedXcm::::decode(&mut &data[..]) .map(Xcm::::try_from); match maybe_msg { @@ -295,7 +295,7 @@ pub mod mock_msg_queue { Self::deposit_event(Event::UnsupportedVersion(id)); }, Ok(Ok(x)) => { - let outcome = T::XcmExecutor::execute_xcm(Parent, x.clone(), id, limit); + let outcome = T::XcmExecutor::prepare_and_execute(Parent, x.clone(), &mut id, limit, Weight::zero()); >::append(x); Self::deposit_event(Event::ExecutedDownward(id, outcome)); }, diff --git a/polkadot/xcm/xcm-simulator/fuzzer/src/relay_chain.rs b/polkadot/xcm/xcm-simulator/fuzzer/src/relay_chain.rs index c9a57db970a7..d638f7572b11 100644 --- a/polkadot/xcm/xcm-simulator/fuzzer/src/relay_chain.rs +++ b/polkadot/xcm/xcm-simulator/fuzzer/src/relay_chain.rs @@ -104,10 +104,10 @@ impl configuration::Config for Runtime { } parameter_types! { - pub const TokenLocation: MultiLocation = Here.into_location(); + pub const TokenLocation: Location = Here.into_location(); pub const ThisNetwork: NetworkId = NetworkId::ByGenesis([0; 32]); pub const AnyNetwork: Option = None; - pub const UniversalLocation: InteriorMultiLocation = Here; + pub const UniversalLocation: InteriorLocation = Here; } pub type SovereignAccountOf = @@ -125,7 +125,7 @@ type LocalOriginConverter = ( parameter_types! { pub const BaseXcmWeight: Weight = Weight::from_parts(1_000, 1_000); - pub KsmPerSecondPerByte: (AssetId, u128, u128) = (Concrete(TokenLocation::get()), 1, 1); + pub KsmPerSecondPerByte: (AssetId, u128, u128) = (AssetId(TokenLocation::get()), 1, 1); pub const MaxInstructions: u32 = u32::MAX; pub const MaxAssetsIntoHolding: u32 = 64; } diff --git a/polkadot/xcm/xcm-simulator/src/lib.rs b/polkadot/xcm/xcm-simulator/src/lib.rs index b38465b3d4a2..6bcd111c2b86 100644 --- a/polkadot/xcm/xcm-simulator/src/lib.rs +++ b/polkadot/xcm/xcm-simulator/src/lib.rs @@ -258,9 +258,9 @@ macro_rules! __impl_ext { } thread_local! { - pub static PARA_MESSAGE_BUS: RefCell)>> + pub static PARA_MESSAGE_BUS: RefCell)>> = RefCell::new(VecDeque::new()); - pub static RELAY_MESSAGE_BUS: RefCell)>> + pub static RELAY_MESSAGE_BUS: RefCell)>> = RefCell::new(VecDeque::new()); } @@ -318,8 +318,8 @@ macro_rules! decl_test_network { while let Some((para_id, destination, message)) = $crate::PARA_MESSAGE_BUS.with( |b| b.borrow_mut().pop_front()) { - match destination.interior() { - $crate::Junctions::Here if destination.parent_count() == 1 => { + match destination.unpack() { + (1, HERE) => { let encoded = $crate::encode_xcm(message, $crate::MessageKind::Ump); let mut _id = [0; 32]; let r = <$relay_chain>::process_message( @@ -336,7 +336,7 @@ macro_rules! decl_test_network { } }, $( - $crate::X1($crate::Parachain(id)) if *id == $para_id && destination.parent_count() == 1 => { + (1, [$crate::Parachain(id)]) if *id == $para_id => { let encoded = $crate::encode_xcm(message, $crate::MessageKind::Xcmp); let messages = vec![(para_id, 1, &encoded[..])]; let _weight = <$parachain>::handle_xcmp_messages( @@ -360,9 +360,9 @@ macro_rules! decl_test_network { while let Some((destination, message)) = $crate::RELAY_MESSAGE_BUS.with( |b| b.borrow_mut().pop_front()) { - match destination.interior() { + match destination.unpack() { $( - $crate::X1($crate::Parachain(id)) if *id == $para_id && destination.parent_count() == 0 => { + (0, [$crate::Parachain(id)]) if *id == $para_id => { let encoded = $crate::encode_xcm(message, $crate::MessageKind::Dmp); // NOTE: RelayChainBlockNumber is hard-coded to 1 let messages = vec![(1, encoded)]; @@ -382,18 +382,18 @@ macro_rules! decl_test_network { pub struct ParachainXcmRouter($crate::PhantomData); impl> $crate::SendXcm for ParachainXcmRouter { - type Ticket = ($crate::ParaId, $crate::MultiLocation, $crate::Xcm<()>); + type Ticket = ($crate::ParaId, $crate::Location, $crate::Xcm<()>); fn validate( - destination: &mut Option<$crate::MultiLocation>, + destination: &mut Option<$crate::Location>, message: &mut Option<$crate::Xcm<()>>, - ) -> $crate::SendResult<($crate::ParaId, $crate::MultiLocation, $crate::Xcm<()>)> { + ) -> $crate::SendResult<($crate::ParaId, $crate::Location, $crate::Xcm<()>)> { use $crate::XcmpMessageHandlerT; let d = destination.take().ok_or($crate::SendError::MissingArgument)?; - match (d.interior(), d.parent_count()) { - ($crate::Junctions::Here, 1) => {}, + match d.unpack() { + (1, HERE) => {}, $( - ($crate::X1($crate::Parachain(id)), 1) if id == &$para_id => {} + (1, [$crate::Parachain(id)]) if id == &$para_id => {} )* _ => { *destination = Some(d); @@ -401,10 +401,10 @@ macro_rules! decl_test_network { }, } let m = message.take().ok_or($crate::SendError::MissingArgument)?; - Ok(((T::get(), d, m), $crate::MultiAssets::new())) + Ok(((T::get(), d, m), $crate::Assets::new())) } fn deliver( - triple: ($crate::ParaId, $crate::MultiLocation, $crate::Xcm<()>), + triple: ($crate::ParaId, $crate::Location, $crate::Xcm<()>), ) -> Result<$crate::XcmHash, $crate::SendError> { let hash = $crate::fake_message_hash(&triple.2); $crate::PARA_MESSAGE_BUS.with(|b| b.borrow_mut().push_back(triple)); @@ -415,17 +415,17 @@ macro_rules! decl_test_network { /// XCM router for relay chain. pub struct RelayChainXcmRouter; impl $crate::SendXcm for RelayChainXcmRouter { - type Ticket = ($crate::MultiLocation, $crate::Xcm<()>); + type Ticket = ($crate::Location, $crate::Xcm<()>); fn validate( - destination: &mut Option<$crate::MultiLocation>, + destination: &mut Option<$crate::Location>, message: &mut Option<$crate::Xcm<()>>, - ) -> $crate::SendResult<($crate::MultiLocation, $crate::Xcm<()>)> { + ) -> $crate::SendResult<($crate::Location, $crate::Xcm<()>)> { use $crate::DmpMessageHandlerT; let d = destination.take().ok_or($crate::SendError::MissingArgument)?; - match (d.interior(), d.parent_count()) { + match d.unpack() { $( - ($crate::X1($crate::Parachain(id)), 0) if id == &$para_id => {}, + (0, [$crate::Parachain(id)]) if id == &$para_id => {}, )* _ => { *destination = Some(d); @@ -433,10 +433,10 @@ macro_rules! decl_test_network { }, } let m = message.take().ok_or($crate::SendError::MissingArgument)?; - Ok(((d, m), $crate::MultiAssets::new())) + Ok(((d, m), $crate::Assets::new())) } fn deliver( - pair: ($crate::MultiLocation, $crate::Xcm<()>), + pair: ($crate::Location, $crate::Xcm<()>), ) -> Result<$crate::XcmHash, $crate::SendError> { let hash = $crate::fake_message_hash(&pair.1); $crate::RELAY_MESSAGE_BUS.with(|b| b.borrow_mut().push_back(pair)); diff --git a/substrate/frame/assets/src/benchmarking.rs b/substrate/frame/assets/src/benchmarking.rs index c9b0825542de..25d981b6bd98 100644 --- a/substrate/frame/assets/src/benchmarking.rs +++ b/substrate/frame/assets/src/benchmarking.rs @@ -45,7 +45,7 @@ fn create_default_asset, I: 'static>( let root = SystemOrigin::Root.into(); assert!(Assets::::force_create( root, - asset_id, + asset_id.clone(), caller_lookup.clone(), is_sufficient, 1u32.into(), @@ -64,7 +64,7 @@ fn create_default_minted_asset, I: 'static>( } assert!(Assets::::mint( SystemOrigin::Signed(caller.clone()).into(), - asset_id, + asset_id.clone(), caller_lookup.clone(), amount, ) @@ -91,7 +91,7 @@ fn add_sufficients, I: 'static>(minter: T::AccountId, n: u32) { let target_lookup = T::Lookup::unlookup(target); assert!(Assets::::mint( origin.clone().into(), - asset_id, + asset_id.clone(), target_lookup, 100u32.into() ) @@ -108,8 +108,13 @@ fn add_approvals, I: 'static>(minter: T::AccountId, n: u32) { ); let minter_lookup = T::Lookup::unlookup(minter.clone()); let origin = SystemOrigin::Signed(minter); - Assets::::mint(origin.clone().into(), asset_id, minter_lookup, (100 * (n + 1)).into()) - .unwrap(); + Assets::::mint( + origin.clone().into(), + asset_id.clone(), + minter_lookup, + (100 * (n + 1)).into(), + ) + .unwrap(); let enough = T::Currency::minimum_balance(); for i in 0..n { let target = account("approval", i, SEED); @@ -117,7 +122,7 @@ fn add_approvals, I: 'static>(minter: T::AccountId, n: u32) { let target_lookup = T::Lookup::unlookup(target); Assets::::approve_transfer( origin.clone().into(), - asset_id, + asset_id.clone(), target_lookup, 100u32.into(), ) @@ -136,12 +141,12 @@ fn assert_event, I: 'static>(generic_event: >::Runti benchmarks_instance_pallet! { create { let asset_id = default_asset_id::(); - let origin = T::CreateOrigin::try_successful_origin(&asset_id.into()) + let origin = T::CreateOrigin::try_successful_origin(&asset_id.clone().into()) .map_err(|_| BenchmarkError::Weightless)?; - let caller = T::CreateOrigin::ensure_origin(origin.clone(), &asset_id.into()).unwrap(); + let caller = T::CreateOrigin::ensure_origin(origin.clone(), &asset_id.clone().into()).unwrap(); let caller_lookup = T::Lookup::unlookup(caller.clone()); T::Currency::make_free_balance_be(&caller, DepositBalanceOf::::max_value()); - }: _(origin, asset_id, caller_lookup, 1u32.into()) + }: _(origin, asset_id.clone(), caller_lookup, 1u32.into()) verify { assert_last_event::(Event::Created { asset_id: asset_id.into(), creator: caller.clone(), owner: caller }.into()); } @@ -150,7 +155,7 @@ benchmarks_instance_pallet! { let asset_id = default_asset_id::(); let caller: T::AccountId = whitelisted_caller(); let caller_lookup = T::Lookup::unlookup(caller.clone()); - }: _(SystemOrigin::Root, asset_id, caller_lookup, true, 1u32.into()) + }: _(SystemOrigin::Root, asset_id.clone(), caller_lookup, true, 1u32.into()) verify { assert_last_event::(Event::ForceCreated { asset_id: asset_id.into(), owner: caller }.into()); } @@ -159,9 +164,9 @@ benchmarks_instance_pallet! { let (asset_id, caller, caller_lookup) = create_default_minted_asset::(true, 100u32.into()); Assets::::freeze_asset( SystemOrigin::Signed(caller.clone()).into(), - asset_id, + asset_id.clone(), )?; - }:_(SystemOrigin::Signed(caller), asset_id) + }:_(SystemOrigin::Signed(caller), asset_id.clone()) verify { assert_last_event::(Event::DestructionStarted { asset_id: asset_id.into() }.into()); } @@ -172,10 +177,10 @@ benchmarks_instance_pallet! { add_sufficients::(caller.clone(), c); Assets::::freeze_asset( SystemOrigin::Signed(caller.clone()).into(), - asset_id, + asset_id.clone(), )?; - Assets::::start_destroy(SystemOrigin::Signed(caller.clone()).into(), asset_id)?; - }:_(SystemOrigin::Signed(caller), asset_id) + Assets::::start_destroy(SystemOrigin::Signed(caller.clone()).into(), asset_id.clone())?; + }:_(SystemOrigin::Signed(caller), asset_id.clone()) verify { assert_last_event::(Event::AccountsDestroyed { asset_id: asset_id.into(), @@ -190,10 +195,10 @@ benchmarks_instance_pallet! { add_approvals::(caller.clone(), a); Assets::::freeze_asset( SystemOrigin::Signed(caller.clone()).into(), - asset_id, + asset_id.clone(), )?; - Assets::::start_destroy(SystemOrigin::Signed(caller.clone()).into(), asset_id)?; - }:_(SystemOrigin::Signed(caller), asset_id) + Assets::::start_destroy(SystemOrigin::Signed(caller.clone()).into(), asset_id.clone())?; + }:_(SystemOrigin::Signed(caller), asset_id.clone()) verify { assert_last_event::(Event::ApprovalsDestroyed { asset_id: asset_id.into(), @@ -206,10 +211,10 @@ benchmarks_instance_pallet! { let (asset_id, caller, caller_lookup) = create_default_asset::(true); Assets::::freeze_asset( SystemOrigin::Signed(caller.clone()).into(), - asset_id, + asset_id.clone(), )?; - Assets::::start_destroy(SystemOrigin::Signed(caller.clone()).into(), asset_id)?; - }:_(SystemOrigin::Signed(caller), asset_id) + Assets::::start_destroy(SystemOrigin::Signed(caller.clone()).into(), asset_id.clone())?; + }:_(SystemOrigin::Signed(caller), asset_id.clone()) verify { assert_last_event::(Event::Destroyed { asset_id: asset_id.into(), @@ -220,7 +225,7 @@ benchmarks_instance_pallet! { mint { let (asset_id, caller, caller_lookup) = create_default_asset::(true); let amount = T::Balance::from(100u32); - }: _(SystemOrigin::Signed(caller.clone()), asset_id, caller_lookup, amount) + }: _(SystemOrigin::Signed(caller.clone()), asset_id.clone(), caller_lookup, amount) verify { assert_last_event::(Event::Issued { asset_id: asset_id.into(), owner: caller, amount }.into()); } @@ -228,7 +233,7 @@ benchmarks_instance_pallet! { burn { let amount = T::Balance::from(100u32); let (asset_id, caller, caller_lookup) = create_default_minted_asset::(true, amount); - }: _(SystemOrigin::Signed(caller.clone()), asset_id, caller_lookup, amount) + }: _(SystemOrigin::Signed(caller.clone()), asset_id.clone(), caller_lookup, amount) verify { assert_last_event::(Event::Burned { asset_id: asset_id.into(), owner: caller, balance: amount }.into()); } @@ -238,7 +243,7 @@ benchmarks_instance_pallet! { let (asset_id, caller, caller_lookup) = create_default_minted_asset::(true, amount); let target: T::AccountId = account("target", 0, SEED); let target_lookup = T::Lookup::unlookup(target.clone()); - }: _(SystemOrigin::Signed(caller.clone()), asset_id, target_lookup, amount) + }: _(SystemOrigin::Signed(caller.clone()), asset_id.clone(), target_lookup, amount) verify { assert_last_event::(Event::Transferred { asset_id: asset_id.into(), from: caller, to: target, amount }.into()); } @@ -249,7 +254,7 @@ benchmarks_instance_pallet! { let (asset_id, caller, caller_lookup) = create_default_minted_asset::(true, mint_amount); let target: T::AccountId = account("target", 0, SEED); let target_lookup = T::Lookup::unlookup(target.clone()); - }: _(SystemOrigin::Signed(caller.clone()), asset_id, target_lookup, amount) + }: _(SystemOrigin::Signed(caller.clone()), asset_id.clone(), target_lookup, amount) verify { assert!(frame_system::Pallet::::account_exists(&caller)); assert_last_event::(Event::Transferred { asset_id: asset_id.into(), from: caller, to: target, amount }.into()); @@ -260,7 +265,7 @@ benchmarks_instance_pallet! { let (asset_id, caller, caller_lookup) = create_default_minted_asset::(true, amount); let target: T::AccountId = account("target", 0, SEED); let target_lookup = T::Lookup::unlookup(target.clone()); - }: _(SystemOrigin::Signed(caller.clone()), asset_id, caller_lookup, target_lookup, amount) + }: _(SystemOrigin::Signed(caller.clone()), asset_id.clone(), caller_lookup, target_lookup, amount) verify { assert_last_event::( Event::Transferred { asset_id: asset_id.into(), from: caller, to: target, amount }.into() @@ -269,7 +274,7 @@ benchmarks_instance_pallet! { freeze { let (asset_id, caller, caller_lookup) = create_default_minted_asset::(true, 100u32.into()); - }: _(SystemOrigin::Signed(caller.clone()), asset_id, caller_lookup) + }: _(SystemOrigin::Signed(caller.clone()), asset_id.clone(), caller_lookup) verify { assert_last_event::(Event::Frozen { asset_id: asset_id.into(), who: caller }.into()); } @@ -278,17 +283,17 @@ benchmarks_instance_pallet! { let (asset_id, caller, caller_lookup) = create_default_minted_asset::(true, 100u32.into()); Assets::::freeze( SystemOrigin::Signed(caller.clone()).into(), - asset_id, + asset_id.clone(), caller_lookup.clone(), )?; - }: _(SystemOrigin::Signed(caller.clone()), asset_id, caller_lookup) + }: _(SystemOrigin::Signed(caller.clone()), asset_id.clone(), caller_lookup) verify { assert_last_event::(Event::Thawed { asset_id: asset_id.into(), who: caller }.into()); } freeze_asset { let (asset_id, caller, caller_lookup) = create_default_minted_asset::(true, 100u32.into()); - }: _(SystemOrigin::Signed(caller.clone()), asset_id) + }: _(SystemOrigin::Signed(caller.clone()), asset_id.clone()) verify { assert_last_event::(Event::AssetFrozen { asset_id: asset_id.into() }.into()); } @@ -297,9 +302,9 @@ benchmarks_instance_pallet! { let (asset_id, caller, caller_lookup) = create_default_minted_asset::(true, 100u32.into()); Assets::::freeze_asset( SystemOrigin::Signed(caller.clone()).into(), - asset_id, + asset_id.clone(), )?; - }: _(SystemOrigin::Signed(caller.clone()), asset_id) + }: _(SystemOrigin::Signed(caller.clone()), asset_id.clone()) verify { assert_last_event::(Event::AssetThawed { asset_id: asset_id.into() }.into()); } @@ -308,7 +313,7 @@ benchmarks_instance_pallet! { let (asset_id, caller, _) = create_default_asset::(true); let target: T::AccountId = account("target", 0, SEED); let target_lookup = T::Lookup::unlookup(target.clone()); - }: _(SystemOrigin::Signed(caller), asset_id, target_lookup) + }: _(SystemOrigin::Signed(caller), asset_id.clone(), target_lookup) verify { assert_last_event::(Event::OwnerChanged { asset_id: asset_id.into(), owner: target }.into()); } @@ -318,7 +323,7 @@ benchmarks_instance_pallet! { let target0 = T::Lookup::unlookup(account("target", 0, SEED)); let target1 = T::Lookup::unlookup(account("target", 1, SEED)); let target2 = T::Lookup::unlookup(account("target", 2, SEED)); - }: _(SystemOrigin::Signed(caller), asset_id, target0, target1, target2) + }: _(SystemOrigin::Signed(caller), asset_id.clone(), target0, target1, target2) verify { assert_last_event::(Event::TeamChanged { asset_id: asset_id.into(), @@ -338,7 +343,7 @@ benchmarks_instance_pallet! { let (asset_id, caller, _) = create_default_asset::(true); T::Currency::make_free_balance_be(&caller, DepositBalanceOf::::max_value()); - }: _(SystemOrigin::Signed(caller), asset_id, name.clone(), symbol.clone(), decimals) + }: _(SystemOrigin::Signed(caller), asset_id.clone(), name.clone(), symbol.clone(), decimals) verify { assert_last_event::(Event::MetadataSet { asset_id: asset_id.into(), name, symbol, decimals, is_frozen: false }.into()); } @@ -348,8 +353,8 @@ benchmarks_instance_pallet! { T::Currency::make_free_balance_be(&caller, DepositBalanceOf::::max_value()); let dummy = vec![0u8; T::StringLimit::get() as usize]; let origin = SystemOrigin::Signed(caller.clone()).into(); - Assets::::set_metadata(origin, asset_id, dummy.clone(), dummy, 12)?; - }: _(SystemOrigin::Signed(caller), asset_id) + Assets::::set_metadata(origin, asset_id.clone(), dummy.clone(), dummy, 12)?; + }: _(SystemOrigin::Signed(caller), asset_id.clone()) verify { assert_last_event::(Event::MetadataCleared { asset_id: asset_id.into() }.into()); } @@ -367,7 +372,7 @@ benchmarks_instance_pallet! { let origin = T::ForceOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; let call = Call::::force_set_metadata { - id: asset_id, + id: asset_id.clone(), name: name.clone(), symbol: symbol.clone(), decimals, @@ -383,11 +388,11 @@ benchmarks_instance_pallet! { T::Currency::make_free_balance_be(&caller, DepositBalanceOf::::max_value()); let dummy = vec![0u8; T::StringLimit::get() as usize]; let origin = SystemOrigin::Signed(caller).into(); - Assets::::set_metadata(origin, asset_id, dummy.clone(), dummy, 12)?; + Assets::::set_metadata(origin, asset_id.clone(), dummy.clone(), dummy, 12)?; let origin = T::ForceOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let call = Call::::force_clear_metadata { id: asset_id }; + let call = Call::::force_clear_metadata { id: asset_id.clone() }; }: { call.dispatch_bypass_filter(origin)? } verify { assert_last_event::(Event::MetadataCleared { asset_id: asset_id.into() }.into()); @@ -399,7 +404,7 @@ benchmarks_instance_pallet! { let origin = T::ForceOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; let call = Call::::force_asset_status { - id: asset_id, + id: asset_id.clone(), owner: caller_lookup.clone(), issuer: caller_lookup.clone(), admin: caller_lookup.clone(), @@ -420,7 +425,7 @@ benchmarks_instance_pallet! { let delegate: T::AccountId = account("delegate", 0, SEED); let delegate_lookup = T::Lookup::unlookup(delegate.clone()); let amount = 100u32.into(); - }: _(SystemOrigin::Signed(caller.clone()), asset_id, delegate_lookup, amount) + }: _(SystemOrigin::Signed(caller.clone()), asset_id.clone(), delegate_lookup, amount) verify { assert_last_event::(Event::ApprovedTransfer { asset_id: asset_id.into(), source: caller, delegate, amount }.into()); } @@ -434,11 +439,11 @@ benchmarks_instance_pallet! { let delegate_lookup = T::Lookup::unlookup(delegate.clone()); let amount = 100u32.into(); let origin = SystemOrigin::Signed(owner.clone()).into(); - Assets::::approve_transfer(origin, asset_id, delegate_lookup, amount)?; + Assets::::approve_transfer(origin, asset_id.clone(), delegate_lookup, amount)?; let dest: T::AccountId = account("dest", 0, SEED); let dest_lookup = T::Lookup::unlookup(dest.clone()); - }: _(SystemOrigin::Signed(delegate.clone()), asset_id, owner_lookup, dest_lookup, amount) + }: _(SystemOrigin::Signed(delegate.clone()), asset_id.clone(), owner_lookup, dest_lookup, amount) verify { assert!(T::Currency::reserved_balance(&owner).is_zero()); assert_event::(Event::Transferred { asset_id: asset_id.into(), from: owner, to: dest, amount }.into()); @@ -452,8 +457,8 @@ benchmarks_instance_pallet! { let delegate_lookup = T::Lookup::unlookup(delegate.clone()); let amount = 100u32.into(); let origin = SystemOrigin::Signed(caller.clone()).into(); - Assets::::approve_transfer(origin, asset_id, delegate_lookup.clone(), amount)?; - }: _(SystemOrigin::Signed(caller.clone()), asset_id, delegate_lookup) + Assets::::approve_transfer(origin, asset_id.clone(), delegate_lookup.clone(), amount)?; + }: _(SystemOrigin::Signed(caller.clone()), asset_id.clone(), delegate_lookup) verify { assert_last_event::(Event::ApprovalCancelled { asset_id: asset_id.into(), owner: caller, delegate }.into()); } @@ -466,15 +471,15 @@ benchmarks_instance_pallet! { let delegate_lookup = T::Lookup::unlookup(delegate.clone()); let amount = 100u32.into(); let origin = SystemOrigin::Signed(caller.clone()).into(); - Assets::::approve_transfer(origin, asset_id, delegate_lookup.clone(), amount)?; - }: _(SystemOrigin::Signed(caller.clone()), asset_id, caller_lookup, delegate_lookup) + Assets::::approve_transfer(origin, asset_id.clone(), delegate_lookup.clone(), amount)?; + }: _(SystemOrigin::Signed(caller.clone()), asset_id.clone(), caller_lookup, delegate_lookup) verify { assert_last_event::(Event::ApprovalCancelled { asset_id: asset_id.into(), owner: caller, delegate }.into()); } set_min_balance { let (asset_id, caller, caller_lookup) = create_default_asset::(false); - }: _(SystemOrigin::Signed(caller.clone()), asset_id, 50u32.into()) + }: _(SystemOrigin::Signed(caller.clone()), asset_id.clone(), 50u32.into()) verify { assert_last_event::(Event::AssetMinBalanceChanged { asset_id: asset_id.into(), new_min_balance: 50u32.into() }.into()); } @@ -484,8 +489,8 @@ benchmarks_instance_pallet! { let new_account: T::AccountId = account("newaccount", 1, SEED); T::Currency::make_free_balance_be(&new_account, DepositBalanceOf::::max_value()); assert_ne!(asset_owner, new_account); - assert!(!Account::::contains_key(asset_id.into(), &new_account)); - }: _(SystemOrigin::Signed(new_account.clone()), asset_id) + assert!(!Account::::contains_key(asset_id.clone().into(), &new_account)); + }: _(SystemOrigin::Signed(new_account.clone()), asset_id.clone()) verify { assert!(Account::::contains_key(asset_id.into(), &new_account)); } @@ -496,8 +501,8 @@ benchmarks_instance_pallet! { let new_account_lookup = T::Lookup::unlookup(new_account.clone()); T::Currency::make_free_balance_be(&asset_owner, DepositBalanceOf::::max_value()); assert_ne!(asset_owner, new_account); - assert!(!Account::::contains_key(asset_id.into(), &new_account)); - }: _(SystemOrigin::Signed(asset_owner.clone()), asset_id, new_account_lookup) + assert!(!Account::::contains_key(asset_id.clone().into(), &new_account)); + }: _(SystemOrigin::Signed(asset_owner.clone()), asset_id.clone(), new_account_lookup) verify { assert!(Account::::contains_key(asset_id.into(), &new_account)); } @@ -509,12 +514,12 @@ benchmarks_instance_pallet! { assert_ne!(asset_owner, new_account); assert!(Assets::::touch( SystemOrigin::Signed(new_account.clone()).into(), - asset_id + asset_id.clone() ).is_ok()); // `touch` should reserve balance of the caller according to the `AssetAccountDeposit` amount... assert_eq!(T::Currency::reserved_balance(&new_account), T::AssetAccountDeposit::get()); // ...and also create an `Account` entry. - assert!(Account::::contains_key(asset_id.into(), &new_account)); + assert!(Account::::contains_key(asset_id.clone().into(), &new_account)); }: _(SystemOrigin::Signed(new_account.clone()), asset_id, true) verify { // `refund`ing should of course repatriate the reserve @@ -529,12 +534,12 @@ benchmarks_instance_pallet! { assert_ne!(asset_owner, new_account); assert!(Assets::::touch_other( SystemOrigin::Signed(asset_owner.clone()).into(), - asset_id, + asset_id.clone(), new_account_lookup.clone() ).is_ok()); // `touch` should reserve balance of the caller according to the `AssetAccountDeposit` amount... assert_eq!(T::Currency::reserved_balance(&asset_owner), T::AssetAccountDeposit::get()); - assert!(Account::::contains_key(asset_id.into(), &new_account)); + assert!(Account::::contains_key(asset_id.clone().into(), &new_account)); }: _(SystemOrigin::Signed(asset_owner.clone()), asset_id, new_account_lookup.clone()) verify { // this should repatriate the reserved balance of the freezer @@ -543,7 +548,7 @@ benchmarks_instance_pallet! { block { let (asset_id, caller, caller_lookup) = create_default_minted_asset::(true, 100u32.into()); - }: _(SystemOrigin::Signed(caller.clone()), asset_id, caller_lookup) + }: _(SystemOrigin::Signed(caller.clone()), asset_id.clone(), caller_lookup) verify { assert_last_event::(Event::Blocked { asset_id: asset_id.into(), who: caller }.into()); } diff --git a/substrate/frame/assets/src/lib.rs b/substrate/frame/assets/src/lib.rs index 79e4fe300187..c70b5b1db580 100644 --- a/substrate/frame/assets/src/lib.rs +++ b/substrate/frame/assets/src/lib.rs @@ -259,11 +259,7 @@ pub mod pallet { /// This type includes the `From` bound, since tightly coupled pallets may /// want to convert an `AssetId` into a parameter for calling dispatchable functions /// directly. - type AssetIdParameter: Parameter - + Copy - + From - + Into - + MaxEncodedLen; + type AssetIdParameter: Parameter + From + Into + MaxEncodedLen; /// The currency mechanism. type Currency: ReservableCurrency; diff --git a/substrate/frame/support/src/traits/tokens/pay.rs b/substrate/frame/support/src/traits/tokens/pay.rs index 4d1d80b5b507..62d7a056a3f1 100644 --- a/substrate/frame/support/src/traits/tokens/pay.rs +++ b/substrate/frame/support/src/traits/tokens/pay.rs @@ -26,7 +26,7 @@ use sp_std::fmt::Debug; use super::{fungible, fungibles, Balance, Preservation::Expendable}; /// Can be implemented by `PayFromAccount` using a `fungible` impl, but can also be implemented with -/// XCM/MultiAsset and made generic over assets. +/// XCM/Asset and made generic over assets. pub trait Pay { /// The type by which we measure units of the currency in which we make payments. type Balance: Balance;