pallet_xcm/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3
4// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16
17//! Pallet to handle XCM messages.
18
19#![cfg_attr(not(feature = "std"), no_std)]
20
21#[cfg(feature = "runtime-benchmarks")]
22pub mod benchmarking;
23#[cfg(test)]
24mod mock;
25#[cfg(test)]
26mod tests;
27mod transfer_assets_validation;
28
29pub mod migration;
30#[cfg(any(test, feature = "test-utils"))]
31pub mod xcm_helpers;
32
33extern crate alloc;
34
35use alloc::{boxed::Box, vec, vec::Vec};
36use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
37use core::{marker::PhantomData, result::Result};
38use frame_support::{
39	dispatch::{
40		DispatchErrorWithPostInfo, GetDispatchInfo, PostDispatchInfo, WithPostDispatchInfo,
41	},
42	pallet_prelude::*,
43	traits::{
44		Consideration, Contains, ContainsPair, Currency, Defensive, EnsureOrigin, Footprint, Get,
45		LockableCurrency, OriginTrait, WithdrawReasons,
46	},
47	PalletId,
48};
49use frame_system::pallet_prelude::{BlockNumberFor, *};
50pub use pallet::*;
51use scale_info::TypeInfo;
52use sp_core::H256;
53use sp_runtime::{
54	traits::{
55		AccountIdConversion, BadOrigin, BlakeTwo256, BlockNumberProvider, Dispatchable, Hash,
56		Saturating, Zero,
57	},
58	Either, RuntimeDebug, SaturatedConversion,
59};
60use storage::{with_transaction, TransactionOutcome};
61use xcm::{latest::QueryResponseInfo, prelude::*};
62use xcm_builder::{
63	ExecuteController, ExecuteControllerWeightInfo, InspectMessageQueues, QueryController,
64	QueryControllerWeightInfo, SendController, SendControllerWeightInfo,
65};
66use xcm_executor::{
67	traits::{
68		AssetTransferError, CheckSuspension, ClaimAssets, ConvertLocation, ConvertOrigin,
69		DropAssets, EventEmitter, FeeManager, FeeReason, MatchesFungible, OnResponse, Properties,
70		QueryHandler, QueryResponseStatus, RecordXcm, TransactAsset, TransferType,
71		VersionChangeNotifier, WeightBounds, XcmAssetTransfers,
72	},
73	AssetsInHolding,
74};
75use xcm_runtime_apis::{
76	authorized_aliases::{Error as AuthorizedAliasersApiError, OriginAliaser},
77	dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
78	fees::Error as XcmPaymentApiError,
79	trusted_query::Error as TrustedQueryApiError,
80};
81
82mod errors;
83pub use errors::ExecutionError;
84
85#[cfg(any(feature = "try-runtime", test))]
86use sp_runtime::TryRuntimeError;
87
88pub trait WeightInfo {
89	fn send() -> Weight;
90	fn teleport_assets() -> Weight;
91	fn reserve_transfer_assets() -> Weight;
92	fn transfer_assets() -> Weight;
93	fn execute() -> Weight;
94	fn force_xcm_version() -> Weight;
95	fn force_default_xcm_version() -> Weight;
96	fn force_subscribe_version_notify() -> Weight;
97	fn force_unsubscribe_version_notify() -> Weight;
98	fn force_suspension() -> Weight;
99	fn migrate_supported_version() -> Weight;
100	fn migrate_version_notifiers() -> Weight;
101	fn already_notified_target() -> Weight;
102	fn notify_current_targets() -> Weight;
103	fn notify_target_migration_fail() -> Weight;
104	fn migrate_version_notify_targets() -> Weight;
105	fn migrate_and_notify_old_targets() -> Weight;
106	fn new_query() -> Weight;
107	fn take_response() -> Weight;
108	fn claim_assets() -> Weight;
109	fn add_authorized_alias() -> Weight;
110	fn remove_authorized_alias() -> Weight;
111
112	fn weigh_message() -> Weight;
113}
114
115/// fallback implementation
116pub struct TestWeightInfo;
117impl WeightInfo for TestWeightInfo {
118	fn send() -> Weight {
119		Weight::from_parts(100_000_000, 0)
120	}
121
122	fn teleport_assets() -> Weight {
123		Weight::from_parts(100_000_000, 0)
124	}
125
126	fn reserve_transfer_assets() -> Weight {
127		Weight::from_parts(100_000_000, 0)
128	}
129
130	fn transfer_assets() -> Weight {
131		Weight::from_parts(100_000_000, 0)
132	}
133
134	fn execute() -> Weight {
135		Weight::from_parts(100_000_000, 0)
136	}
137
138	fn force_xcm_version() -> Weight {
139		Weight::from_parts(100_000_000, 0)
140	}
141
142	fn force_default_xcm_version() -> Weight {
143		Weight::from_parts(100_000_000, 0)
144	}
145
146	fn force_subscribe_version_notify() -> Weight {
147		Weight::from_parts(100_000_000, 0)
148	}
149
150	fn force_unsubscribe_version_notify() -> Weight {
151		Weight::from_parts(100_000_000, 0)
152	}
153
154	fn force_suspension() -> Weight {
155		Weight::from_parts(100_000_000, 0)
156	}
157
158	fn migrate_supported_version() -> Weight {
159		Weight::from_parts(100_000_000, 0)
160	}
161
162	fn migrate_version_notifiers() -> Weight {
163		Weight::from_parts(100_000_000, 0)
164	}
165
166	fn already_notified_target() -> Weight {
167		Weight::from_parts(100_000_000, 0)
168	}
169
170	fn notify_current_targets() -> Weight {
171		Weight::from_parts(100_000_000, 0)
172	}
173
174	fn notify_target_migration_fail() -> Weight {
175		Weight::from_parts(100_000_000, 0)
176	}
177
178	fn migrate_version_notify_targets() -> Weight {
179		Weight::from_parts(100_000_000, 0)
180	}
181
182	fn migrate_and_notify_old_targets() -> Weight {
183		Weight::from_parts(100_000_000, 0)
184	}
185
186	fn new_query() -> Weight {
187		Weight::from_parts(100_000_000, 0)
188	}
189
190	fn take_response() -> Weight {
191		Weight::from_parts(100_000_000, 0)
192	}
193
194	fn claim_assets() -> Weight {
195		Weight::from_parts(100_000_000, 0)
196	}
197
198	fn add_authorized_alias() -> Weight {
199		Weight::from_parts(100_000, 0)
200	}
201
202	fn remove_authorized_alias() -> Weight {
203		Weight::from_parts(100_000, 0)
204	}
205
206	fn weigh_message() -> Weight {
207		Weight::from_parts(100_000, 0)
208	}
209}
210
211#[derive(Clone, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
212pub struct AuthorizedAliasesEntry<Ticket, MAX: Get<u32>> {
213	pub aliasers: BoundedVec<OriginAliaser, MAX>,
214	pub ticket: Ticket,
215}
216
217pub fn aliasers_footprint(aliasers_count: usize) -> Footprint {
218	Footprint::from_parts(aliasers_count, OriginAliaser::max_encoded_len())
219}
220
221#[frame_support::pallet]
222pub mod pallet {
223	use super::*;
224	use frame_support::{
225		dispatch::{GetDispatchInfo, PostDispatchInfo},
226		parameter_types,
227	};
228	use frame_system::Config as SysConfig;
229	use sp_runtime::traits::Dispatchable;
230	use xcm_executor::traits::{MatchesFungible, WeightBounds};
231
232	parameter_types! {
233		/// An implementation of `Get<u32>` which just returns the latest XCM version which we can
234		/// support.
235		pub const CurrentXcmVersion: u32 = XCM_VERSION;
236
237		#[derive(Debug, TypeInfo)]
238		/// The maximum number of distinct locations allowed as authorized aliases for a local origin.
239		pub const MaxAuthorizedAliases: u32 = 10;
240	}
241
242	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
243
244	#[pallet::pallet]
245	#[pallet::storage_version(STORAGE_VERSION)]
246	#[pallet::without_storage_info]
247	pub struct Pallet<T>(_);
248
249	pub type BalanceOf<T> =
250		<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
251	pub type TicketOf<T> = <T as Config>::AuthorizedAliasConsideration;
252
253	#[pallet::config]
254	/// The module configuration trait.
255	pub trait Config: frame_system::Config {
256		/// The overarching event type.
257		#[allow(deprecated)]
258		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
259
260		/// A lockable currency.
261		// TODO: We should really use a trait which can handle multiple currencies.
262		type Currency: LockableCurrency<Self::AccountId, Moment = BlockNumberFor<Self>>;
263
264		/// The `Asset` matcher for `Currency`.
265		type CurrencyMatcher: MatchesFungible<BalanceOf<Self>>;
266
267		/// A means of providing some cost while Authorized Aliasers data is stored on-chain.
268		type AuthorizedAliasConsideration: Consideration<Self::AccountId, Footprint>;
269
270		/// Required origin for sending XCM messages. If successful, it resolves to `Location`
271		/// which exists as an interior location within this chain's XCM context.
272		type SendXcmOrigin: EnsureOrigin<<Self as SysConfig>::RuntimeOrigin, Success = Location>;
273
274		/// The type used to actually dispatch an XCM to its destination.
275		type XcmRouter: SendXcm;
276
277		/// Required origin for executing XCM messages, including the teleport functionality. If
278		/// successful, then it resolves to `Location` which exists as an interior location
279		/// within this chain's XCM context.
280		type ExecuteXcmOrigin: EnsureOrigin<<Self as SysConfig>::RuntimeOrigin, Success = Location>;
281
282		/// Our XCM filter which messages to be executed using `XcmExecutor` must pass.
283		type XcmExecuteFilter: Contains<(Location, Xcm<<Self as Config>::RuntimeCall>)>;
284
285		/// Something to execute an XCM message.
286		type XcmExecutor: ExecuteXcm<<Self as Config>::RuntimeCall> + XcmAssetTransfers + FeeManager;
287
288		/// Our XCM filter which messages to be teleported using the dedicated extrinsic must pass.
289		type XcmTeleportFilter: Contains<(Location, Vec<Asset>)>;
290
291		/// Our XCM filter which messages to be reserve-transferred using the dedicated extrinsic
292		/// must pass.
293		type XcmReserveTransferFilter: Contains<(Location, Vec<Asset>)>;
294
295		/// Means of measuring the weight consumed by an XCM message locally.
296		type Weigher: WeightBounds<<Self as Config>::RuntimeCall>;
297
298		/// This chain's Universal Location.
299		#[pallet::constant]
300		type UniversalLocation: Get<InteriorLocation>;
301
302		/// The runtime `Origin` type.
303		type RuntimeOrigin: From<Origin> + From<<Self as SysConfig>::RuntimeOrigin>;
304
305		/// The runtime `Call` type.
306		type RuntimeCall: Parameter
307			+ GetDispatchInfo
308			+ Dispatchable<
309				RuntimeOrigin = <Self as Config>::RuntimeOrigin,
310				PostInfo = PostDispatchInfo,
311			>;
312
313		const VERSION_DISCOVERY_QUEUE_SIZE: u32;
314
315		/// The latest supported version that we advertise. Generally just set it to
316		/// `pallet_xcm::CurrentXcmVersion`.
317		#[pallet::constant]
318		type AdvertisedXcmVersion: Get<XcmVersion>;
319
320		/// The origin that is allowed to call privileged operations on the XCM pallet
321		type AdminOrigin: EnsureOrigin<<Self as SysConfig>::RuntimeOrigin>;
322
323		/// The assets which we consider a given origin is trusted if they claim to have placed a
324		/// lock.
325		type TrustedLockers: ContainsPair<Location, Asset>;
326
327		/// How to get an `AccountId` value from a `Location`, useful for handling asset locks.
328		type SovereignAccountOf: ConvertLocation<Self::AccountId>;
329
330		/// The maximum number of local XCM locks that a single account may have.
331		#[pallet::constant]
332		type MaxLockers: Get<u32>;
333
334		/// The maximum number of consumers a single remote lock may have.
335		#[pallet::constant]
336		type MaxRemoteLockConsumers: Get<u32>;
337
338		/// The ID type for local consumers of remote locks.
339		type RemoteLockConsumerIdentifier: Parameter + Member + MaxEncodedLen + Ord + Copy;
340
341		/// Weight information for extrinsics in this pallet.
342		type WeightInfo: WeightInfo;
343	}
344
345	impl<T: Config> ExecuteControllerWeightInfo for Pallet<T> {
346		fn execute() -> Weight {
347			T::WeightInfo::execute()
348		}
349	}
350
351	impl<T: Config> ExecuteController<OriginFor<T>, <T as Config>::RuntimeCall> for Pallet<T> {
352		type WeightInfo = Self;
353		fn execute(
354			origin: OriginFor<T>,
355			message: Box<VersionedXcm<<T as Config>::RuntimeCall>>,
356			max_weight: Weight,
357		) -> Result<Weight, DispatchErrorWithPostInfo> {
358			tracing::trace!(target: "xcm::pallet_xcm::execute", ?message, ?max_weight);
359			let outcome = (|| {
360				let origin_location = T::ExecuteXcmOrigin::ensure_origin(origin)?;
361				let mut hash = message.using_encoded(sp_io::hashing::blake2_256);
362				let message = (*message).try_into().map_err(|()| {
363					tracing::debug!(
364						target: "xcm::pallet_xcm::execute", id=?hash,
365						"Failed to convert VersionedXcm to Xcm",
366					);
367					Error::<T>::BadVersion
368				})?;
369				let value = (origin_location, message);
370				ensure!(T::XcmExecuteFilter::contains(&value), Error::<T>::Filtered);
371				let (origin_location, message) = value;
372				Ok(T::XcmExecutor::prepare_and_execute(
373					origin_location,
374					message,
375					&mut hash,
376					max_weight,
377					max_weight,
378				))
379			})()
380			.map_err(|e: DispatchError| {
381				tracing::debug!(
382					target: "xcm::pallet_xcm::execute", error=?e,
383					"Failed XCM pre-execution validation or filter",
384				);
385				e.with_weight(<Self::WeightInfo as ExecuteControllerWeightInfo>::execute())
386			})?;
387
388			Self::deposit_event(Event::Attempted { outcome: outcome.clone() });
389			let weight_used = outcome.weight_used();
390			outcome.ensure_complete().map_err(|error| {
391				tracing::error!(target: "xcm::pallet_xcm::execute", ?error, "XCM execution failed with error");
392				Error::<T>::LocalExecutionIncompleteWithError {
393					index: error.index,
394					error: error.error.into(),
395				}
396				.with_weight(
397					weight_used.saturating_add(
398						<Self::WeightInfo as ExecuteControllerWeightInfo>::execute(),
399					),
400				)
401			})?;
402			Ok(weight_used)
403		}
404	}
405
406	impl<T: Config> SendControllerWeightInfo for Pallet<T> {
407		fn send() -> Weight {
408			T::WeightInfo::send()
409		}
410	}
411
412	impl<T: Config> SendController<OriginFor<T>> for Pallet<T> {
413		type WeightInfo = Self;
414		fn send(
415			origin: OriginFor<T>,
416			dest: Box<VersionedLocation>,
417			message: Box<VersionedXcm<()>>,
418		) -> Result<XcmHash, DispatchError> {
419			let origin_location = T::SendXcmOrigin::ensure_origin(origin)?;
420			let interior: Junctions = origin_location.clone().try_into().map_err(|_| {
421				tracing::debug!(
422					target: "xcm::pallet_xcm::send",
423					"Failed to convert origin_location to interior Junctions",
424				);
425				Error::<T>::InvalidOrigin
426			})?;
427			let dest = Location::try_from(*dest).map_err(|()| {
428				tracing::debug!(
429					target: "xcm::pallet_xcm::send",
430					"Failed to convert destination VersionedLocation to Location",
431				);
432				Error::<T>::BadVersion
433			})?;
434			let message: Xcm<()> = (*message).try_into().map_err(|()| {
435				tracing::debug!(
436					target: "xcm::pallet_xcm::send",
437					"Failed to convert VersionedXcm message to Xcm",
438				);
439				Error::<T>::BadVersion
440			})?;
441
442			let message_id = Self::send_xcm(interior, dest.clone(), message.clone())
443				.map_err(|error| {
444					tracing::error!(target: "xcm::pallet_xcm::send", ?error, ?dest, ?message, "XCM send failed with error");
445					Error::<T>::from(error)
446				})?;
447			let e = Event::Sent { origin: origin_location, destination: dest, message, message_id };
448			Self::deposit_event(e);
449			Ok(message_id)
450		}
451	}
452
453	impl<T: Config> QueryControllerWeightInfo for Pallet<T> {
454		fn query() -> Weight {
455			T::WeightInfo::new_query()
456		}
457		fn take_response() -> Weight {
458			T::WeightInfo::take_response()
459		}
460	}
461
462	impl<T: Config> QueryController<OriginFor<T>, BlockNumberFor<T>> for Pallet<T> {
463		type WeightInfo = Self;
464
465		fn query(
466			origin: OriginFor<T>,
467			timeout: BlockNumberFor<T>,
468			match_querier: VersionedLocation,
469		) -> Result<QueryId, DispatchError> {
470			let responder = <T as Config>::ExecuteXcmOrigin::ensure_origin(origin)?;
471			let query_id = <Self as QueryHandler>::new_query(
472				responder,
473				timeout,
474				Location::try_from(match_querier).map_err(|_| {
475					tracing::debug!(
476						target: "xcm::pallet_xcm::query",
477						"Failed to convert VersionedLocation for match_querier",
478					);
479					Into::<DispatchError>::into(Error::<T>::BadVersion)
480				})?,
481			);
482
483			Ok(query_id)
484		}
485	}
486
487	impl<T: Config> EventEmitter for Pallet<T> {
488		fn emit_sent_event(
489			origin: Location,
490			destination: Location,
491			message: Option<Xcm<()>>,
492			message_id: XcmHash,
493		) {
494			Self::deposit_event(Event::Sent {
495				origin,
496				destination,
497				message: message.unwrap_or_default(),
498				message_id,
499			});
500		}
501
502		fn emit_send_failure_event(
503			origin: Location,
504			destination: Location,
505			error: SendError,
506			message_id: XcmHash,
507		) {
508			Self::deposit_event(Event::SendFailed { origin, destination, error, message_id });
509		}
510
511		fn emit_process_failure_event(origin: Location, error: XcmError, message_id: XcmHash) {
512			Self::deposit_event(Event::ProcessXcmError { origin, error, message_id });
513		}
514	}
515
516	#[pallet::event]
517	#[pallet::generate_deposit(pub(super) fn deposit_event)]
518	pub enum Event<T: Config> {
519		/// Execution of an XCM message was attempted.
520		Attempted { outcome: xcm::latest::Outcome },
521		/// An XCM message was sent.
522		Sent { origin: Location, destination: Location, message: Xcm<()>, message_id: XcmHash },
523		/// An XCM message failed to send.
524		SendFailed {
525			origin: Location,
526			destination: Location,
527			error: SendError,
528			message_id: XcmHash,
529		},
530		/// An XCM message failed to process.
531		ProcessXcmError { origin: Location, error: XcmError, message_id: XcmHash },
532		/// Query response received which does not match a registered query. This may be because a
533		/// matching query was never registered, it may be because it is a duplicate response, or
534		/// because the query timed out.
535		UnexpectedResponse { origin: Location, query_id: QueryId },
536		/// Query response has been received and is ready for taking with `take_response`. There is
537		/// no registered notification call.
538		ResponseReady { query_id: QueryId, response: Response },
539		/// Query response has been received and query is removed. The registered notification has
540		/// been dispatched and executed successfully.
541		Notified { query_id: QueryId, pallet_index: u8, call_index: u8 },
542		/// Query response has been received and query is removed. The registered notification
543		/// could not be dispatched because the dispatch weight is greater than the maximum weight
544		/// originally budgeted by this runtime for the query result.
545		NotifyOverweight {
546			query_id: QueryId,
547			pallet_index: u8,
548			call_index: u8,
549			actual_weight: Weight,
550			max_budgeted_weight: Weight,
551		},
552		/// Query response has been received and query is removed. There was a general error with
553		/// dispatching the notification call.
554		NotifyDispatchError { query_id: QueryId, pallet_index: u8, call_index: u8 },
555		/// Query response has been received and query is removed. The dispatch was unable to be
556		/// decoded into a `Call`; this might be due to dispatch function having a signature which
557		/// is not `(origin, QueryId, Response)`.
558		NotifyDecodeFailed { query_id: QueryId, pallet_index: u8, call_index: u8 },
559		/// Expected query response has been received but the origin location of the response does
560		/// not match that expected. The query remains registered for a later, valid, response to
561		/// be received and acted upon.
562		InvalidResponder {
563			origin: Location,
564			query_id: QueryId,
565			expected_location: Option<Location>,
566		},
567		/// Expected query response has been received but the expected origin location placed in
568		/// storage by this runtime previously cannot be decoded. The query remains registered.
569		///
570		/// This is unexpected (since a location placed in storage in a previously executing
571		/// runtime should be readable prior to query timeout) and dangerous since the possibly
572		/// valid response will be dropped. Manual governance intervention is probably going to be
573		/// needed.
574		InvalidResponderVersion { origin: Location, query_id: QueryId },
575		/// Received query response has been read and removed.
576		ResponseTaken { query_id: QueryId },
577		/// Some assets have been placed in an asset trap.
578		AssetsTrapped { hash: H256, origin: Location, assets: VersionedAssets },
579		/// An XCM version change notification message has been attempted to be sent.
580		///
581		/// The cost of sending it (borne by the chain) is included.
582		VersionChangeNotified {
583			destination: Location,
584			result: XcmVersion,
585			cost: Assets,
586			message_id: XcmHash,
587		},
588		/// The supported version of a location has been changed. This might be through an
589		/// automatic notification or a manual intervention.
590		SupportedVersionChanged { location: Location, version: XcmVersion },
591		/// A given location which had a version change subscription was dropped owing to an error
592		/// sending the notification to it.
593		NotifyTargetSendFail { location: Location, query_id: QueryId, error: XcmError },
594		/// A given location which had a version change subscription was dropped owing to an error
595		/// migrating the location to our new XCM format.
596		NotifyTargetMigrationFail { location: VersionedLocation, query_id: QueryId },
597		/// Expected query response has been received but the expected querier location placed in
598		/// storage by this runtime previously cannot be decoded. The query remains registered.
599		///
600		/// This is unexpected (since a location placed in storage in a previously executing
601		/// runtime should be readable prior to query timeout) and dangerous since the possibly
602		/// valid response will be dropped. Manual governance intervention is probably going to be
603		/// needed.
604		InvalidQuerierVersion { origin: Location, query_id: QueryId },
605		/// Expected query response has been received but the querier location of the response does
606		/// not match the expected. The query remains registered for a later, valid, response to
607		/// be received and acted upon.
608		InvalidQuerier {
609			origin: Location,
610			query_id: QueryId,
611			expected_querier: Location,
612			maybe_actual_querier: Option<Location>,
613		},
614		/// A remote has requested XCM version change notification from us and we have honored it.
615		/// A version information message is sent to them and its cost is included.
616		VersionNotifyStarted { destination: Location, cost: Assets, message_id: XcmHash },
617		/// We have requested that a remote chain send us XCM version change notifications.
618		VersionNotifyRequested { destination: Location, cost: Assets, message_id: XcmHash },
619		/// We have requested that a remote chain stops sending us XCM version change
620		/// notifications.
621		VersionNotifyUnrequested { destination: Location, cost: Assets, message_id: XcmHash },
622		/// Fees were paid from a location for an operation (often for using `SendXcm`).
623		FeesPaid { paying: Location, fees: Assets },
624		/// Some assets have been claimed from an asset trap
625		AssetsClaimed { hash: H256, origin: Location, assets: VersionedAssets },
626		/// A XCM version migration finished.
627		VersionMigrationFinished { version: XcmVersion },
628		/// An `aliaser` location was authorized by `target` to alias it, authorization valid until
629		/// `expiry` block number.
630		AliasAuthorized { aliaser: Location, target: Location, expiry: Option<u64> },
631		/// `target` removed alias authorization for `aliaser`.
632		AliasAuthorizationRemoved { aliaser: Location, target: Location },
633		/// `target` removed all alias authorizations.
634		AliasesAuthorizationsRemoved { target: Location },
635	}
636
637	#[pallet::origin]
638	#[derive(
639		PartialEq,
640		Eq,
641		Clone,
642		Encode,
643		Decode,
644		DecodeWithMemTracking,
645		RuntimeDebug,
646		TypeInfo,
647		MaxEncodedLen,
648	)]
649	pub enum Origin {
650		/// It comes from somewhere in the XCM space wanting to transact.
651		Xcm(Location),
652		/// It comes as an expected response from an XCM location.
653		Response(Location),
654	}
655	impl From<Location> for Origin {
656		fn from(location: Location) -> Origin {
657			Origin::Xcm(location)
658		}
659	}
660
661	/// A reason for this pallet placing a hold on funds.
662	#[pallet::composite_enum]
663	pub enum HoldReason {
664		/// The funds are held as storage deposit for an authorized alias.
665		AuthorizeAlias,
666	}
667
668	#[pallet::error]
669	pub enum Error<T> {
670		/// The desired destination was unreachable, generally because there is a no way of routing
671		/// to it.
672		Unreachable,
673		/// There was some other issue (i.e. not to do with routing) in sending the message.
674		/// Perhaps a lack of space for buffering the message.
675		SendFailure,
676		/// The message execution fails the filter.
677		Filtered,
678		/// The message's weight could not be determined.
679		UnweighableMessage,
680		/// The destination `Location` provided cannot be inverted.
681		DestinationNotInvertible,
682		/// The assets to be sent are empty.
683		Empty,
684		/// Could not re-anchor the assets to declare the fees for the destination chain.
685		CannotReanchor,
686		/// Too many assets have been attempted for transfer.
687		TooManyAssets,
688		/// Origin is invalid for sending.
689		InvalidOrigin,
690		/// The version of the `Versioned` value used is not able to be interpreted.
691		BadVersion,
692		/// The given location could not be used (e.g. because it cannot be expressed in the
693		/// desired version of XCM).
694		BadLocation,
695		/// The referenced subscription could not be found.
696		NoSubscription,
697		/// The location is invalid since it already has a subscription from us.
698		AlreadySubscribed,
699		/// Could not check-out the assets for teleportation to the destination chain.
700		CannotCheckOutTeleport,
701		/// The owner does not own (all) of the asset that they wish to do the operation on.
702		LowBalance,
703		/// The asset owner has too many locks on the asset.
704		TooManyLocks,
705		/// The given account is not an identifiable sovereign account for any location.
706		AccountNotSovereign,
707		/// The operation required fees to be paid which the initiator could not meet.
708		FeesNotMet,
709		/// A remote lock with the corresponding data could not be found.
710		LockNotFound,
711		/// The unlock operation cannot succeed because there are still consumers of the lock.
712		InUse,
713		/// Invalid asset, reserve chain could not be determined for it.
714		#[codec(index = 21)]
715		InvalidAssetUnknownReserve,
716		/// Invalid asset, do not support remote asset reserves with different fees reserves.
717		#[codec(index = 22)]
718		InvalidAssetUnsupportedReserve,
719		/// Too many assets with different reserve locations have been attempted for transfer.
720		#[codec(index = 23)]
721		TooManyReserves,
722		/// Local XCM execution incomplete.
723		#[deprecated(since = "20.0.0", note = "Use `LocalExecutionIncompleteWithError` instead")]
724		#[codec(index = 24)]
725		LocalExecutionIncomplete,
726		/// Too many locations authorized to alias origin.
727		#[codec(index = 25)]
728		TooManyAuthorizedAliases,
729		/// Expiry block number is in the past.
730		#[codec(index = 26)]
731		ExpiresInPast,
732		/// The alias to remove authorization for was not found.
733		#[codec(index = 27)]
734		AliasNotFound,
735		/// Local XCM execution incomplete with the actual XCM error and the index of the
736		/// instruction that caused the error.
737		#[codec(index = 28)]
738		LocalExecutionIncompleteWithError { index: InstructionIndex, error: ExecutionError },
739	}
740
741	impl<T: Config> From<SendError> for Error<T> {
742		fn from(e: SendError) -> Self {
743			match e {
744				SendError::Fees => Error::<T>::FeesNotMet,
745				SendError::NotApplicable => Error::<T>::Unreachable,
746				_ => Error::<T>::SendFailure,
747			}
748		}
749	}
750
751	impl<T: Config> From<AssetTransferError> for Error<T> {
752		fn from(e: AssetTransferError) -> Self {
753			match e {
754				AssetTransferError::UnknownReserve => Error::<T>::InvalidAssetUnknownReserve,
755			}
756		}
757	}
758
759	/// The status of a query.
760	#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]
761	pub enum QueryStatus<BlockNumber> {
762		/// The query was sent but no response has yet been received.
763		Pending {
764			/// The `QueryResponse` XCM must have this origin to be considered a reply for this
765			/// query.
766			responder: VersionedLocation,
767			/// The `QueryResponse` XCM must have this value as the `querier` field to be
768			/// considered a reply for this query. If `None` then the querier is ignored.
769			maybe_match_querier: Option<VersionedLocation>,
770			maybe_notify: Option<(u8, u8)>,
771			timeout: BlockNumber,
772		},
773		/// The query is for an ongoing version notification subscription.
774		VersionNotifier { origin: VersionedLocation, is_active: bool },
775		/// A response has been received.
776		Ready { response: VersionedResponse, at: BlockNumber },
777	}
778
779	#[derive(Copy, Clone)]
780	pub(crate) struct LatestVersionedLocation<'a>(pub(crate) &'a Location);
781	impl<'a> EncodeLike<VersionedLocation> for LatestVersionedLocation<'a> {}
782	impl<'a> Encode for LatestVersionedLocation<'a> {
783		fn encode(&self) -> Vec<u8> {
784			let mut r = VersionedLocation::from(Location::default()).encode();
785			r.truncate(1);
786			self.0.using_encoded(|d| r.extend_from_slice(d));
787			r
788		}
789	}
790
791	#[derive(Clone, Encode, Decode, Eq, PartialEq, Ord, PartialOrd, TypeInfo)]
792	pub enum VersionMigrationStage {
793		MigrateSupportedVersion,
794		MigrateVersionNotifiers,
795		NotifyCurrentTargets(Option<Vec<u8>>),
796		MigrateAndNotifyOldTargets,
797	}
798
799	impl Default for VersionMigrationStage {
800		fn default() -> Self {
801			Self::MigrateSupportedVersion
802		}
803	}
804
805	/// The latest available query index.
806	#[pallet::storage]
807	pub(super) type QueryCounter<T: Config> = StorageValue<_, QueryId, ValueQuery>;
808
809	/// The ongoing queries.
810	#[pallet::storage]
811	pub(super) type Queries<T: Config> =
812		StorageMap<_, Blake2_128Concat, QueryId, QueryStatus<BlockNumberFor<T>>, OptionQuery>;
813
814	/// The existing asset traps.
815	///
816	/// Key is the blake2 256 hash of (origin, versioned `Assets`) pair. Value is the number of
817	/// times this pair has been trapped (usually just 1 if it exists at all).
818	#[pallet::storage]
819	pub(super) type AssetTraps<T: Config> = StorageMap<_, Identity, H256, u32, ValueQuery>;
820
821	/// Default version to encode XCM when latest version of destination is unknown. If `None`,
822	/// then the destinations whose XCM version is unknown are considered unreachable.
823	#[pallet::storage]
824	#[pallet::whitelist_storage]
825	pub(super) type SafeXcmVersion<T: Config> = StorageValue<_, XcmVersion, OptionQuery>;
826
827	/// The Latest versions that we know various locations support.
828	#[pallet::storage]
829	pub(super) type SupportedVersion<T: Config> = StorageDoubleMap<
830		_,
831		Twox64Concat,
832		XcmVersion,
833		Blake2_128Concat,
834		VersionedLocation,
835		XcmVersion,
836		OptionQuery,
837	>;
838
839	/// All locations that we have requested version notifications from.
840	#[pallet::storage]
841	pub(super) type VersionNotifiers<T: Config> = StorageDoubleMap<
842		_,
843		Twox64Concat,
844		XcmVersion,
845		Blake2_128Concat,
846		VersionedLocation,
847		QueryId,
848		OptionQuery,
849	>;
850
851	/// The target locations that are subscribed to our version changes, as well as the most recent
852	/// of our versions we informed them of.
853	#[pallet::storage]
854	pub(super) type VersionNotifyTargets<T: Config> = StorageDoubleMap<
855		_,
856		Twox64Concat,
857		XcmVersion,
858		Blake2_128Concat,
859		VersionedLocation,
860		(QueryId, Weight, XcmVersion),
861		OptionQuery,
862	>;
863
864	pub struct VersionDiscoveryQueueSize<T>(PhantomData<T>);
865	impl<T: Config> Get<u32> for VersionDiscoveryQueueSize<T> {
866		fn get() -> u32 {
867			T::VERSION_DISCOVERY_QUEUE_SIZE
868		}
869	}
870
871	/// Destinations whose latest XCM version we would like to know. Duplicates not allowed, and
872	/// the `u32` counter is the number of times that a send to the destination has been attempted,
873	/// which is used as a prioritization.
874	#[pallet::storage]
875	#[pallet::whitelist_storage]
876	pub(super) type VersionDiscoveryQueue<T: Config> = StorageValue<
877		_,
878		BoundedVec<(VersionedLocation, u32), VersionDiscoveryQueueSize<T>>,
879		ValueQuery,
880	>;
881
882	/// The current migration's stage, if any.
883	#[pallet::storage]
884	pub(super) type CurrentMigration<T: Config> =
885		StorageValue<_, VersionMigrationStage, OptionQuery>;
886
887	#[derive(Clone, Encode, Decode, Eq, PartialEq, Ord, PartialOrd, TypeInfo, MaxEncodedLen)]
888	#[scale_info(skip_type_params(MaxConsumers))]
889	pub struct RemoteLockedFungibleRecord<ConsumerIdentifier, MaxConsumers: Get<u32>> {
890		/// Total amount of the asset held by the remote lock.
891		pub amount: u128,
892		/// The owner of the locked asset.
893		pub owner: VersionedLocation,
894		/// The location which holds the original lock.
895		pub locker: VersionedLocation,
896		/// Local consumers of the remote lock with a consumer identifier and the amount
897		/// of fungible asset every consumer holds.
898		/// Every consumer can hold up to total amount of the remote lock.
899		pub consumers: BoundedVec<(ConsumerIdentifier, u128), MaxConsumers>,
900	}
901
902	impl<LockId, MaxConsumers: Get<u32>> RemoteLockedFungibleRecord<LockId, MaxConsumers> {
903		/// Amount of the remote lock in use by consumers.
904		/// Returns `None` if the remote lock has no consumers.
905		pub fn amount_held(&self) -> Option<u128> {
906			self.consumers.iter().max_by(|x, y| x.1.cmp(&y.1)).map(|max| max.1)
907		}
908	}
909
910	/// Fungible assets which we know are locked on a remote chain.
911	#[pallet::storage]
912	pub(super) type RemoteLockedFungibles<T: Config> = StorageNMap<
913		_,
914		(
915			NMapKey<Twox64Concat, XcmVersion>,
916			NMapKey<Blake2_128Concat, T::AccountId>,
917			NMapKey<Blake2_128Concat, VersionedAssetId>,
918		),
919		RemoteLockedFungibleRecord<T::RemoteLockConsumerIdentifier, T::MaxRemoteLockConsumers>,
920		OptionQuery,
921	>;
922
923	/// Fungible assets which we know are locked on this chain.
924	#[pallet::storage]
925	pub(super) type LockedFungibles<T: Config> = StorageMap<
926		_,
927		Blake2_128Concat,
928		T::AccountId,
929		BoundedVec<(BalanceOf<T>, VersionedLocation), T::MaxLockers>,
930		OptionQuery,
931	>;
932
933	/// Global suspension state of the XCM executor.
934	#[pallet::storage]
935	pub(super) type XcmExecutionSuspended<T: Config> = StorageValue<_, bool, ValueQuery>;
936
937	/// Whether or not incoming XCMs (both executed locally and received) should be recorded.
938	/// Only one XCM program will be recorded at a time.
939	/// This is meant to be used in runtime APIs, and it's advised it stays false
940	/// for all other use cases, so as to not degrade regular performance.
941	///
942	/// Only relevant if this pallet is being used as the [`xcm_executor::traits::RecordXcm`]
943	/// implementation in the XCM executor configuration.
944	#[pallet::storage]
945	pub(crate) type ShouldRecordXcm<T: Config> = StorageValue<_, bool, ValueQuery>;
946
947	/// If [`ShouldRecordXcm`] is set to true, then the last XCM program executed locally
948	/// will be stored here.
949	/// Runtime APIs can fetch the XCM that was executed by accessing this value.
950	///
951	/// Only relevant if this pallet is being used as the [`xcm_executor::traits::RecordXcm`]
952	/// implementation in the XCM executor configuration.
953	#[pallet::storage]
954	pub(crate) type RecordedXcm<T: Config> = StorageValue<_, Xcm<()>>;
955
956	/// Map of authorized aliasers of local origins. Each local location can authorize a list of
957	/// other locations to alias into it. Each aliaser is only valid until its inner `expiry`
958	/// block number.
959	#[pallet::storage]
960	pub(super) type AuthorizedAliases<T: Config> = StorageMap<
961		_,
962		Blake2_128Concat,
963		VersionedLocation,
964		AuthorizedAliasesEntry<TicketOf<T>, MaxAuthorizedAliases>,
965		OptionQuery,
966	>;
967
968	#[pallet::genesis_config]
969	pub struct GenesisConfig<T: Config> {
970		#[serde(skip)]
971		pub _config: core::marker::PhantomData<T>,
972		/// The default version to encode outgoing XCM messages with.
973		pub safe_xcm_version: Option<XcmVersion>,
974	}
975
976	impl<T: Config> Default for GenesisConfig<T> {
977		fn default() -> Self {
978			Self { safe_xcm_version: Some(XCM_VERSION), _config: Default::default() }
979		}
980	}
981
982	#[pallet::genesis_build]
983	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
984		fn build(&self) {
985			SafeXcmVersion::<T>::set(self.safe_xcm_version);
986		}
987	}
988
989	#[pallet::hooks]
990	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
991		fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
992			let mut weight_used = Weight::zero();
993			if let Some(migration) = CurrentMigration::<T>::get() {
994				// Consume 10% of block at most
995				let max_weight = T::BlockWeights::get().max_block / 10;
996				let (w, maybe_migration) = Self::lazy_migration(migration, max_weight);
997				if maybe_migration.is_none() {
998					Self::deposit_event(Event::VersionMigrationFinished { version: XCM_VERSION });
999				}
1000				CurrentMigration::<T>::set(maybe_migration);
1001				weight_used.saturating_accrue(w);
1002			}
1003
1004			// Here we aim to get one successful version negotiation request sent per block, ordered
1005			// by the destinations being most sent to.
1006			let mut q = VersionDiscoveryQueue::<T>::take().into_inner();
1007			// TODO: correct weights.
1008			weight_used.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
1009			q.sort_by_key(|i| i.1);
1010			while let Some((versioned_dest, _)) = q.pop() {
1011				if let Ok(dest) = Location::try_from(versioned_dest) {
1012					if Self::request_version_notify(dest).is_ok() {
1013						// TODO: correct weights.
1014						weight_used.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
1015						break
1016					}
1017				}
1018			}
1019			// Should never fail since we only removed items. But better safe than panicking as it's
1020			// way better to drop the queue than panic on initialize.
1021			if let Ok(q) = BoundedVec::try_from(q) {
1022				VersionDiscoveryQueue::<T>::put(q);
1023			}
1024			weight_used
1025		}
1026
1027		#[cfg(feature = "try-runtime")]
1028		fn try_state(_n: BlockNumberFor<T>) -> Result<(), TryRuntimeError> {
1029			Self::do_try_state()
1030		}
1031	}
1032
1033	pub mod migrations {
1034		use super::*;
1035		use frame_support::traits::{PalletInfoAccess, StorageVersion};
1036
1037		#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)]
1038		enum QueryStatusV0<BlockNumber> {
1039			Pending {
1040				responder: VersionedLocation,
1041				maybe_notify: Option<(u8, u8)>,
1042				timeout: BlockNumber,
1043			},
1044			VersionNotifier {
1045				origin: VersionedLocation,
1046				is_active: bool,
1047			},
1048			Ready {
1049				response: VersionedResponse,
1050				at: BlockNumber,
1051			},
1052		}
1053		impl<B> From<QueryStatusV0<B>> for QueryStatus<B> {
1054			fn from(old: QueryStatusV0<B>) -> Self {
1055				use QueryStatusV0::*;
1056				match old {
1057					Pending { responder, maybe_notify, timeout } => QueryStatus::Pending {
1058						responder,
1059						maybe_notify,
1060						timeout,
1061						maybe_match_querier: Some(Location::here().into()),
1062					},
1063					VersionNotifier { origin, is_active } =>
1064						QueryStatus::VersionNotifier { origin, is_active },
1065					Ready { response, at } => QueryStatus::Ready { response, at },
1066				}
1067			}
1068		}
1069
1070		pub fn migrate_to_v1<T: Config, P: GetStorageVersion + PalletInfoAccess>(
1071		) -> frame_support::weights::Weight {
1072			let on_chain_storage_version = <P as GetStorageVersion>::on_chain_storage_version();
1073			tracing::info!(
1074				target: "runtime::xcm",
1075				?on_chain_storage_version,
1076				"Running migration storage v1 for xcm with storage version",
1077			);
1078
1079			if on_chain_storage_version < 1 {
1080				let mut count = 0;
1081				Queries::<T>::translate::<QueryStatusV0<BlockNumberFor<T>>, _>(|_key, value| {
1082					count += 1;
1083					Some(value.into())
1084				});
1085				StorageVersion::new(1).put::<P>();
1086				tracing::info!(
1087					target: "runtime::xcm",
1088					?on_chain_storage_version,
1089					"Running migration storage v1 for xcm with storage version was complete",
1090				);
1091				// calculate and return migration weights
1092				T::DbWeight::get().reads_writes(count as u64 + 1, count as u64 + 1)
1093			} else {
1094				tracing::warn!(
1095					target: "runtime::xcm",
1096					?on_chain_storage_version,
1097					"Attempted to apply migration to v1 but failed because storage version is",
1098				);
1099				T::DbWeight::get().reads(1)
1100			}
1101		}
1102	}
1103
1104	#[pallet::call(weight(<T as Config>::WeightInfo))]
1105	impl<T: Config> Pallet<T> {
1106		#[pallet::call_index(0)]
1107		pub fn send(
1108			origin: OriginFor<T>,
1109			dest: Box<VersionedLocation>,
1110			message: Box<VersionedXcm<()>>,
1111		) -> DispatchResult {
1112			<Self as SendController<_>>::send(origin, dest, message)?;
1113			Ok(())
1114		}
1115
1116		/// Teleport some assets from the local chain to some destination chain.
1117		///
1118		/// **This function is deprecated: Use `limited_teleport_assets` instead.**
1119		///
1120		/// Fee payment on the destination side is made from the asset in the `assets` vector of
1121		/// index `fee_asset_item`. The weight limit for fees is not provided and thus is unlimited,
1122		/// with all fees taken as needed from the asset.
1123		///
1124		/// - `origin`: Must be capable of withdrawing the `assets` and executing XCM.
1125		/// - `dest`: Destination context for the assets. Will typically be `[Parent,
1126		///   Parachain(..)]` to send from parachain to parachain, or `[Parachain(..)]` to send from
1127		///   relay to parachain.
1128		/// - `beneficiary`: A beneficiary location for the assets in the context of `dest`. Will
1129		///   generally be an `AccountId32` value.
1130		/// - `assets`: The assets to be withdrawn. This should include the assets used to pay the
1131		///   fee on the `dest` chain.
1132		/// - `fee_asset_item`: The index into `assets` of the item which should be used to pay
1133		///   fees.
1134		#[pallet::call_index(1)]
1135		#[allow(deprecated)]
1136		#[deprecated(
1137			note = "This extrinsic uses `WeightLimit::Unlimited`, please migrate to `limited_teleport_assets` or `transfer_assets`"
1138		)]
1139		pub fn teleport_assets(
1140			origin: OriginFor<T>,
1141			dest: Box<VersionedLocation>,
1142			beneficiary: Box<VersionedLocation>,
1143			assets: Box<VersionedAssets>,
1144			fee_asset_item: u32,
1145		) -> DispatchResult {
1146			Self::do_teleport_assets(origin, dest, beneficiary, assets, fee_asset_item, Unlimited)
1147		}
1148
1149		/// Transfer some assets from the local chain to the destination chain through their local,
1150		/// destination or remote reserve.
1151		///
1152		/// `assets` must have same reserve location and may not be teleportable to `dest`.
1153		///  - `assets` have local reserve: transfer assets to sovereign account of destination
1154		///    chain and forward a notification XCM to `dest` to mint and deposit reserve-based
1155		///    assets to `beneficiary`.
1156		///  - `assets` have destination reserve: burn local assets and forward a notification to
1157		///    `dest` chain to withdraw the reserve assets from this chain's sovereign account and
1158		///    deposit them to `beneficiary`.
1159		///  - `assets` have remote reserve: burn local assets, forward XCM to reserve chain to move
1160		///    reserves from this chain's SA to `dest` chain's SA, and forward another XCM to `dest`
1161		///    to mint and deposit reserve-based assets to `beneficiary`.
1162		///
1163		/// **This function is deprecated: Use `limited_reserve_transfer_assets` instead.**
1164		///
1165		/// Fee payment on the destination side is made from the asset in the `assets` vector of
1166		/// index `fee_asset_item`. The weight limit for fees is not provided and thus is unlimited,
1167		/// with all fees taken as needed from the asset.
1168		///
1169		/// - `origin`: Must be capable of withdrawing the `assets` and executing XCM.
1170		/// - `dest`: Destination context for the assets. Will typically be `[Parent,
1171		///   Parachain(..)]` to send from parachain to parachain, or `[Parachain(..)]` to send from
1172		///   relay to parachain.
1173		/// - `beneficiary`: A beneficiary location for the assets in the context of `dest`. Will
1174		///   generally be an `AccountId32` value.
1175		/// - `assets`: The assets to be withdrawn. This should include the assets used to pay the
1176		///   fee on the `dest` (and possibly reserve) chains.
1177		/// - `fee_asset_item`: The index into `assets` of the item which should be used to pay
1178		///   fees.
1179		#[pallet::call_index(2)]
1180		#[allow(deprecated)]
1181		#[deprecated(
1182			note = "This extrinsic uses `WeightLimit::Unlimited`, please migrate to `limited_reserve_transfer_assets` or `transfer_assets`"
1183		)]
1184		pub fn reserve_transfer_assets(
1185			origin: OriginFor<T>,
1186			dest: Box<VersionedLocation>,
1187			beneficiary: Box<VersionedLocation>,
1188			assets: Box<VersionedAssets>,
1189			fee_asset_item: u32,
1190		) -> DispatchResult {
1191			Self::do_reserve_transfer_assets(
1192				origin,
1193				dest,
1194				beneficiary,
1195				assets,
1196				fee_asset_item,
1197				Unlimited,
1198			)
1199		}
1200
1201		/// Execute an XCM message from a local, signed, origin.
1202		///
1203		/// An event is deposited indicating whether `msg` could be executed completely or only
1204		/// partially.
1205		///
1206		/// No more than `max_weight` will be used in its attempted execution. If this is less than
1207		/// the maximum amount of weight that the message could take to be executed, then no
1208		/// execution attempt will be made.
1209		#[pallet::call_index(3)]
1210		#[pallet::weight(max_weight.saturating_add(T::WeightInfo::execute()))]
1211		pub fn execute(
1212			origin: OriginFor<T>,
1213			message: Box<VersionedXcm<<T as Config>::RuntimeCall>>,
1214			max_weight: Weight,
1215		) -> DispatchResultWithPostInfo {
1216			let weight_used =
1217				<Self as ExecuteController<_, _>>::execute(origin, message, max_weight)?;
1218			Ok(Some(weight_used.saturating_add(T::WeightInfo::execute())).into())
1219		}
1220
1221		/// Extoll that a particular destination can be communicated with through a particular
1222		/// version of XCM.
1223		///
1224		/// - `origin`: Must be an origin specified by AdminOrigin.
1225		/// - `location`: The destination that is being described.
1226		/// - `xcm_version`: The latest version of XCM that `location` supports.
1227		#[pallet::call_index(4)]
1228		pub fn force_xcm_version(
1229			origin: OriginFor<T>,
1230			location: Box<Location>,
1231			version: XcmVersion,
1232		) -> DispatchResult {
1233			T::AdminOrigin::ensure_origin(origin)?;
1234			let location = *location;
1235			SupportedVersion::<T>::insert(XCM_VERSION, LatestVersionedLocation(&location), version);
1236			Self::deposit_event(Event::SupportedVersionChanged { location, version });
1237			Ok(())
1238		}
1239
1240		/// Set a safe XCM version (the version that XCM should be encoded with if the most recent
1241		/// version a destination can accept is unknown).
1242		///
1243		/// - `origin`: Must be an origin specified by AdminOrigin.
1244		/// - `maybe_xcm_version`: The default XCM encoding version, or `None` to disable.
1245		#[pallet::call_index(5)]
1246		pub fn force_default_xcm_version(
1247			origin: OriginFor<T>,
1248			maybe_xcm_version: Option<XcmVersion>,
1249		) -> DispatchResult {
1250			T::AdminOrigin::ensure_origin(origin)?;
1251			SafeXcmVersion::<T>::set(maybe_xcm_version);
1252			Ok(())
1253		}
1254
1255		/// Ask a location to notify us regarding their XCM version and any changes to it.
1256		///
1257		/// - `origin`: Must be an origin specified by AdminOrigin.
1258		/// - `location`: The location to which we should subscribe for XCM version notifications.
1259		#[pallet::call_index(6)]
1260		pub fn force_subscribe_version_notify(
1261			origin: OriginFor<T>,
1262			location: Box<VersionedLocation>,
1263		) -> DispatchResult {
1264			T::AdminOrigin::ensure_origin(origin)?;
1265			let location: Location = (*location).try_into().map_err(|()| {
1266				tracing::debug!(
1267					target: "xcm::pallet_xcm::force_subscribe_version_notify",
1268					"Failed to convert VersionedLocation for subscription target"
1269				);
1270				Error::<T>::BadLocation
1271			})?;
1272			Self::request_version_notify(location).map_err(|e| {
1273				tracing::debug!(
1274					target: "xcm::pallet_xcm::force_subscribe_version_notify", error=?e,
1275					"Failed to subscribe for version notifications for location"
1276				);
1277				match e {
1278					XcmError::InvalidLocation => Error::<T>::AlreadySubscribed,
1279					_ => Error::<T>::InvalidOrigin,
1280				}
1281				.into()
1282			})
1283		}
1284
1285		/// Require that a particular destination should no longer notify us regarding any XCM
1286		/// version changes.
1287		///
1288		/// - `origin`: Must be an origin specified by AdminOrigin.
1289		/// - `location`: The location to which we are currently subscribed for XCM version
1290		///   notifications which we no longer desire.
1291		#[pallet::call_index(7)]
1292		pub fn force_unsubscribe_version_notify(
1293			origin: OriginFor<T>,
1294			location: Box<VersionedLocation>,
1295		) -> DispatchResult {
1296			T::AdminOrigin::ensure_origin(origin)?;
1297			let location: Location = (*location).try_into().map_err(|()| {
1298				tracing::debug!(
1299					target: "xcm::pallet_xcm::force_unsubscribe_version_notify",
1300					"Failed to convert VersionedLocation for unsubscription target"
1301				);
1302				Error::<T>::BadLocation
1303			})?;
1304			Self::unrequest_version_notify(location).map_err(|e| {
1305				tracing::debug!(
1306					target: "xcm::pallet_xcm::force_unsubscribe_version_notify", error=?e,
1307					"Failed to unsubscribe from version notifications for location"
1308				);
1309				match e {
1310					XcmError::InvalidLocation => Error::<T>::NoSubscription,
1311					_ => Error::<T>::InvalidOrigin,
1312				}
1313				.into()
1314			})
1315		}
1316
1317		/// Transfer some assets from the local chain to the destination chain through their local,
1318		/// destination or remote reserve.
1319		///
1320		/// `assets` must have same reserve location and may not be teleportable to `dest`.
1321		///  - `assets` have local reserve: transfer assets to sovereign account of destination
1322		///    chain and forward a notification XCM to `dest` to mint and deposit reserve-based
1323		///    assets to `beneficiary`.
1324		///  - `assets` have destination reserve: burn local assets and forward a notification to
1325		///    `dest` chain to withdraw the reserve assets from this chain's sovereign account and
1326		///    deposit them to `beneficiary`.
1327		///  - `assets` have remote reserve: burn local assets, forward XCM to reserve chain to move
1328		///    reserves from this chain's SA to `dest` chain's SA, and forward another XCM to `dest`
1329		///    to mint and deposit reserve-based assets to `beneficiary`.
1330		///
1331		/// Fee payment on the destination side is made from the asset in the `assets` vector of
1332		/// index `fee_asset_item`, up to enough to pay for `weight_limit` of weight. If more weight
1333		/// is needed than `weight_limit`, then the operation will fail and the sent assets may be
1334		/// at risk.
1335		///
1336		/// - `origin`: Must be capable of withdrawing the `assets` and executing XCM.
1337		/// - `dest`: Destination context for the assets. Will typically be `[Parent,
1338		///   Parachain(..)]` to send from parachain to parachain, or `[Parachain(..)]` to send from
1339		///   relay to parachain.
1340		/// - `beneficiary`: A beneficiary location for the assets in the context of `dest`. Will
1341		///   generally be an `AccountId32` value.
1342		/// - `assets`: The assets to be withdrawn. This should include the assets used to pay the
1343		///   fee on the `dest` (and possibly reserve) chains.
1344		/// - `fee_asset_item`: The index into `assets` of the item which should be used to pay
1345		///   fees.
1346		/// - `weight_limit`: The remote-side weight limit, if any, for the XCM fee purchase.
1347		#[pallet::call_index(8)]
1348		#[pallet::weight(T::WeightInfo::reserve_transfer_assets())]
1349		pub fn limited_reserve_transfer_assets(
1350			origin: OriginFor<T>,
1351			dest: Box<VersionedLocation>,
1352			beneficiary: Box<VersionedLocation>,
1353			assets: Box<VersionedAssets>,
1354			fee_asset_item: u32,
1355			weight_limit: WeightLimit,
1356		) -> DispatchResult {
1357			Self::do_reserve_transfer_assets(
1358				origin,
1359				dest,
1360				beneficiary,
1361				assets,
1362				fee_asset_item,
1363				weight_limit,
1364			)
1365		}
1366
1367		/// Teleport some assets from the local chain to some destination chain.
1368		///
1369		/// Fee payment on the destination side is made from the asset in the `assets` vector of
1370		/// index `fee_asset_item`, up to enough to pay for `weight_limit` of weight. If more weight
1371		/// is needed than `weight_limit`, then the operation will fail and the sent assets may be
1372		/// at risk.
1373		///
1374		/// - `origin`: Must be capable of withdrawing the `assets` and executing XCM.
1375		/// - `dest`: Destination context for the assets. Will typically be `[Parent,
1376		///   Parachain(..)]` to send from parachain to parachain, or `[Parachain(..)]` to send from
1377		///   relay to parachain.
1378		/// - `beneficiary`: A beneficiary location for the assets in the context of `dest`. Will
1379		///   generally be an `AccountId32` value.
1380		/// - `assets`: The assets to be withdrawn. This should include the assets used to pay the
1381		///   fee on the `dest` chain.
1382		/// - `fee_asset_item`: The index into `assets` of the item which should be used to pay
1383		///   fees.
1384		/// - `weight_limit`: The remote-side weight limit, if any, for the XCM fee purchase.
1385		#[pallet::call_index(9)]
1386		#[pallet::weight(T::WeightInfo::teleport_assets())]
1387		pub fn limited_teleport_assets(
1388			origin: OriginFor<T>,
1389			dest: Box<VersionedLocation>,
1390			beneficiary: Box<VersionedLocation>,
1391			assets: Box<VersionedAssets>,
1392			fee_asset_item: u32,
1393			weight_limit: WeightLimit,
1394		) -> DispatchResult {
1395			Self::do_teleport_assets(
1396				origin,
1397				dest,
1398				beneficiary,
1399				assets,
1400				fee_asset_item,
1401				weight_limit,
1402			)
1403		}
1404
1405		/// Set or unset the global suspension state of the XCM executor.
1406		///
1407		/// - `origin`: Must be an origin specified by AdminOrigin.
1408		/// - `suspended`: `true` to suspend, `false` to resume.
1409		#[pallet::call_index(10)]
1410		pub fn force_suspension(origin: OriginFor<T>, suspended: bool) -> DispatchResult {
1411			T::AdminOrigin::ensure_origin(origin)?;
1412			XcmExecutionSuspended::<T>::set(suspended);
1413			Ok(())
1414		}
1415
1416		/// Transfer some assets from the local chain to the destination chain through their local,
1417		/// destination or remote reserve, or through teleports.
1418		///
1419		/// Fee payment on the destination side is made from the asset in the `assets` vector of
1420		/// index `fee_asset_item` (hence referred to as `fees`), up to enough to pay for
1421		/// `weight_limit` of weight. If more weight is needed than `weight_limit`, then the
1422		/// operation will fail and the sent assets may be at risk.
1423		///
1424		/// `assets` (excluding `fees`) must have same reserve location or otherwise be teleportable
1425		/// to `dest`, no limitations imposed on `fees`.
1426		///  - for local reserve: transfer assets to sovereign account of destination chain and
1427		///    forward a notification XCM to `dest` to mint and deposit reserve-based assets to
1428		///    `beneficiary`.
1429		///  - for destination reserve: burn local assets and forward a notification to `dest` chain
1430		///    to withdraw the reserve assets from this chain's sovereign account and deposit them
1431		///    to `beneficiary`.
1432		///  - for remote reserve: burn local assets, forward XCM to reserve chain to move reserves
1433		///    from this chain's SA to `dest` chain's SA, and forward another XCM to `dest` to mint
1434		///    and deposit reserve-based assets to `beneficiary`.
1435		///  - for teleports: burn local assets and forward XCM to `dest` chain to mint/teleport
1436		///    assets and deposit them to `beneficiary`.
1437		///
1438		/// - `origin`: Must be capable of withdrawing the `assets` and executing XCM.
1439		/// - `dest`: Destination context for the assets. Will typically be `X2(Parent,
1440		///   Parachain(..))` to send from parachain to parachain, or `X1(Parachain(..))` to send
1441		///   from relay to parachain.
1442		/// - `beneficiary`: A beneficiary location for the assets in the context of `dest`. Will
1443		///   generally be an `AccountId32` value.
1444		/// - `assets`: The assets to be withdrawn. This should include the assets used to pay the
1445		///   fee on the `dest` (and possibly reserve) chains.
1446		/// - `fee_asset_item`: The index into `assets` of the item which should be used to pay
1447		///   fees.
1448		/// - `weight_limit`: The remote-side weight limit, if any, for the XCM fee purchase.
1449		#[pallet::call_index(11)]
1450		pub fn transfer_assets(
1451			origin: OriginFor<T>,
1452			dest: Box<VersionedLocation>,
1453			beneficiary: Box<VersionedLocation>,
1454			assets: Box<VersionedAssets>,
1455			fee_asset_item: u32,
1456			weight_limit: WeightLimit,
1457		) -> DispatchResult {
1458			let origin = T::ExecuteXcmOrigin::ensure_origin(origin)?;
1459			let dest = (*dest).try_into().map_err(|()| {
1460				tracing::debug!(
1461					target: "xcm::pallet_xcm::transfer_assets",
1462					"Failed to convert destination VersionedLocation",
1463				);
1464				Error::<T>::BadVersion
1465			})?;
1466			let beneficiary: Location = (*beneficiary).try_into().map_err(|()| {
1467				tracing::debug!(
1468					target: "xcm::pallet_xcm::transfer_assets",
1469					"Failed to convert beneficiary VersionedLocation",
1470				);
1471				Error::<T>::BadVersion
1472			})?;
1473			let assets: Assets = (*assets).try_into().map_err(|()| {
1474				tracing::debug!(
1475					target: "xcm::pallet_xcm::transfer_assets",
1476					"Failed to convert VersionedAssets",
1477				);
1478				Error::<T>::BadVersion
1479			})?;
1480			tracing::debug!(
1481				target: "xcm::pallet_xcm::transfer_assets",
1482				?origin, ?dest, ?beneficiary, ?assets, ?fee_asset_item, ?weight_limit,
1483			);
1484
1485			ensure!(assets.len() <= MAX_ASSETS_FOR_TRANSFER, Error::<T>::TooManyAssets);
1486			let assets = assets.into_inner();
1487			let fee_asset_item = fee_asset_item as usize;
1488			// Find transfer types for fee and non-fee assets.
1489			let (fees_transfer_type, assets_transfer_type) =
1490				Self::find_fee_and_assets_transfer_types(&assets, fee_asset_item, &dest)?;
1491
1492			// We check for network native asset reserve transfers in preparation for the Asset Hub
1493			// Migration. This check will be removed after the migration and the determined
1494			// reserve location adjusted accordingly. For more information, see https://github.com/paritytech/polkadot-sdk/issues/9054.
1495			Self::ensure_network_asset_reserve_transfer_allowed(
1496				&assets,
1497				fee_asset_item,
1498				&assets_transfer_type,
1499				&fees_transfer_type,
1500			)?;
1501
1502			Self::do_transfer_assets(
1503				origin,
1504				dest,
1505				Either::Left(beneficiary),
1506				assets,
1507				assets_transfer_type,
1508				fee_asset_item,
1509				fees_transfer_type,
1510				weight_limit,
1511			)
1512		}
1513
1514		/// Claims assets trapped on this pallet because of leftover assets during XCM execution.
1515		///
1516		/// - `origin`: Anyone can call this extrinsic.
1517		/// - `assets`: The exact assets that were trapped. Use the version to specify what version
1518		/// was the latest when they were trapped.
1519		/// - `beneficiary`: The location/account where the claimed assets will be deposited.
1520		#[pallet::call_index(12)]
1521		pub fn claim_assets(
1522			origin: OriginFor<T>,
1523			assets: Box<VersionedAssets>,
1524			beneficiary: Box<VersionedLocation>,
1525		) -> DispatchResult {
1526			let origin_location = T::ExecuteXcmOrigin::ensure_origin(origin)?;
1527			tracing::debug!(target: "xcm::pallet_xcm::claim_assets", ?origin_location, ?assets, ?beneficiary);
1528			// Extract version from `assets`.
1529			let assets_version = assets.identify_version();
1530			let assets: Assets = (*assets).try_into().map_err(|()| {
1531				tracing::debug!(
1532					target: "xcm::pallet_xcm::claim_assets",
1533					"Failed to convert input VersionedAssets",
1534				);
1535				Error::<T>::BadVersion
1536			})?;
1537			let number_of_assets = assets.len() as u32;
1538			let beneficiary: Location = (*beneficiary).try_into().map_err(|()| {
1539				tracing::debug!(
1540					target: "xcm::pallet_xcm::claim_assets",
1541					"Failed to convert beneficiary VersionedLocation",
1542				);
1543				Error::<T>::BadVersion
1544			})?;
1545			let ticket: Location = GeneralIndex(assets_version as u128).into();
1546			let mut message = Xcm(vec![
1547				ClaimAsset { assets, ticket },
1548				DepositAsset { assets: AllCounted(number_of_assets).into(), beneficiary },
1549			]);
1550			let weight = T::Weigher::weight(&mut message, Weight::MAX).map_err(|error| {
1551				tracing::debug!(target: "xcm::pallet_xcm::claim_assets", ?error, "Failed to calculate weight");
1552				Error::<T>::UnweighableMessage
1553			})?;
1554			let mut hash = message.using_encoded(sp_io::hashing::blake2_256);
1555			let outcome = T::XcmExecutor::prepare_and_execute(
1556				origin_location,
1557				message,
1558				&mut hash,
1559				weight,
1560				weight,
1561			);
1562			outcome.ensure_complete().map_err(|error| {
1563				tracing::error!(target: "xcm::pallet_xcm::claim_assets", ?error, "XCM execution failed with error");
1564				Error::<T>::LocalExecutionIncompleteWithError { index: error.index, error: error.error.into()}
1565			})?;
1566			Ok(())
1567		}
1568
1569		/// Transfer assets from the local chain to the destination chain using explicit transfer
1570		/// types for assets and fees.
1571		///
1572		/// `assets` must have same reserve location or may be teleportable to `dest`. Caller must
1573		/// provide the `assets_transfer_type` to be used for `assets`:
1574		///  - `TransferType::LocalReserve`: transfer assets to sovereign account of destination
1575		///    chain and forward a notification XCM to `dest` to mint and deposit reserve-based
1576		///    assets to `beneficiary`.
1577		///  - `TransferType::DestinationReserve`: burn local assets and forward a notification to
1578		///    `dest` chain to withdraw the reserve assets from this chain's sovereign account and
1579		///    deposit them to `beneficiary`.
1580		///  - `TransferType::RemoteReserve(reserve)`: burn local assets, forward XCM to `reserve`
1581		///    chain to move reserves from this chain's SA to `dest` chain's SA, and forward another
1582		///    XCM to `dest` to mint and deposit reserve-based assets to `beneficiary`. Typically
1583		///    the remote `reserve` is Asset Hub.
1584		///  - `TransferType::Teleport`: burn local assets and forward XCM to `dest` chain to
1585		///    mint/teleport assets and deposit them to `beneficiary`.
1586		///
1587		/// On the destination chain, as well as any intermediary hops, `BuyExecution` is used to
1588		/// buy execution using transferred `assets` identified by `remote_fees_id`.
1589		/// Make sure enough of the specified `remote_fees_id` asset is included in the given list
1590		/// of `assets`. `remote_fees_id` should be enough to pay for `weight_limit`. If more weight
1591		/// is needed than `weight_limit`, then the operation will fail and the sent assets may be
1592		/// at risk.
1593		///
1594		/// `remote_fees_id` may use different transfer type than rest of `assets` and can be
1595		/// specified through `fees_transfer_type`.
1596		///
1597		/// The caller needs to specify what should happen to the transferred assets once they reach
1598		/// the `dest` chain. This is done through the `custom_xcm_on_dest` parameter, which
1599		/// contains the instructions to execute on `dest` as a final step.
1600		///   This is usually as simple as:
1601		///   `Xcm(vec![DepositAsset { assets: Wild(AllCounted(assets.len())), beneficiary }])`,
1602		///   but could be something more exotic like sending the `assets` even further.
1603		///
1604		/// - `origin`: Must be capable of withdrawing the `assets` and executing XCM.
1605		/// - `dest`: Destination context for the assets. Will typically be `[Parent,
1606		///   Parachain(..)]` to send from parachain to parachain, or `[Parachain(..)]` to send from
1607		///   relay to parachain, or `(parents: 2, (GlobalConsensus(..), ..))` to send from
1608		///   parachain across a bridge to another ecosystem destination.
1609		/// - `assets`: The assets to be withdrawn. This should include the assets used to pay the
1610		///   fee on the `dest` (and possibly reserve) chains.
1611		/// - `assets_transfer_type`: The XCM `TransferType` used to transfer the `assets`.
1612		/// - `remote_fees_id`: One of the included `assets` to be used to pay fees.
1613		/// - `fees_transfer_type`: The XCM `TransferType` used to transfer the `fees` assets.
1614		/// - `custom_xcm_on_dest`: The XCM to be executed on `dest` chain as the last step of the
1615		///   transfer, which also determines what happens to the assets on the destination chain.
1616		/// - `weight_limit`: The remote-side weight limit, if any, for the XCM fee purchase.
1617		#[pallet::call_index(13)]
1618		#[pallet::weight(T::WeightInfo::transfer_assets())]
1619		pub fn transfer_assets_using_type_and_then(
1620			origin: OriginFor<T>,
1621			dest: Box<VersionedLocation>,
1622			assets: Box<VersionedAssets>,
1623			assets_transfer_type: Box<TransferType>,
1624			remote_fees_id: Box<VersionedAssetId>,
1625			fees_transfer_type: Box<TransferType>,
1626			custom_xcm_on_dest: Box<VersionedXcm<()>>,
1627			weight_limit: WeightLimit,
1628		) -> DispatchResult {
1629			let origin_location = T::ExecuteXcmOrigin::ensure_origin(origin)?;
1630			let dest: Location = (*dest).try_into().map_err(|()| {
1631				tracing::debug!(
1632					target: "xcm::pallet_xcm::transfer_assets_using_type_and_then",
1633					"Failed to convert destination VersionedLocation",
1634				);
1635				Error::<T>::BadVersion
1636			})?;
1637			let assets: Assets = (*assets).try_into().map_err(|()| {
1638				tracing::debug!(
1639					target: "xcm::pallet_xcm::transfer_assets_using_type_and_then",
1640					"Failed to convert VersionedAssets",
1641				);
1642				Error::<T>::BadVersion
1643			})?;
1644			let fees_id: AssetId = (*remote_fees_id).try_into().map_err(|()| {
1645				tracing::debug!(
1646					target: "xcm::pallet_xcm::transfer_assets_using_type_and_then",
1647					"Failed to convert remote_fees_id VersionedAssetId",
1648				);
1649				Error::<T>::BadVersion
1650			})?;
1651			let remote_xcm: Xcm<()> = (*custom_xcm_on_dest).try_into().map_err(|()| {
1652				tracing::debug!(
1653					target: "xcm::pallet_xcm::transfer_assets_using_type_and_then",
1654					"Failed to convert custom_xcm_on_dest VersionedXcm",
1655				);
1656				Error::<T>::BadVersion
1657			})?;
1658			tracing::debug!(
1659				target: "xcm::pallet_xcm::transfer_assets_using_type_and_then",
1660				?origin_location, ?dest, ?assets, ?assets_transfer_type, ?fees_id, ?fees_transfer_type,
1661				?remote_xcm, ?weight_limit,
1662			);
1663
1664			let assets = assets.into_inner();
1665			ensure!(assets.len() <= MAX_ASSETS_FOR_TRANSFER, Error::<T>::TooManyAssets);
1666
1667			let fee_asset_index =
1668				assets.iter().position(|a| a.id == fees_id).ok_or(Error::<T>::FeesNotMet)?;
1669			Self::do_transfer_assets(
1670				origin_location,
1671				dest,
1672				Either::Right(remote_xcm),
1673				assets,
1674				*assets_transfer_type,
1675				fee_asset_index,
1676				*fees_transfer_type,
1677				weight_limit,
1678			)
1679		}
1680
1681		/// Authorize another `aliaser` location to alias into the local `origin` making this call.
1682		/// The `aliaser` is only authorized until the provided `expiry` block number.
1683		/// The call can also be used for a previously authorized alias in order to update its
1684		/// `expiry` block number.
1685		///
1686		/// Usually useful to allow your local account to be aliased into from a remote location
1687		/// also under your control (like your account on another chain).
1688		///
1689		/// WARNING: make sure the caller `origin` (you) trusts the `aliaser` location to act in
1690		/// their/your name. Once authorized using this call, the `aliaser` can freely impersonate
1691		/// `origin` in XCM programs executed on the local chain.
1692		#[pallet::call_index(14)]
1693		pub fn add_authorized_alias(
1694			origin: OriginFor<T>,
1695			aliaser: Box<VersionedLocation>,
1696			expires: Option<u64>,
1697		) -> DispatchResult {
1698			let signed_origin = ensure_signed(origin.clone())?;
1699			let origin_location: Location = T::ExecuteXcmOrigin::ensure_origin(origin)?;
1700			let new_aliaser: Location = (*aliaser).try_into().map_err(|()| {
1701				tracing::debug!(
1702					target: "xcm::pallet_xcm::add_authorized_alias",
1703					"Failed to convert aliaser VersionedLocation",
1704				);
1705				Error::<T>::BadVersion
1706			})?;
1707			ensure!(origin_location != new_aliaser, Error::<T>::BadLocation);
1708			// remove `network` from inner `AccountId32` for easier matching
1709			let origin_location = match origin_location.unpack() {
1710				(0, [AccountId32 { network: _, id }]) =>
1711					Location::new(0, [AccountId32 { network: None, id: *id }]),
1712				_ => return Err(Error::<T>::InvalidOrigin.into()),
1713			};
1714			tracing::debug!(target: "xcm::pallet_xcm::add_authorized_alias", ?origin_location, ?new_aliaser, ?expires);
1715			ensure!(origin_location != new_aliaser, Error::<T>::BadLocation);
1716			if let Some(expiry) = expires {
1717				ensure!(
1718					expiry >
1719						frame_system::Pallet::<T>::current_block_number().saturated_into::<u64>(),
1720					Error::<T>::ExpiresInPast
1721				);
1722			}
1723			let versioned_origin = VersionedLocation::from(origin_location.clone());
1724			let versioned_aliaser = VersionedLocation::from(new_aliaser.clone());
1725			let entry = if let Some(entry) = AuthorizedAliases::<T>::get(&versioned_origin) {
1726				// entry already exists, update it
1727				let (mut aliasers, mut ticket) = (entry.aliasers, entry.ticket);
1728				if let Some(aliaser) =
1729					aliasers.iter_mut().find(|aliaser| aliaser.location == versioned_aliaser)
1730				{
1731					// if the aliaser already exists, just update its expiry block
1732					aliaser.expiry = expires;
1733				} else {
1734					// if it doesn't, we try to add it
1735					let aliaser =
1736						OriginAliaser { location: versioned_aliaser.clone(), expiry: expires };
1737					aliasers.try_push(aliaser).map_err(|_| {
1738						tracing::debug!(
1739							target: "xcm::pallet_xcm::add_authorized_alias",
1740							"Failed to add new aliaser to existing entry",
1741						);
1742						Error::<T>::TooManyAuthorizedAliases
1743					})?;
1744					// we try to update the ticket (the storage deposit)
1745					ticket = ticket.update(&signed_origin, aliasers_footprint(aliasers.len()))?;
1746				}
1747				AuthorizedAliasesEntry { aliasers, ticket }
1748			} else {
1749				// add new entry with its first alias
1750				let ticket = TicketOf::<T>::new(&signed_origin, aliasers_footprint(1))?;
1751				let aliaser =
1752					OriginAliaser { location: versioned_aliaser.clone(), expiry: expires };
1753				let mut aliasers = BoundedVec::<OriginAliaser, MaxAuthorizedAliases>::new();
1754				aliasers.try_push(aliaser).map_err(|error| {
1755					tracing::debug!(
1756						target: "xcm::pallet_xcm::add_authorized_alias", ?error,
1757						"Failed to add first aliaser to new entry",
1758					);
1759					Error::<T>::TooManyAuthorizedAliases
1760				})?;
1761				AuthorizedAliasesEntry { aliasers, ticket }
1762			};
1763			// write to storage
1764			AuthorizedAliases::<T>::insert(&versioned_origin, entry);
1765			Self::deposit_event(Event::AliasAuthorized {
1766				aliaser: new_aliaser,
1767				target: origin_location,
1768				expiry: expires,
1769			});
1770			Ok(())
1771		}
1772
1773		/// Remove a previously authorized `aliaser` from the list of locations that can alias into
1774		/// the local `origin` making this call.
1775		#[pallet::call_index(15)]
1776		pub fn remove_authorized_alias(
1777			origin: OriginFor<T>,
1778			aliaser: Box<VersionedLocation>,
1779		) -> DispatchResult {
1780			let signed_origin = ensure_signed(origin.clone())?;
1781			let origin_location: Location = T::ExecuteXcmOrigin::ensure_origin(origin)?;
1782			let to_remove: Location = (*aliaser).try_into().map_err(|()| {
1783				tracing::debug!(
1784					target: "xcm::pallet_xcm::remove_authorized_alias",
1785					"Failed to convert aliaser VersionedLocation",
1786				);
1787				Error::<T>::BadVersion
1788			})?;
1789			ensure!(origin_location != to_remove, Error::<T>::BadLocation);
1790			// remove `network` from inner `AccountId32` for easier matching
1791			let origin_location = match origin_location.unpack() {
1792				(0, [AccountId32 { network: _, id }]) =>
1793					Location::new(0, [AccountId32 { network: None, id: *id }]),
1794				_ => return Err(Error::<T>::InvalidOrigin.into()),
1795			};
1796			tracing::debug!(target: "xcm::pallet_xcm::remove_authorized_alias", ?origin_location, ?to_remove);
1797			ensure!(origin_location != to_remove, Error::<T>::BadLocation);
1798			// convert to latest versioned
1799			let versioned_origin = VersionedLocation::from(origin_location.clone());
1800			let versioned_to_remove = VersionedLocation::from(to_remove.clone());
1801			AuthorizedAliases::<T>::get(&versioned_origin)
1802				.ok_or(Error::<T>::AliasNotFound.into())
1803				.and_then(|entry| {
1804					let (mut aliasers, mut ticket) = (entry.aliasers, entry.ticket);
1805					let old_len = aliasers.len();
1806					aliasers.retain(|alias| versioned_to_remove.ne(&alias.location));
1807					let new_len = aliasers.len();
1808					if aliasers.is_empty() {
1809						// remove entry altogether and return all storage deposit
1810						ticket.drop(&signed_origin)?;
1811						AuthorizedAliases::<T>::remove(&versioned_origin);
1812						Self::deposit_event(Event::AliasAuthorizationRemoved {
1813							aliaser: to_remove,
1814							target: origin_location,
1815						});
1816						Ok(())
1817					} else if old_len != new_len {
1818						// update aliasers and storage deposit
1819						ticket = ticket.update(&signed_origin, aliasers_footprint(new_len))?;
1820						let entry = AuthorizedAliasesEntry { aliasers, ticket };
1821						AuthorizedAliases::<T>::insert(&versioned_origin, entry);
1822						Self::deposit_event(Event::AliasAuthorizationRemoved {
1823							aliaser: to_remove,
1824							target: origin_location,
1825						});
1826						Ok(())
1827					} else {
1828						Err(Error::<T>::AliasNotFound.into())
1829					}
1830				})
1831		}
1832
1833		/// Remove all previously authorized `aliaser`s that can alias into the local `origin`
1834		/// making this call.
1835		#[pallet::call_index(16)]
1836		#[pallet::weight(T::WeightInfo::remove_authorized_alias())]
1837		pub fn remove_all_authorized_aliases(origin: OriginFor<T>) -> DispatchResult {
1838			let signed_origin = ensure_signed(origin.clone())?;
1839			let origin_location: Location = T::ExecuteXcmOrigin::ensure_origin(origin)?;
1840			// remove `network` from inner `AccountId32` for easier matching
1841			let origin_location = match origin_location.unpack() {
1842				(0, [AccountId32 { network: _, id }]) =>
1843					Location::new(0, [AccountId32 { network: None, id: *id }]),
1844				_ => return Err(Error::<T>::InvalidOrigin.into()),
1845			};
1846			tracing::debug!(target: "xcm::pallet_xcm::remove_all_authorized_aliases", ?origin_location);
1847			// convert to latest versioned
1848			let versioned_origin = VersionedLocation::from(origin_location.clone());
1849			if let Some(entry) = AuthorizedAliases::<T>::get(&versioned_origin) {
1850				// remove entry altogether and return all storage deposit
1851				entry.ticket.drop(&signed_origin)?;
1852				AuthorizedAliases::<T>::remove(&versioned_origin);
1853				Self::deposit_event(Event::AliasesAuthorizationsRemoved {
1854					target: origin_location,
1855				});
1856				Ok(())
1857			} else {
1858				tracing::debug!(target: "xcm::pallet_xcm::remove_all_authorized_aliases", "No authorized alias entry found for the origin");
1859				Err(Error::<T>::AliasNotFound.into())
1860			}
1861		}
1862	}
1863}
1864
1865/// The maximum number of distinct assets allowed to be transferred in a single helper extrinsic.
1866const MAX_ASSETS_FOR_TRANSFER: usize = 2;
1867
1868/// Specify how assets used for fees are handled during asset transfers.
1869#[derive(Clone, PartialEq)]
1870enum FeesHandling<T: Config> {
1871	/// `fees` asset can be batch-transferred with rest of assets using same XCM instructions.
1872	Batched { fees: Asset },
1873	/// fees cannot be batched, they are handled separately using XCM programs here.
1874	Separate { local_xcm: Xcm<<T as Config>::RuntimeCall>, remote_xcm: Xcm<()> },
1875}
1876
1877impl<T: Config> core::fmt::Debug for FeesHandling<T> {
1878	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1879		match self {
1880			Self::Batched { fees } => write!(f, "FeesHandling::Batched({:?})", fees),
1881			Self::Separate { local_xcm, remote_xcm } => write!(
1882				f,
1883				"FeesHandling::Separate(local: {:?}, remote: {:?})",
1884				local_xcm, remote_xcm
1885			),
1886		}
1887	}
1888}
1889
1890impl<T: Config> QueryHandler for Pallet<T> {
1891	type BlockNumber = BlockNumberFor<T>;
1892	type Error = XcmError;
1893	type UniversalLocation = T::UniversalLocation;
1894
1895	/// Attempt to create a new query ID and register it as a query that is yet to respond.
1896	fn new_query(
1897		responder: impl Into<Location>,
1898		timeout: BlockNumberFor<T>,
1899		match_querier: impl Into<Location>,
1900	) -> QueryId {
1901		Self::do_new_query(responder, None, timeout, match_querier)
1902	}
1903
1904	/// To check the status of the query, use `fn query()` passing the resultant `QueryId`
1905	/// value.
1906	fn report_outcome(
1907		message: &mut Xcm<()>,
1908		responder: impl Into<Location>,
1909		timeout: Self::BlockNumber,
1910	) -> Result<QueryId, Self::Error> {
1911		let responder = responder.into();
1912		let destination =
1913			Self::UniversalLocation::get().invert_target(&responder).map_err(|()| {
1914				tracing::debug!(
1915					target: "xcm::pallet_xcm::report_outcome",
1916					"Failed to invert responder Location",
1917				);
1918				XcmError::LocationNotInvertible
1919			})?;
1920		let query_id = Self::new_query(responder, timeout, Here);
1921		let response_info = QueryResponseInfo { destination, query_id, max_weight: Weight::zero() };
1922		let report_error = Xcm(vec![ReportError(response_info)]);
1923		message.0.insert(0, SetAppendix(report_error));
1924		Ok(query_id)
1925	}
1926
1927	/// Removes response when ready and emits [Event::ResponseTaken] event.
1928	fn take_response(query_id: QueryId) -> QueryResponseStatus<Self::BlockNumber> {
1929		match Queries::<T>::get(query_id) {
1930			Some(QueryStatus::Ready { response, at }) => match response.try_into() {
1931				Ok(response) => {
1932					Queries::<T>::remove(query_id);
1933					Self::deposit_event(Event::ResponseTaken { query_id });
1934					QueryResponseStatus::Ready { response, at }
1935				},
1936				Err(_) => {
1937					tracing::debug!(
1938						target: "xcm::pallet_xcm::take_response", ?query_id,
1939						"Failed to convert VersionedResponse to Response for query",
1940					);
1941					QueryResponseStatus::UnexpectedVersion
1942				},
1943			},
1944			Some(QueryStatus::Pending { timeout, .. }) => QueryResponseStatus::Pending { timeout },
1945			Some(_) => {
1946				tracing::debug!(
1947					target: "xcm::pallet_xcm::take_response", ?query_id,
1948					"Unexpected QueryStatus variant for query",
1949				);
1950				QueryResponseStatus::UnexpectedVersion
1951			},
1952			None => {
1953				tracing::debug!(
1954					target: "xcm::pallet_xcm::take_response", ?query_id,
1955					"Query ID not found`",
1956				);
1957				QueryResponseStatus::NotFound
1958			},
1959		}
1960	}
1961
1962	#[cfg(feature = "runtime-benchmarks")]
1963	fn expect_response(id: QueryId, response: Response) {
1964		let response = response.into();
1965		Queries::<T>::insert(
1966			id,
1967			QueryStatus::Ready { response, at: frame_system::Pallet::<T>::current_block_number() },
1968		);
1969	}
1970}
1971
1972impl<T: Config> Pallet<T> {
1973	/// The ongoing queries.
1974	pub fn query(query_id: &QueryId) -> Option<QueryStatus<BlockNumberFor<T>>> {
1975		Queries::<T>::get(query_id)
1976	}
1977
1978	/// The existing asset traps.
1979	///
1980	/// Key is the blake2 256 hash of (origin, versioned `Assets`) pair.
1981	/// Value is the number of times this pair has been trapped
1982	/// (usually just 1 if it exists at all).
1983	pub fn asset_trap(trap_id: &H256) -> u32 {
1984		AssetTraps::<T>::get(trap_id)
1985	}
1986
1987	/// Find `TransferType`s for `assets` and fee identified through `fee_asset_item`, when
1988	/// transferring to `dest`.
1989	///
1990	/// Validate `assets` to all have same `TransferType`.
1991	fn find_fee_and_assets_transfer_types(
1992		assets: &[Asset],
1993		fee_asset_item: usize,
1994		dest: &Location,
1995	) -> Result<(TransferType, TransferType), Error<T>> {
1996		let mut fees_transfer_type = None;
1997		let mut assets_transfer_type = None;
1998		for (idx, asset) in assets.iter().enumerate() {
1999			if let Fungible(x) = asset.fun {
2000				// If fungible asset, ensure non-zero amount.
2001				ensure!(!x.is_zero(), Error::<T>::Empty);
2002			}
2003			let transfer_type =
2004				T::XcmExecutor::determine_for(&asset, dest).map_err(Error::<T>::from)?;
2005			if idx == fee_asset_item {
2006				fees_transfer_type = Some(transfer_type);
2007			} else {
2008				if let Some(existing) = assets_transfer_type.as_ref() {
2009					// Ensure transfer for multiple assets uses same transfer type (only fee may
2010					// have different transfer type/path)
2011					ensure!(existing == &transfer_type, Error::<T>::TooManyReserves);
2012				} else {
2013					// asset reserve identified
2014					assets_transfer_type = Some(transfer_type);
2015				}
2016			}
2017		}
2018		// single asset also marked as fee item
2019		if assets.len() == 1 {
2020			assets_transfer_type = fees_transfer_type.clone()
2021		}
2022		Ok((
2023			fees_transfer_type.ok_or(Error::<T>::Empty)?,
2024			assets_transfer_type.ok_or(Error::<T>::Empty)?,
2025		))
2026	}
2027
2028	fn do_reserve_transfer_assets(
2029		origin: OriginFor<T>,
2030		dest: Box<VersionedLocation>,
2031		beneficiary: Box<VersionedLocation>,
2032		assets: Box<VersionedAssets>,
2033		fee_asset_item: u32,
2034		weight_limit: WeightLimit,
2035	) -> DispatchResult {
2036		let origin_location = T::ExecuteXcmOrigin::ensure_origin(origin)?;
2037		let dest = (*dest).try_into().map_err(|()| {
2038			tracing::debug!(
2039				target: "xcm::pallet_xcm::do_reserve_transfer_assets",
2040				"Failed to convert destination VersionedLocation",
2041			);
2042			Error::<T>::BadVersion
2043		})?;
2044		let beneficiary: Location = (*beneficiary).try_into().map_err(|()| {
2045			tracing::debug!(
2046				target: "xcm::pallet_xcm::do_reserve_transfer_assets",
2047				"Failed to convert beneficiary VersionedLocation",
2048			);
2049			Error::<T>::BadVersion
2050		})?;
2051		let assets: Assets = (*assets).try_into().map_err(|()| {
2052			tracing::debug!(
2053				target: "xcm::pallet_xcm::do_reserve_transfer_assets",
2054				"Failed to convert VersionedAssets",
2055			);
2056			Error::<T>::BadVersion
2057		})?;
2058		tracing::debug!(
2059			target: "xcm::pallet_xcm::do_reserve_transfer_assets",
2060			?origin_location, ?dest, ?beneficiary, ?assets, ?fee_asset_item,
2061		);
2062
2063		ensure!(assets.len() <= MAX_ASSETS_FOR_TRANSFER, Error::<T>::TooManyAssets);
2064		let value = (origin_location, assets.into_inner());
2065		ensure!(T::XcmReserveTransferFilter::contains(&value), Error::<T>::Filtered);
2066		let (origin, assets) = value;
2067
2068		let fee_asset_item = fee_asset_item as usize;
2069		let fees = assets.get(fee_asset_item as usize).ok_or(Error::<T>::Empty)?.clone();
2070
2071		// Find transfer types for fee and non-fee assets.
2072		let (fees_transfer_type, assets_transfer_type) =
2073			Self::find_fee_and_assets_transfer_types(&assets, fee_asset_item, &dest)?;
2074		// Ensure assets (and fees according to check below) are not teleportable to `dest`.
2075		ensure!(assets_transfer_type != TransferType::Teleport, Error::<T>::Filtered);
2076		// Ensure all assets (including fees) have same reserve location.
2077		ensure!(assets_transfer_type == fees_transfer_type, Error::<T>::TooManyReserves);
2078
2079		// We check for network native asset reserve transfers in preparation for the Asset Hub
2080		// Migration. This check will be removed after the migration and the determined
2081		// reserve location adjusted accordingly. For more information, see https://github.com/paritytech/polkadot-sdk/issues/9054.
2082		Self::ensure_network_asset_reserve_transfer_allowed(
2083			&assets,
2084			fee_asset_item,
2085			&assets_transfer_type,
2086			&fees_transfer_type,
2087		)?;
2088
2089		let (local_xcm, remote_xcm) = Self::build_xcm_transfer_type(
2090			origin.clone(),
2091			dest.clone(),
2092			Either::Left(beneficiary),
2093			assets,
2094			assets_transfer_type,
2095			FeesHandling::Batched { fees },
2096			weight_limit,
2097		)?;
2098		Self::execute_xcm_transfer(origin, dest, local_xcm, remote_xcm)
2099	}
2100
2101	fn do_teleport_assets(
2102		origin: OriginFor<T>,
2103		dest: Box<VersionedLocation>,
2104		beneficiary: Box<VersionedLocation>,
2105		assets: Box<VersionedAssets>,
2106		fee_asset_item: u32,
2107		weight_limit: WeightLimit,
2108	) -> DispatchResult {
2109		let origin_location = T::ExecuteXcmOrigin::ensure_origin(origin)?;
2110		let dest = (*dest).try_into().map_err(|()| {
2111			tracing::debug!(
2112				target: "xcm::pallet_xcm::do_teleport_assets",
2113				"Failed to convert destination VersionedLocation",
2114			);
2115			Error::<T>::BadVersion
2116		})?;
2117		let beneficiary: Location = (*beneficiary).try_into().map_err(|()| {
2118			tracing::debug!(
2119				target: "xcm::pallet_xcm::do_teleport_assets",
2120				"Failed to convert beneficiary VersionedLocation",
2121			);
2122			Error::<T>::BadVersion
2123		})?;
2124		let assets: Assets = (*assets).try_into().map_err(|()| {
2125			tracing::debug!(
2126				target: "xcm::pallet_xcm::do_teleport_assets",
2127				"Failed to convert VersionedAssets",
2128			);
2129			Error::<T>::BadVersion
2130		})?;
2131		tracing::debug!(
2132			target: "xcm::pallet_xcm::do_teleport_assets",
2133			?origin_location, ?dest, ?beneficiary, ?assets, ?fee_asset_item, ?weight_limit,
2134		);
2135
2136		ensure!(assets.len() <= MAX_ASSETS_FOR_TRANSFER, Error::<T>::TooManyAssets);
2137		let value = (origin_location, assets.into_inner());
2138		ensure!(T::XcmTeleportFilter::contains(&value), Error::<T>::Filtered);
2139		let (origin_location, assets) = value;
2140		for asset in assets.iter() {
2141			let transfer_type =
2142				T::XcmExecutor::determine_for(asset, &dest).map_err(Error::<T>::from)?;
2143			ensure!(transfer_type == TransferType::Teleport, Error::<T>::Filtered);
2144		}
2145		let fees = assets.get(fee_asset_item as usize).ok_or(Error::<T>::Empty)?.clone();
2146
2147		let (local_xcm, remote_xcm) = Self::build_xcm_transfer_type(
2148			origin_location.clone(),
2149			dest.clone(),
2150			Either::Left(beneficiary),
2151			assets,
2152			TransferType::Teleport,
2153			FeesHandling::Batched { fees },
2154			weight_limit,
2155		)?;
2156		Self::execute_xcm_transfer(origin_location, dest, local_xcm, remote_xcm)
2157	}
2158
2159	fn do_transfer_assets(
2160		origin: Location,
2161		dest: Location,
2162		beneficiary: Either<Location, Xcm<()>>,
2163		mut assets: Vec<Asset>,
2164		assets_transfer_type: TransferType,
2165		fee_asset_index: usize,
2166		fees_transfer_type: TransferType,
2167		weight_limit: WeightLimit,
2168	) -> DispatchResult {
2169		// local and remote XCM programs to potentially handle fees separately
2170		let fees = if fees_transfer_type == assets_transfer_type {
2171			let fees = assets.get(fee_asset_index).ok_or(Error::<T>::Empty)?.clone();
2172			// no need for custom fees instructions, fees are batched with assets
2173			FeesHandling::Batched { fees }
2174		} else {
2175			// Disallow _remote reserves_ unless assets & fees have same remote reserve (covered
2176			// by branch above). The reason for this is that we'd need to send XCMs to separate
2177			// chains with no guarantee of delivery order on final destination; therefore we
2178			// cannot guarantee to have fees in place on final destination chain to pay for
2179			// assets transfer.
2180			ensure!(
2181				!matches!(assets_transfer_type, TransferType::RemoteReserve(_)),
2182				Error::<T>::InvalidAssetUnsupportedReserve
2183			);
2184			let weight_limit = weight_limit.clone();
2185			// remove `fees` from `assets` and build separate fees transfer instructions to be
2186			// added to assets transfers XCM programs
2187			let fees = assets.remove(fee_asset_index);
2188			let (local_xcm, remote_xcm) = match fees_transfer_type {
2189				TransferType::LocalReserve => Self::local_reserve_fees_instructions(
2190					origin.clone(),
2191					dest.clone(),
2192					fees,
2193					weight_limit,
2194				)?,
2195				TransferType::DestinationReserve => Self::destination_reserve_fees_instructions(
2196					origin.clone(),
2197					dest.clone(),
2198					fees,
2199					weight_limit,
2200				)?,
2201				TransferType::Teleport => Self::teleport_fees_instructions(
2202					origin.clone(),
2203					dest.clone(),
2204					fees,
2205					weight_limit,
2206				)?,
2207				TransferType::RemoteReserve(_) =>
2208					return Err(Error::<T>::InvalidAssetUnsupportedReserve.into()),
2209			};
2210			FeesHandling::Separate { local_xcm, remote_xcm }
2211		};
2212
2213		let (local_xcm, remote_xcm) = Self::build_xcm_transfer_type(
2214			origin.clone(),
2215			dest.clone(),
2216			beneficiary,
2217			assets,
2218			assets_transfer_type,
2219			fees,
2220			weight_limit,
2221		)?;
2222		Self::execute_xcm_transfer(origin, dest, local_xcm, remote_xcm)
2223	}
2224
2225	fn build_xcm_transfer_type(
2226		origin: Location,
2227		dest: Location,
2228		beneficiary: Either<Location, Xcm<()>>,
2229		assets: Vec<Asset>,
2230		transfer_type: TransferType,
2231		fees: FeesHandling<T>,
2232		weight_limit: WeightLimit,
2233	) -> Result<(Xcm<<T as Config>::RuntimeCall>, Option<Xcm<()>>), Error<T>> {
2234		tracing::debug!(
2235			target: "xcm::pallet_xcm::build_xcm_transfer_type",
2236			?origin, ?dest, ?beneficiary, ?assets, ?transfer_type, ?fees, ?weight_limit,
2237		);
2238		match transfer_type {
2239			TransferType::LocalReserve => Self::local_reserve_transfer_programs(
2240				origin.clone(),
2241				dest.clone(),
2242				beneficiary,
2243				assets,
2244				fees,
2245				weight_limit,
2246			)
2247			.map(|(local, remote)| (local, Some(remote))),
2248			TransferType::DestinationReserve => Self::destination_reserve_transfer_programs(
2249				origin.clone(),
2250				dest.clone(),
2251				beneficiary,
2252				assets,
2253				fees,
2254				weight_limit,
2255			)
2256			.map(|(local, remote)| (local, Some(remote))),
2257			TransferType::RemoteReserve(reserve) => {
2258				let fees = match fees {
2259					FeesHandling::Batched { fees } => fees,
2260					_ => return Err(Error::<T>::InvalidAssetUnsupportedReserve.into()),
2261				};
2262				Self::remote_reserve_transfer_program(
2263					origin.clone(),
2264					reserve.try_into().map_err(|()| {
2265						tracing::debug!(
2266							target: "xcm::pallet_xcm::build_xcm_transfer_type",
2267							"Failed to convert remote reserve location",
2268						);
2269						Error::<T>::BadVersion
2270					})?,
2271					beneficiary,
2272					dest.clone(),
2273					assets,
2274					fees,
2275					weight_limit,
2276				)
2277				.map(|local| (local, None))
2278			},
2279			TransferType::Teleport => Self::teleport_assets_program(
2280				origin.clone(),
2281				dest.clone(),
2282				beneficiary,
2283				assets,
2284				fees,
2285				weight_limit,
2286			)
2287			.map(|(local, remote)| (local, Some(remote))),
2288		}
2289	}
2290
2291	fn execute_xcm_transfer(
2292		origin: Location,
2293		dest: Location,
2294		mut local_xcm: Xcm<<T as Config>::RuntimeCall>,
2295		remote_xcm: Option<Xcm<()>>,
2296	) -> DispatchResult {
2297		tracing::debug!(
2298			target: "xcm::pallet_xcm::execute_xcm_transfer",
2299			?origin, ?dest, ?local_xcm, ?remote_xcm,
2300		);
2301
2302		let weight =
2303			T::Weigher::weight(&mut local_xcm, Weight::MAX).map_err(|error| {
2304				tracing::debug!(target: "xcm::pallet_xcm::execute_xcm_transfer", ?error, "Failed to calculate weight");
2305				Error::<T>::UnweighableMessage
2306			})?;
2307		let mut hash = local_xcm.using_encoded(sp_io::hashing::blake2_256);
2308		let outcome = T::XcmExecutor::prepare_and_execute(
2309			origin.clone(),
2310			local_xcm,
2311			&mut hash,
2312			weight,
2313			weight,
2314		);
2315		Self::deposit_event(Event::Attempted { outcome: outcome.clone() });
2316		outcome.clone().ensure_complete().map_err(|error| {
2317			tracing::error!(
2318				target: "xcm::pallet_xcm::execute_xcm_transfer",
2319				?error, "XCM execution failed with error with outcome: {:?}", outcome
2320			);
2321			Error::<T>::LocalExecutionIncompleteWithError {
2322				index: error.index,
2323				error: error.error.into(),
2324			}
2325		})?;
2326
2327		if let Some(remote_xcm) = remote_xcm {
2328			let (ticket, price) = validate_send::<T::XcmRouter>(dest.clone(), remote_xcm.clone())
2329				.map_err(|error| {
2330					tracing::error!(target: "xcm::pallet_xcm::execute_xcm_transfer", ?error, ?dest, ?remote_xcm, "XCM validate_send failed with error");
2331					Error::<T>::from(error)
2332				})?;
2333			if origin != Here.into_location() {
2334				Self::charge_fees(origin.clone(), price.clone()).map_err(|error| {
2335					tracing::error!(
2336						target: "xcm::pallet_xcm::execute_xcm_transfer",
2337						?error, ?price, ?origin, "Unable to charge fee",
2338					);
2339					Error::<T>::FeesNotMet
2340				})?;
2341			}
2342			let message_id = T::XcmRouter::deliver(ticket)
2343				.map_err(|error| {
2344					tracing::error!(target: "xcm::pallet_xcm::execute_xcm_transfer", ?error, ?dest, ?remote_xcm, "XCM deliver failed with error");
2345					Error::<T>::from(error)
2346				})?;
2347
2348			let e = Event::Sent { origin, destination: dest, message: remote_xcm, message_id };
2349			Self::deposit_event(e);
2350		}
2351		Ok(())
2352	}
2353
2354	fn add_fees_to_xcm(
2355		dest: Location,
2356		fees: FeesHandling<T>,
2357		weight_limit: WeightLimit,
2358		local: &mut Xcm<<T as Config>::RuntimeCall>,
2359		remote: &mut Xcm<()>,
2360	) -> Result<(), Error<T>> {
2361		match fees {
2362			FeesHandling::Batched { fees } => {
2363				let context = T::UniversalLocation::get();
2364				// no custom fees instructions, they are batched together with `assets` transfer;
2365				// BuyExecution happens after receiving all `assets`
2366				let reanchored_fees =
2367					fees.reanchored(&dest, &context).map_err(|e| {
2368						tracing::error!(target: "xcm::pallet_xcm::add_fees_to_xcm", ?e, ?dest, ?context, "Failed to re-anchor fees");
2369						Error::<T>::CannotReanchor
2370					})?;
2371				// buy execution using `fees` batched together with above `reanchored_assets`
2372				remote.inner_mut().push(BuyExecution { fees: reanchored_fees, weight_limit });
2373			},
2374			FeesHandling::Separate { local_xcm: mut local_fees, remote_xcm: mut remote_fees } => {
2375				// fees are handled by separate XCM instructions, prepend fees instructions (for
2376				// remote XCM they have to be prepended instead of appended to pass barriers).
2377				core::mem::swap(local, &mut local_fees);
2378				core::mem::swap(remote, &mut remote_fees);
2379				// these are now swapped so fees actually go first
2380				local.inner_mut().append(&mut local_fees.into_inner());
2381				remote.inner_mut().append(&mut remote_fees.into_inner());
2382			},
2383		}
2384		Ok(())
2385	}
2386
2387	fn local_reserve_fees_instructions(
2388		origin: Location,
2389		dest: Location,
2390		fees: Asset,
2391		weight_limit: WeightLimit,
2392	) -> Result<(Xcm<<T as Config>::RuntimeCall>, Xcm<()>), Error<T>> {
2393		let value = (origin, vec![fees.clone()]);
2394		ensure!(T::XcmReserveTransferFilter::contains(&value), Error::<T>::Filtered);
2395
2396		let context = T::UniversalLocation::get();
2397		let reanchored_fees = fees.clone().reanchored(&dest, &context).map_err(|_| {
2398			tracing::debug!(
2399				target: "xcm::pallet_xcm::local_reserve_fees_instructions",
2400				"Failed to re-anchor fees",
2401			);
2402			Error::<T>::CannotReanchor
2403		})?;
2404
2405		let local_execute_xcm = Xcm(vec![
2406			// move `fees` to `dest`s local sovereign account
2407			TransferAsset { assets: fees.into(), beneficiary: dest },
2408		]);
2409		let xcm_on_dest = Xcm(vec![
2410			// let (dest) chain know `fees` are in its SA on reserve
2411			ReserveAssetDeposited(reanchored_fees.clone().into()),
2412			// buy exec using `fees` in holding deposited in above instruction
2413			BuyExecution { fees: reanchored_fees, weight_limit },
2414		]);
2415		Ok((local_execute_xcm, xcm_on_dest))
2416	}
2417
2418	fn local_reserve_transfer_programs(
2419		origin: Location,
2420		dest: Location,
2421		beneficiary: Either<Location, Xcm<()>>,
2422		assets: Vec<Asset>,
2423		fees: FeesHandling<T>,
2424		weight_limit: WeightLimit,
2425	) -> Result<(Xcm<<T as Config>::RuntimeCall>, Xcm<()>), Error<T>> {
2426		let value = (origin, assets);
2427		ensure!(T::XcmReserveTransferFilter::contains(&value), Error::<T>::Filtered);
2428		let (_, assets) = value;
2429
2430		// max assets is `assets` (+ potentially separately handled fee)
2431		let max_assets =
2432			assets.len() as u32 + if matches!(&fees, FeesHandling::Batched { .. }) { 0 } else { 1 };
2433		let assets: Assets = assets.into();
2434		let context = T::UniversalLocation::get();
2435		let mut reanchored_assets = assets.clone();
2436		reanchored_assets
2437			.reanchor(&dest, &context)
2438			.map_err(|e| {
2439				tracing::error!(target: "xcm::pallet_xcm::local_reserve_transfer_programs", ?e, ?dest, ?context, "Failed to re-anchor assets");
2440				Error::<T>::CannotReanchor
2441			})?;
2442
2443		// XCM instructions to be executed on local chain
2444		let mut local_execute_xcm = Xcm(vec![
2445			// locally move `assets` to `dest`s local sovereign account
2446			TransferAsset { assets, beneficiary: dest.clone() },
2447		]);
2448		// XCM instructions to be executed on destination chain
2449		let mut xcm_on_dest = Xcm(vec![
2450			// let (dest) chain know assets are in its SA on reserve
2451			ReserveAssetDeposited(reanchored_assets),
2452			// following instructions are not exec'ed on behalf of origin chain anymore
2453			ClearOrigin,
2454		]);
2455		// handle fees
2456		Self::add_fees_to_xcm(dest, fees, weight_limit, &mut local_execute_xcm, &mut xcm_on_dest)?;
2457
2458		// Use custom XCM on remote chain, or just default to depositing everything to beneficiary.
2459		let custom_remote_xcm = match beneficiary {
2460			Either::Right(custom_xcm) => custom_xcm,
2461			Either::Left(beneficiary) => {
2462				// deposit all remaining assets in holding to `beneficiary` location
2463				Xcm(vec![DepositAsset { assets: Wild(AllCounted(max_assets)), beneficiary }])
2464			},
2465		};
2466		xcm_on_dest.0.extend(custom_remote_xcm.into_iter());
2467
2468		Ok((local_execute_xcm, xcm_on_dest))
2469	}
2470
2471	fn destination_reserve_fees_instructions(
2472		origin: Location,
2473		dest: Location,
2474		fees: Asset,
2475		weight_limit: WeightLimit,
2476	) -> Result<(Xcm<<T as Config>::RuntimeCall>, Xcm<()>), Error<T>> {
2477		let value = (origin, vec![fees.clone()]);
2478		ensure!(T::XcmReserveTransferFilter::contains(&value), Error::<T>::Filtered);
2479		ensure!(
2480			<T::XcmExecutor as XcmAssetTransfers>::IsReserve::contains(&fees, &dest),
2481			Error::<T>::InvalidAssetUnsupportedReserve
2482		);
2483
2484		let context = T::UniversalLocation::get();
2485		let reanchored_fees = fees
2486			.clone()
2487			.reanchored(&dest, &context)
2488			.map_err(|e| {
2489				tracing::error!(target: "xcm::pallet_xcm::destination_reserve_fees_instructions", ?e, ?dest,?context, "Failed to re-anchor fees");
2490				Error::<T>::CannotReanchor
2491			})?;
2492		let fees: Assets = fees.into();
2493
2494		let local_execute_xcm = Xcm(vec![
2495			// withdraw reserve-based fees (derivatives)
2496			WithdrawAsset(fees.clone()),
2497			// burn derivatives
2498			BurnAsset(fees),
2499		]);
2500		let xcm_on_dest = Xcm(vec![
2501			// withdraw `fees` from origin chain's sovereign account
2502			WithdrawAsset(reanchored_fees.clone().into()),
2503			// buy exec using `fees` in holding withdrawn in above instruction
2504			BuyExecution { fees: reanchored_fees, weight_limit },
2505		]);
2506		Ok((local_execute_xcm, xcm_on_dest))
2507	}
2508
2509	fn destination_reserve_transfer_programs(
2510		origin: Location,
2511		dest: Location,
2512		beneficiary: Either<Location, Xcm<()>>,
2513		assets: Vec<Asset>,
2514		fees: FeesHandling<T>,
2515		weight_limit: WeightLimit,
2516	) -> Result<(Xcm<<T as Config>::RuntimeCall>, Xcm<()>), Error<T>> {
2517		let value = (origin, assets);
2518		ensure!(T::XcmReserveTransferFilter::contains(&value), Error::<T>::Filtered);
2519		let (_, assets) = value;
2520		for asset in assets.iter() {
2521			ensure!(
2522				<T::XcmExecutor as XcmAssetTransfers>::IsReserve::contains(&asset, &dest),
2523				Error::<T>::InvalidAssetUnsupportedReserve
2524			);
2525		}
2526
2527		// max assets is `assets` (+ potentially separately handled fee)
2528		let max_assets =
2529			assets.len() as u32 + if matches!(&fees, FeesHandling::Batched { .. }) { 0 } else { 1 };
2530		let assets: Assets = assets.into();
2531		let context = T::UniversalLocation::get();
2532		let mut reanchored_assets = assets.clone();
2533		reanchored_assets
2534			.reanchor(&dest, &context)
2535			.map_err(|e| {
2536				tracing::error!(target: "xcm::pallet_xcm::destination_reserve_transfer_programs", ?e, ?dest, ?context, "Failed to re-anchor assets");
2537				Error::<T>::CannotReanchor
2538			})?;
2539
2540		// XCM instructions to be executed on local chain
2541		let mut local_execute_xcm = Xcm(vec![
2542			// withdraw reserve-based assets
2543			WithdrawAsset(assets.clone()),
2544			// burn reserve-based assets
2545			BurnAsset(assets),
2546		]);
2547		// XCM instructions to be executed on destination chain
2548		let mut xcm_on_dest = Xcm(vec![
2549			// withdraw `assets` from origin chain's sovereign account
2550			WithdrawAsset(reanchored_assets),
2551			// following instructions are not exec'ed on behalf of origin chain anymore
2552			ClearOrigin,
2553		]);
2554		// handle fees
2555		Self::add_fees_to_xcm(dest, fees, weight_limit, &mut local_execute_xcm, &mut xcm_on_dest)?;
2556
2557		// Use custom XCM on remote chain, or just default to depositing everything to beneficiary.
2558		let custom_remote_xcm = match beneficiary {
2559			Either::Right(custom_xcm) => custom_xcm,
2560			Either::Left(beneficiary) => {
2561				// deposit all remaining assets in holding to `beneficiary` location
2562				Xcm(vec![DepositAsset { assets: Wild(AllCounted(max_assets)), beneficiary }])
2563			},
2564		};
2565		xcm_on_dest.0.extend(custom_remote_xcm.into_iter());
2566
2567		Ok((local_execute_xcm, xcm_on_dest))
2568	}
2569
2570	// function assumes fees and assets have the same remote reserve
2571	fn remote_reserve_transfer_program(
2572		origin: Location,
2573		reserve: Location,
2574		beneficiary: Either<Location, Xcm<()>>,
2575		dest: Location,
2576		assets: Vec<Asset>,
2577		fees: Asset,
2578		weight_limit: WeightLimit,
2579	) -> Result<Xcm<<T as Config>::RuntimeCall>, Error<T>> {
2580		let value = (origin, assets);
2581		ensure!(T::XcmReserveTransferFilter::contains(&value), Error::<T>::Filtered);
2582		let (_, assets) = value;
2583
2584		let max_assets = assets.len() as u32;
2585		let context = T::UniversalLocation::get();
2586		// we spend up to half of fees for execution on reserve and other half for execution on
2587		// destination
2588		let (fees_half_1, fees_half_2) = Self::halve_fees(fees)?;
2589		// identifies fee item as seen by `reserve` - to be used at reserve chain
2590		let reserve_fees = fees_half_1
2591			.reanchored(&reserve, &context)
2592			.map_err(|e| {
2593				tracing::error!(target: "xcm::pallet_xcm::remote_reserve_transfer_program", ?e, ?reserve, ?context, "Failed to re-anchor reserve_fees");
2594				Error::<T>::CannotReanchor
2595			})?;
2596		// identifies fee item as seen by `dest` - to be used at destination chain
2597		let dest_fees = fees_half_2
2598			.reanchored(&dest, &context)
2599			.map_err(|e| {
2600				tracing::error!(target: "xcm::pallet_xcm::remote_reserve_transfer_program", ?e, ?dest, ?context, "Failed to re-anchor dest_fees");
2601				Error::<T>::CannotReanchor
2602			})?;
2603		// identifies `dest` as seen by `reserve`
2604		let dest = dest.reanchored(&reserve, &context).map_err(|e| {
2605			tracing::error!(target: "xcm::pallet_xcm::remote_reserve_transfer_program", ?e, ?reserve, ?context, "Failed to re-anchor dest");
2606			Error::<T>::CannotReanchor
2607		})?;
2608		// xcm to be executed at dest
2609		let mut xcm_on_dest =
2610			Xcm(vec![BuyExecution { fees: dest_fees, weight_limit: weight_limit.clone() }]);
2611		// Use custom XCM on remote chain, or just default to depositing everything to beneficiary.
2612		let custom_xcm_on_dest = match beneficiary {
2613			Either::Right(custom_xcm) => custom_xcm,
2614			Either::Left(beneficiary) => {
2615				// deposit all remaining assets in holding to `beneficiary` location
2616				Xcm(vec![DepositAsset { assets: Wild(AllCounted(max_assets)), beneficiary }])
2617			},
2618		};
2619		xcm_on_dest.0.extend(custom_xcm_on_dest.into_iter());
2620		// xcm to be executed on reserve
2621		let xcm_on_reserve = Xcm(vec![
2622			BuyExecution { fees: reserve_fees, weight_limit },
2623			DepositReserveAsset { assets: Wild(AllCounted(max_assets)), dest, xcm: xcm_on_dest },
2624		]);
2625		Ok(Xcm(vec![
2626			WithdrawAsset(assets.into()),
2627			SetFeesMode { jit_withdraw: true },
2628			InitiateReserveWithdraw {
2629				assets: Wild(AllCounted(max_assets)),
2630				reserve,
2631				xcm: xcm_on_reserve,
2632			},
2633		]))
2634	}
2635
2636	fn teleport_fees_instructions(
2637		origin: Location,
2638		dest: Location,
2639		fees: Asset,
2640		weight_limit: WeightLimit,
2641	) -> Result<(Xcm<<T as Config>::RuntimeCall>, Xcm<()>), Error<T>> {
2642		let value = (origin, vec![fees.clone()]);
2643		ensure!(T::XcmTeleportFilter::contains(&value), Error::<T>::Filtered);
2644		ensure!(
2645			<T::XcmExecutor as XcmAssetTransfers>::IsTeleporter::contains(&fees, &dest),
2646			Error::<T>::Filtered
2647		);
2648
2649		let context = T::UniversalLocation::get();
2650		let reanchored_fees = fees
2651			.clone()
2652			.reanchored(&dest, &context)
2653			.map_err(|e| {
2654				tracing::error!(target: "xcm::pallet_xcm::teleport_fees_instructions", ?e, ?dest, ?context, "Failed to re-anchor fees");
2655				Error::<T>::CannotReanchor
2656			})?;
2657
2658		// XcmContext irrelevant in teleports checks
2659		let dummy_context =
2660			XcmContext { origin: None, message_id: Default::default(), topic: None };
2661		// We should check that the asset can actually be teleported out (for this to
2662		// be in error, there would need to be an accounting violation by ourselves,
2663		// so it's unlikely, but we don't want to allow that kind of bug to leak into
2664		// a trusted chain.
2665		<T::XcmExecutor as XcmAssetTransfers>::AssetTransactor::can_check_out(
2666			&dest,
2667			&fees,
2668			&dummy_context,
2669		)
2670		.map_err(|e| {
2671			tracing::error!(target: "xcm::pallet_xcm::teleport_fees_instructions", ?e, ?fees, ?dest, "Failed can_check_out");
2672			Error::<T>::CannotCheckOutTeleport
2673		})?;
2674		// safe to do this here, we're in a transactional call that will be reverted on any
2675		// errors down the line
2676		<T::XcmExecutor as XcmAssetTransfers>::AssetTransactor::check_out(
2677			&dest,
2678			&fees,
2679			&dummy_context,
2680		);
2681
2682		let fees: Assets = fees.into();
2683		let local_execute_xcm = Xcm(vec![
2684			// withdraw fees
2685			WithdrawAsset(fees.clone()),
2686			// burn fees
2687			BurnAsset(fees),
2688		]);
2689		let xcm_on_dest = Xcm(vec![
2690			// (dest) chain receive teleported assets burned on origin chain
2691			ReceiveTeleportedAsset(reanchored_fees.clone().into()),
2692			// buy exec using `fees` in holding received in above instruction
2693			BuyExecution { fees: reanchored_fees, weight_limit },
2694		]);
2695		Ok((local_execute_xcm, xcm_on_dest))
2696	}
2697
2698	fn teleport_assets_program(
2699		origin: Location,
2700		dest: Location,
2701		beneficiary: Either<Location, Xcm<()>>,
2702		assets: Vec<Asset>,
2703		fees: FeesHandling<T>,
2704		weight_limit: WeightLimit,
2705	) -> Result<(Xcm<<T as Config>::RuntimeCall>, Xcm<()>), Error<T>> {
2706		let value = (origin, assets);
2707		ensure!(T::XcmTeleportFilter::contains(&value), Error::<T>::Filtered);
2708		let (_, assets) = value;
2709		for asset in assets.iter() {
2710			ensure!(
2711				<T::XcmExecutor as XcmAssetTransfers>::IsTeleporter::contains(&asset, &dest),
2712				Error::<T>::Filtered
2713			);
2714		}
2715
2716		// max assets is `assets` (+ potentially separately handled fee)
2717		let max_assets =
2718			assets.len() as u32 + if matches!(&fees, FeesHandling::Batched { .. }) { 0 } else { 1 };
2719		let context = T::UniversalLocation::get();
2720		let assets: Assets = assets.into();
2721		let mut reanchored_assets = assets.clone();
2722		reanchored_assets
2723			.reanchor(&dest, &context)
2724			.map_err(|e| {
2725				tracing::error!(target: "xcm::pallet_xcm::teleport_assets_program", ?e, ?dest, ?context, "Failed to re-anchor asset");
2726				Error::<T>::CannotReanchor
2727			})?;
2728
2729		// XcmContext irrelevant in teleports checks
2730		let dummy_context =
2731			XcmContext { origin: None, message_id: Default::default(), topic: None };
2732		for asset in assets.inner() {
2733			// We should check that the asset can actually be teleported out (for this to
2734			// be in error, there would need to be an accounting violation by ourselves,
2735			// so it's unlikely, but we don't want to allow that kind of bug to leak into
2736			// a trusted chain.
2737			<T::XcmExecutor as XcmAssetTransfers>::AssetTransactor::can_check_out(
2738				&dest,
2739				asset,
2740				&dummy_context,
2741			)
2742			.map_err(|e| {
2743				tracing::error!(target: "xcm::pallet_xcm::teleport_assets_program", ?e, ?asset, ?dest, "Failed can_check_out asset");
2744				Error::<T>::CannotCheckOutTeleport
2745			})?;
2746		}
2747		for asset in assets.inner() {
2748			// safe to do this here, we're in a transactional call that will be reverted on any
2749			// errors down the line
2750			<T::XcmExecutor as XcmAssetTransfers>::AssetTransactor::check_out(
2751				&dest,
2752				asset,
2753				&dummy_context,
2754			);
2755		}
2756
2757		// XCM instructions to be executed on local chain
2758		let mut local_execute_xcm = Xcm(vec![
2759			// withdraw assets to be teleported
2760			WithdrawAsset(assets.clone()),
2761			// burn assets on local chain
2762			BurnAsset(assets),
2763		]);
2764		// XCM instructions to be executed on destination chain
2765		let mut xcm_on_dest = Xcm(vec![
2766			// teleport `assets` in from origin chain
2767			ReceiveTeleportedAsset(reanchored_assets),
2768			// following instructions are not exec'ed on behalf of origin chain anymore
2769			ClearOrigin,
2770		]);
2771		// handle fees
2772		Self::add_fees_to_xcm(dest, fees, weight_limit, &mut local_execute_xcm, &mut xcm_on_dest)?;
2773
2774		// Use custom XCM on remote chain, or just default to depositing everything to beneficiary.
2775		let custom_remote_xcm = match beneficiary {
2776			Either::Right(custom_xcm) => custom_xcm,
2777			Either::Left(beneficiary) => {
2778				// deposit all remaining assets in holding to `beneficiary` location
2779				Xcm(vec![DepositAsset { assets: Wild(AllCounted(max_assets)), beneficiary }])
2780			},
2781		};
2782		xcm_on_dest.0.extend(custom_remote_xcm.into_iter());
2783
2784		Ok((local_execute_xcm, xcm_on_dest))
2785	}
2786
2787	/// Halve `fees` fungible amount.
2788	pub(crate) fn halve_fees(fees: Asset) -> Result<(Asset, Asset), Error<T>> {
2789		match fees.fun {
2790			Fungible(amount) => {
2791				let fee1 = amount.saturating_div(2);
2792				let fee2 = amount.saturating_sub(fee1);
2793				ensure!(fee1 > 0, Error::<T>::FeesNotMet);
2794				ensure!(fee2 > 0, Error::<T>::FeesNotMet);
2795				Ok((Asset::from((fees.id.clone(), fee1)), Asset::from((fees.id.clone(), fee2))))
2796			},
2797			NonFungible(_) => Err(Error::<T>::FeesNotMet),
2798		}
2799	}
2800
2801	/// Will always make progress, and will do its best not to use much more than `weight_cutoff`
2802	/// in doing so.
2803	pub(crate) fn lazy_migration(
2804		mut stage: VersionMigrationStage,
2805		weight_cutoff: Weight,
2806	) -> (Weight, Option<VersionMigrationStage>) {
2807		let mut weight_used = Weight::zero();
2808
2809		let sv_migrate_weight = T::WeightInfo::migrate_supported_version();
2810		let vn_migrate_weight = T::WeightInfo::migrate_version_notifiers();
2811		let vnt_already_notified_weight = T::WeightInfo::already_notified_target();
2812		let vnt_notify_weight = T::WeightInfo::notify_current_targets();
2813		let vnt_migrate_weight = T::WeightInfo::migrate_version_notify_targets();
2814		let vnt_migrate_fail_weight = T::WeightInfo::notify_target_migration_fail();
2815		let vnt_notify_migrate_weight = T::WeightInfo::migrate_and_notify_old_targets();
2816
2817		use VersionMigrationStage::*;
2818
2819		if stage == MigrateSupportedVersion {
2820			// We assume that supported XCM version only ever increases, so just cycle through lower
2821			// XCM versioned from the current.
2822			for v in 0..XCM_VERSION {
2823				for (old_key, value) in SupportedVersion::<T>::drain_prefix(v) {
2824					if let Ok(new_key) = old_key.into_latest() {
2825						SupportedVersion::<T>::insert(XCM_VERSION, new_key, value);
2826					}
2827					weight_used.saturating_accrue(sv_migrate_weight);
2828					if weight_used.any_gte(weight_cutoff) {
2829						return (weight_used, Some(stage))
2830					}
2831				}
2832			}
2833			stage = MigrateVersionNotifiers;
2834		}
2835		if stage == MigrateVersionNotifiers {
2836			for v in 0..XCM_VERSION {
2837				for (old_key, value) in VersionNotifiers::<T>::drain_prefix(v) {
2838					if let Ok(new_key) = old_key.into_latest() {
2839						VersionNotifiers::<T>::insert(XCM_VERSION, new_key, value);
2840					}
2841					weight_used.saturating_accrue(vn_migrate_weight);
2842					if weight_used.any_gte(weight_cutoff) {
2843						return (weight_used, Some(stage))
2844					}
2845				}
2846			}
2847			stage = NotifyCurrentTargets(None);
2848		}
2849
2850		let xcm_version = T::AdvertisedXcmVersion::get();
2851
2852		if let NotifyCurrentTargets(maybe_last_raw_key) = stage {
2853			let mut iter = match maybe_last_raw_key {
2854				Some(k) => VersionNotifyTargets::<T>::iter_prefix_from(XCM_VERSION, k),
2855				None => VersionNotifyTargets::<T>::iter_prefix(XCM_VERSION),
2856			};
2857			while let Some((key, value)) = iter.next() {
2858				let (query_id, max_weight, target_xcm_version) = value;
2859				let new_key: Location = match key.clone().try_into() {
2860					Ok(k) if target_xcm_version != xcm_version => k,
2861					_ => {
2862						// We don't early return here since we need to be certain that we
2863						// make some progress.
2864						weight_used.saturating_accrue(vnt_already_notified_weight);
2865						continue
2866					},
2867				};
2868				let response = Response::Version(xcm_version);
2869				let message =
2870					Xcm(vec![QueryResponse { query_id, response, max_weight, querier: None }]);
2871				let event = match send_xcm::<T::XcmRouter>(new_key.clone(), message) {
2872					Ok((message_id, cost)) => {
2873						let value = (query_id, max_weight, xcm_version);
2874						VersionNotifyTargets::<T>::insert(XCM_VERSION, key, value);
2875						Event::VersionChangeNotified {
2876							destination: new_key,
2877							result: xcm_version,
2878							cost,
2879							message_id,
2880						}
2881					},
2882					Err(e) => {
2883						VersionNotifyTargets::<T>::remove(XCM_VERSION, key);
2884						Event::NotifyTargetSendFail { location: new_key, query_id, error: e.into() }
2885					},
2886				};
2887				Self::deposit_event(event);
2888				weight_used.saturating_accrue(vnt_notify_weight);
2889				if weight_used.any_gte(weight_cutoff) {
2890					let last = Some(iter.last_raw_key().into());
2891					return (weight_used, Some(NotifyCurrentTargets(last)))
2892				}
2893			}
2894			stage = MigrateAndNotifyOldTargets;
2895		}
2896		if stage == MigrateAndNotifyOldTargets {
2897			for v in 0..XCM_VERSION {
2898				for (old_key, value) in VersionNotifyTargets::<T>::drain_prefix(v) {
2899					let (query_id, max_weight, target_xcm_version) = value;
2900					let new_key = match Location::try_from(old_key.clone()) {
2901						Ok(k) => k,
2902						Err(()) => {
2903							Self::deposit_event(Event::NotifyTargetMigrationFail {
2904								location: old_key,
2905								query_id: value.0,
2906							});
2907							weight_used.saturating_accrue(vnt_migrate_fail_weight);
2908							if weight_used.any_gte(weight_cutoff) {
2909								return (weight_used, Some(stage))
2910							}
2911							continue
2912						},
2913					};
2914
2915					let versioned_key = LatestVersionedLocation(&new_key);
2916					if target_xcm_version == xcm_version {
2917						VersionNotifyTargets::<T>::insert(XCM_VERSION, versioned_key, value);
2918						weight_used.saturating_accrue(vnt_migrate_weight);
2919					} else {
2920						// Need to notify target.
2921						let response = Response::Version(xcm_version);
2922						let message = Xcm(vec![QueryResponse {
2923							query_id,
2924							response,
2925							max_weight,
2926							querier: None,
2927						}]);
2928						let event = match send_xcm::<T::XcmRouter>(new_key.clone(), message) {
2929							Ok((message_id, cost)) => {
2930								VersionNotifyTargets::<T>::insert(
2931									XCM_VERSION,
2932									versioned_key,
2933									(query_id, max_weight, xcm_version),
2934								);
2935								Event::VersionChangeNotified {
2936									destination: new_key,
2937									result: xcm_version,
2938									cost,
2939									message_id,
2940								}
2941							},
2942							Err(e) => Event::NotifyTargetSendFail {
2943								location: new_key,
2944								query_id,
2945								error: e.into(),
2946							},
2947						};
2948						Self::deposit_event(event);
2949						weight_used.saturating_accrue(vnt_notify_migrate_weight);
2950					}
2951					if weight_used.any_gte(weight_cutoff) {
2952						return (weight_used, Some(stage))
2953					}
2954				}
2955			}
2956		}
2957		(weight_used, None)
2958	}
2959
2960	/// Request that `dest` informs us of its version.
2961	pub fn request_version_notify(dest: impl Into<Location>) -> XcmResult {
2962		let dest = dest.into();
2963		let versioned_dest = VersionedLocation::from(dest.clone());
2964		let already = VersionNotifiers::<T>::contains_key(XCM_VERSION, &versioned_dest);
2965		ensure!(!already, XcmError::InvalidLocation);
2966		let query_id = QueryCounter::<T>::mutate(|q| {
2967			let r = *q;
2968			q.saturating_inc();
2969			r
2970		});
2971		// TODO #3735: Correct weight.
2972		let instruction = SubscribeVersion { query_id, max_response_weight: Weight::zero() };
2973		let (message_id, cost) = send_xcm::<T::XcmRouter>(dest.clone(), Xcm(vec![instruction]))?;
2974		Self::deposit_event(Event::VersionNotifyRequested { destination: dest, cost, message_id });
2975		VersionNotifiers::<T>::insert(XCM_VERSION, &versioned_dest, query_id);
2976		let query_status =
2977			QueryStatus::VersionNotifier { origin: versioned_dest, is_active: false };
2978		Queries::<T>::insert(query_id, query_status);
2979		Ok(())
2980	}
2981
2982	/// Request that `dest` ceases informing us of its version.
2983	pub fn unrequest_version_notify(dest: impl Into<Location>) -> XcmResult {
2984		let dest = dest.into();
2985		let versioned_dest = LatestVersionedLocation(&dest);
2986		let query_id = VersionNotifiers::<T>::take(XCM_VERSION, versioned_dest)
2987			.ok_or(XcmError::InvalidLocation)?;
2988		let (message_id, cost) =
2989			send_xcm::<T::XcmRouter>(dest.clone(), Xcm(vec![UnsubscribeVersion]))?;
2990		Self::deposit_event(Event::VersionNotifyUnrequested {
2991			destination: dest,
2992			cost,
2993			message_id,
2994		});
2995		Queries::<T>::remove(query_id);
2996		Ok(())
2997	}
2998
2999	/// Relay an XCM `message` from a given `interior` location in this context to a given `dest`
3000	/// location. The `fee_payer` is charged for the delivery unless `None` in which case fees
3001	/// are not charged (and instead borne by the chain).
3002	pub fn send_xcm(
3003		interior: impl Into<Junctions>,
3004		dest: impl Into<Location>,
3005		mut message: Xcm<()>,
3006	) -> Result<XcmHash, SendError> {
3007		let interior = interior.into();
3008		let local_origin = interior.clone().into();
3009		let dest = dest.into();
3010		let is_waived =
3011			<T::XcmExecutor as FeeManager>::is_waived(Some(&local_origin), FeeReason::ChargeFees);
3012		if interior != Junctions::Here {
3013			message.0.insert(0, DescendOrigin(interior.clone()));
3014		}
3015		tracing::debug!(target: "xcm::send_xcm", "{:?}, {:?}", dest.clone(), message.clone());
3016		let (ticket, price) = validate_send::<T::XcmRouter>(dest, message)?;
3017		if !is_waived {
3018			Self::charge_fees(local_origin, price).map_err(|e| {
3019				tracing::error!(
3020					target: "xcm::pallet_xcm::send_xcm",
3021					?e,
3022					"Charging fees failed with error",
3023				);
3024				SendError::Fees
3025			})?;
3026		}
3027		T::XcmRouter::deliver(ticket)
3028	}
3029
3030	pub fn check_account() -> T::AccountId {
3031		const ID: PalletId = PalletId(*b"py/xcmch");
3032		AccountIdConversion::<T::AccountId>::into_account_truncating(&ID)
3033	}
3034
3035	/// Dry-runs `call` with the given `origin`.
3036	///
3037	/// Returns not only the call result and events, but also the local XCM, if any,
3038	/// and any XCMs forwarded to other locations.
3039	/// Meant to be used in the `xcm_runtime_apis::dry_run::DryRunApi` runtime API.
3040	pub fn dry_run_call<Runtime, Router, OriginCaller, RuntimeCall>(
3041		origin: OriginCaller,
3042		call: RuntimeCall,
3043		result_xcms_version: XcmVersion,
3044	) -> Result<CallDryRunEffects<<Runtime as frame_system::Config>::RuntimeEvent>, XcmDryRunApiError>
3045	where
3046		Runtime: crate::Config,
3047		Router: InspectMessageQueues,
3048		RuntimeCall: Dispatchable<PostInfo = PostDispatchInfo>,
3049		<RuntimeCall as Dispatchable>::RuntimeOrigin: From<OriginCaller>,
3050	{
3051		crate::Pallet::<Runtime>::set_record_xcm(true);
3052		// Clear other messages in queues...
3053		Router::clear_messages();
3054		// ...and reset events to make sure we only record events from current call.
3055		frame_system::Pallet::<Runtime>::reset_events();
3056		let result = call.dispatch(origin.into());
3057		crate::Pallet::<Runtime>::set_record_xcm(false);
3058		let local_xcm = crate::Pallet::<Runtime>::recorded_xcm()
3059			.map(|xcm| VersionedXcm::<()>::from(xcm).into_version(result_xcms_version))
3060			.transpose()
3061			.map_err(|()| {
3062				tracing::error!(
3063					target: "xcm::DryRunApi::dry_run_call",
3064					"Local xcm version conversion failed"
3065				);
3066
3067				XcmDryRunApiError::VersionedConversionFailed
3068			})?;
3069
3070		// Should only get messages from this call since we cleared previous ones.
3071		let forwarded_xcms =
3072			Self::convert_forwarded_xcms(result_xcms_version, Router::get_messages()).inspect_err(
3073				|error| {
3074					tracing::error!(
3075						target: "xcm::DryRunApi::dry_run_call",
3076						?error, "Forwarded xcms version conversion failed with error"
3077					);
3078				},
3079			)?;
3080		let events: Vec<<Runtime as frame_system::Config>::RuntimeEvent> =
3081			frame_system::Pallet::<Runtime>::read_events_no_consensus()
3082				.map(|record| record.event.clone())
3083				.collect();
3084		Ok(CallDryRunEffects {
3085			local_xcm: local_xcm.map(VersionedXcm::<()>::from),
3086			forwarded_xcms,
3087			emitted_events: events,
3088			execution_result: result,
3089		})
3090	}
3091
3092	/// Dry-runs `xcm` with the given `origin_location`.
3093	///
3094	/// Returns execution result, events, and any forwarded XCMs to other locations.
3095	/// Meant to be used in the `xcm_runtime_apis::dry_run::DryRunApi` runtime API.
3096	pub fn dry_run_xcm<Runtime, Router, RuntimeCall: Decode + GetDispatchInfo, XcmConfig>(
3097		origin_location: VersionedLocation,
3098		xcm: VersionedXcm<RuntimeCall>,
3099	) -> Result<XcmDryRunEffects<<Runtime as frame_system::Config>::RuntimeEvent>, XcmDryRunApiError>
3100	where
3101		Runtime: frame_system::Config,
3102		Router: InspectMessageQueues,
3103		XcmConfig: xcm_executor::Config<RuntimeCall = RuntimeCall>,
3104	{
3105		let origin_location: Location = origin_location.try_into().map_err(|error| {
3106			tracing::error!(
3107				target: "xcm::DryRunApi::dry_run_xcm",
3108				?error, "Location version conversion failed with error"
3109			);
3110			XcmDryRunApiError::VersionedConversionFailed
3111		})?;
3112		let xcm_version = xcm.identify_version();
3113		let xcm: Xcm<RuntimeCall> = xcm.try_into().map_err(|error| {
3114			tracing::error!(
3115				target: "xcm::DryRunApi::dry_run_xcm",
3116				?error, "Xcm version conversion failed with error"
3117			);
3118			XcmDryRunApiError::VersionedConversionFailed
3119		})?;
3120		let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256);
3121
3122		// To make sure we only record events from current call.
3123		Router::clear_messages();
3124		frame_system::Pallet::<Runtime>::reset_events();
3125
3126		let result = xcm_executor::XcmExecutor::<XcmConfig>::prepare_and_execute(
3127			origin_location,
3128			xcm,
3129			&mut hash,
3130			Weight::MAX, // Max limit available for execution.
3131			Weight::zero(),
3132		);
3133		let forwarded_xcms = Self::convert_forwarded_xcms(xcm_version, Router::get_messages())
3134			.inspect_err(|error| {
3135				tracing::error!(
3136					target: "xcm::DryRunApi::dry_run_xcm",
3137					?error, "Forwarded xcms version conversion failed with error"
3138				);
3139			})?;
3140		let events: Vec<<Runtime as frame_system::Config>::RuntimeEvent> =
3141			frame_system::Pallet::<Runtime>::read_events_no_consensus()
3142				.map(|record| record.event.clone())
3143				.collect();
3144		Ok(XcmDryRunEffects { forwarded_xcms, emitted_events: events, execution_result: result })
3145	}
3146
3147	fn convert_xcms(
3148		xcm_version: XcmVersion,
3149		xcms: Vec<VersionedXcm<()>>,
3150	) -> Result<Vec<VersionedXcm<()>>, ()> {
3151		xcms.into_iter()
3152			.map(|xcm| xcm.into_version(xcm_version))
3153			.collect::<Result<Vec<_>, ()>>()
3154	}
3155
3156	fn convert_forwarded_xcms(
3157		xcm_version: XcmVersion,
3158		forwarded_xcms: Vec<(VersionedLocation, Vec<VersionedXcm<()>>)>,
3159	) -> Result<Vec<(VersionedLocation, Vec<VersionedXcm<()>>)>, XcmDryRunApiError> {
3160		forwarded_xcms
3161			.into_iter()
3162			.map(|(dest, forwarded_xcms)| {
3163				let dest = dest.into_version(xcm_version)?;
3164				let forwarded_xcms = Self::convert_xcms(xcm_version, forwarded_xcms)?;
3165
3166				Ok((dest, forwarded_xcms))
3167			})
3168			.collect::<Result<Vec<_>, ()>>()
3169			.map_err(|()| {
3170				tracing::debug!(
3171					target: "xcm::pallet_xcm::convert_forwarded_xcms",
3172					"Failed to convert VersionedLocation to requested version",
3173				);
3174				XcmDryRunApiError::VersionedConversionFailed
3175			})
3176	}
3177
3178	/// Given a list of asset ids, returns the correct API response for
3179	/// `XcmPaymentApi::query_acceptable_payment_assets`.
3180	///
3181	/// The assets passed in have to be supported for fee payment.
3182	pub fn query_acceptable_payment_assets(
3183		version: xcm::Version,
3184		asset_ids: Vec<AssetId>,
3185	) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
3186		Ok(asset_ids
3187			.into_iter()
3188			.map(|asset_id| VersionedAssetId::from(asset_id))
3189			.filter_map(|asset_id| asset_id.into_version(version).ok())
3190			.collect())
3191	}
3192
3193	pub fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
3194		let message = Xcm::<()>::try_from(message.clone())
3195			.map_err(|e| {
3196				tracing::debug!(target: "xcm::pallet_xcm::query_xcm_weight", ?e, ?message, "Failed to convert versioned message");
3197				XcmPaymentApiError::VersionedConversionFailed
3198			})?;
3199
3200		T::Weigher::weight(&mut message.clone().into(), Weight::MAX).map_err(|error| {
3201			tracing::debug!(target: "xcm::pallet_xcm::query_xcm_weight", ?error, ?message, "Error when querying XCM weight");
3202			XcmPaymentApiError::WeightNotComputable
3203		})
3204	}
3205
3206	/// Computes the weight cost using the provided `WeightTrader`.
3207	/// This function is supposed to be used ONLY in `XcmPaymentApi::query_weight_to_asset_fee`.
3208	///
3209	/// The provided `WeightTrader` must be the same as the one used in the XcmExecutor to ensure
3210	/// uniformity in the weight cost calculation.
3211	///
3212	/// NOTE: Currently this function uses a workaround that should be good enough for all practical
3213	/// uses: passes `u128::MAX / 2 == 2^127` of the specified asset to the `WeightTrader` as
3214	/// payment and computes the weight cost as the difference between this and the unspent amount.
3215	///
3216	/// Some weight traders could add the provided payment to some account's balance. However,
3217	/// it should practically never result in overflow because even currencies with a lot of decimal
3218	/// digits (say 18) usually have the total issuance of billions (`x * 10^9`) or trillions (`x *
3219	/// 10^12`) at max, much less than `2^127 / 10^18 =~ 1.7 * 10^20` (170 billion billion). Thus,
3220	/// any account's balance most likely holds less than `2^127`, so adding `2^127` won't result in
3221	/// `u128` overflow.
3222	pub fn query_weight_to_asset_fee<Trader: xcm_executor::traits::WeightTrader>(
3223		weight: Weight,
3224		asset: VersionedAssetId,
3225	) -> Result<u128, XcmPaymentApiError> {
3226		let asset: AssetId = asset.clone().try_into()
3227			.map_err(|e| {
3228				tracing::debug!(target: "xcm::pallet::query_weight_to_asset_fee", ?e, ?asset, "Failed to convert versioned asset");
3229				XcmPaymentApiError::VersionedConversionFailed
3230			})?;
3231
3232		let max_amount = u128::MAX / 2;
3233		let max_payment: Asset = (asset.clone(), max_amount).into();
3234		let context = XcmContext::with_message_id(XcmHash::default());
3235
3236		// We return the unspent amount without affecting the state
3237		// as we used a big amount of the asset without any check.
3238		let unspent = with_transaction(|| {
3239			let mut trader = Trader::new();
3240			let result = trader.buy_weight(weight, max_payment.into(), &context)
3241				.map_err(|e| {
3242					tracing::error!(target: "xcm::pallet::query_weight_to_asset_fee", ?e, ?asset, "Failed to buy weight");
3243
3244					// Return something convertible to `DispatchError` as required by the `with_transaction` fn.
3245					DispatchError::Other("Failed to buy weight")
3246				});
3247
3248			TransactionOutcome::Rollback(result)
3249		}).map_err(|error| {
3250			tracing::debug!(target: "xcm::pallet::query_weight_to_asset_fee", ?error, "Failed to execute transaction");
3251			XcmPaymentApiError::AssetNotFound
3252		})?;
3253
3254		let Some(unspent) = unspent.fungible.get(&asset) else {
3255			tracing::error!(target: "xcm::pallet::query_weight_to_asset_fee", ?asset, "The trader didn't return the needed fungible asset");
3256			return Err(XcmPaymentApiError::AssetNotFound);
3257		};
3258
3259		let paid = max_amount - unspent;
3260		Ok(paid)
3261	}
3262
3263	/// Given a `destination` and XCM `message`, return assets to be charged as XCM delivery fees.
3264	pub fn query_delivery_fees(
3265		destination: VersionedLocation,
3266		message: VersionedXcm<()>,
3267	) -> Result<VersionedAssets, XcmPaymentApiError> {
3268		let result_version = destination.identify_version().max(message.identify_version());
3269
3270		let destination: Location = destination
3271			.clone()
3272			.try_into()
3273			.map_err(|e| {
3274				tracing::error!(target: "xcm::pallet_xcm::query_delivery_fees", ?e, ?destination, "Failed to convert versioned destination");
3275				XcmPaymentApiError::VersionedConversionFailed
3276			})?;
3277
3278		let message: Xcm<()> =
3279			message.clone().try_into().map_err(|e| {
3280				tracing::error!(target: "xcm::pallet_xcm::query_delivery_fees", ?e, ?message, "Failed to convert versioned message");
3281				XcmPaymentApiError::VersionedConversionFailed
3282			})?;
3283
3284		let (_, fees) = validate_send::<T::XcmRouter>(destination.clone(), message.clone()).map_err(|error| {
3285			tracing::error!(target: "xcm::pallet_xcm::query_delivery_fees", ?error, ?destination, ?message, "Failed to validate send to destination");
3286			XcmPaymentApiError::Unroutable
3287		})?;
3288
3289		VersionedAssets::from(fees)
3290			.into_version(result_version)
3291			.map_err(|e| {
3292				tracing::error!(target: "xcm::pallet_xcm::query_delivery_fees", ?e, ?result_version, "Failed to convert fees into version");
3293				XcmPaymentApiError::VersionedConversionFailed
3294			})
3295	}
3296
3297	/// Given an Asset and a Location, returns if the provided location is a trusted reserve for the
3298	/// given asset.
3299	pub fn is_trusted_reserve(
3300		asset: VersionedAsset,
3301		location: VersionedLocation,
3302	) -> Result<bool, TrustedQueryApiError> {
3303		let location: Location = location.try_into().map_err(|e| {
3304			tracing::debug!(
3305				target: "xcm::pallet_xcm::is_trusted_reserve",
3306				?e, "Failed to convert versioned location",
3307			);
3308			TrustedQueryApiError::VersionedLocationConversionFailed
3309		})?;
3310
3311		let a: Asset = asset.try_into().map_err(|e| {
3312			tracing::debug!(
3313				target: "xcm::pallet_xcm::is_trusted_reserve",
3314				 ?e, "Failed to convert versioned asset",
3315			);
3316			TrustedQueryApiError::VersionedAssetConversionFailed
3317		})?;
3318
3319		Ok(<T::XcmExecutor as XcmAssetTransfers>::IsReserve::contains(&a, &location))
3320	}
3321
3322	/// Given an Asset and a Location, returns if the asset can be teleported to provided location.
3323	pub fn is_trusted_teleporter(
3324		asset: VersionedAsset,
3325		location: VersionedLocation,
3326	) -> Result<bool, TrustedQueryApiError> {
3327		let location: Location = location.try_into().map_err(|e| {
3328			tracing::debug!(
3329				target: "xcm::pallet_xcm::is_trusted_teleporter",
3330				?e, "Failed to convert versioned location",
3331			);
3332			TrustedQueryApiError::VersionedLocationConversionFailed
3333		})?;
3334		let a: Asset = asset.try_into().map_err(|e| {
3335			tracing::debug!(
3336				target: "xcm::pallet_xcm::is_trusted_teleporter",
3337				 ?e, "Failed to convert versioned asset",
3338			);
3339			TrustedQueryApiError::VersionedAssetConversionFailed
3340		})?;
3341		Ok(<T::XcmExecutor as XcmAssetTransfers>::IsTeleporter::contains(&a, &location))
3342	}
3343
3344	/// Returns locations allowed to alias into and act as `target`.
3345	pub fn authorized_aliasers(
3346		target: VersionedLocation,
3347	) -> Result<Vec<OriginAliaser>, AuthorizedAliasersApiError> {
3348		let desired_version = target.identify_version();
3349		// storage entries are always latest version
3350		let target: VersionedLocation = target.into_version(XCM_VERSION).map_err(|e| {
3351			tracing::debug!(
3352				target: "xcm::pallet_xcm::authorized_aliasers",
3353				?e, "Failed to convert versioned location",
3354			);
3355			AuthorizedAliasersApiError::LocationVersionConversionFailed
3356		})?;
3357		Ok(AuthorizedAliases::<T>::get(&target)
3358			.map(|authorized| {
3359				authorized
3360					.aliasers
3361					.into_iter()
3362					.filter_map(|aliaser| {
3363						let OriginAliaser { location, expiry } = aliaser;
3364						location
3365							.into_version(desired_version)
3366							.map(|location| OriginAliaser { location, expiry })
3367							.ok()
3368					})
3369					.collect()
3370			})
3371			.unwrap_or_default())
3372	}
3373
3374	/// Given an `origin` and a `target`, returns if the `origin` location was added by `target` as
3375	/// an authorized aliaser.
3376	///
3377	/// Effectively says whether `origin` is allowed to alias into and act as `target`.
3378	pub fn is_authorized_alias(
3379		origin: VersionedLocation,
3380		target: VersionedLocation,
3381	) -> Result<bool, AuthorizedAliasersApiError> {
3382		let desired_version = target.identify_version();
3383		let origin = origin.into_version(desired_version).map_err(|e| {
3384			tracing::debug!(
3385				target: "xcm::pallet_xcm::is_authorized_alias",
3386				?e, "mismatching origin and target versions",
3387			);
3388			AuthorizedAliasersApiError::LocationVersionConversionFailed
3389		})?;
3390		Ok(Self::authorized_aliasers(target)?.into_iter().any(|aliaser| {
3391			// `aliasers` and `origin` have already been transformed to `desired_version`, we
3392			// can just directly compare them.
3393			aliaser.location == origin &&
3394				aliaser
3395					.expiry
3396					.map(|expiry| {
3397						frame_system::Pallet::<T>::current_block_number().saturated_into::<u64>() <
3398							expiry
3399					})
3400					.unwrap_or(true)
3401		}))
3402	}
3403
3404	/// Create a new expectation of a query response with the querier being here.
3405	fn do_new_query(
3406		responder: impl Into<Location>,
3407		maybe_notify: Option<(u8, u8)>,
3408		timeout: BlockNumberFor<T>,
3409		match_querier: impl Into<Location>,
3410	) -> u64 {
3411		QueryCounter::<T>::mutate(|q| {
3412			let r = *q;
3413			q.saturating_inc();
3414			Queries::<T>::insert(
3415				r,
3416				QueryStatus::Pending {
3417					responder: responder.into().into(),
3418					maybe_match_querier: Some(match_querier.into().into()),
3419					maybe_notify,
3420					timeout,
3421				},
3422			);
3423			r
3424		})
3425	}
3426
3427	/// Consume `message` and return another which is equivalent to it except that it reports
3428	/// back the outcome and dispatches `notify` on this chain.
3429	///
3430	/// - `message`: The message whose outcome should be reported.
3431	/// - `responder`: The origin from which a response should be expected.
3432	/// - `notify`: A dispatchable function which will be called once the outcome of `message` is
3433	///   known. It may be a dispatchable in any pallet of the local chain, but other than the usual
3434	///   origin, it must accept exactly two arguments: `query_id: QueryId` and `outcome: Response`,
3435	///   and in that order. It should expect that the origin is `Origin::Response` and will contain
3436	///   the responder's location.
3437	/// - `timeout`: The block number after which it is permissible for `notify` not to be called
3438	///   even if a response is received.
3439	///
3440	/// `report_outcome_notify` may return an error if the `responder` is not invertible.
3441	///
3442	/// It is assumed that the querier of the response will be `Here`.
3443	///
3444	/// NOTE: `notify` gets called as part of handling an incoming message, so it should be
3445	/// lightweight. Its weight is estimated during this function and stored ready for
3446	/// weighing `ReportOutcome` on the way back. If it turns out to be heavier once it returns
3447	/// then reporting the outcome will fail. Furthermore if the estimate is too high, then it
3448	/// may be put in the overweight queue and need to be manually executed.
3449	pub fn report_outcome_notify(
3450		message: &mut Xcm<()>,
3451		responder: impl Into<Location>,
3452		notify: impl Into<<T as Config>::RuntimeCall>,
3453		timeout: BlockNumberFor<T>,
3454	) -> Result<(), XcmError> {
3455		let responder = responder.into();
3456		let destination = T::UniversalLocation::get().invert_target(&responder).map_err(|()| {
3457			tracing::debug!(
3458				target: "xcm::pallet_xcm::report_outcome_notify",
3459				"Failed to invert responder location to universal location",
3460			);
3461			XcmError::LocationNotInvertible
3462		})?;
3463		let notify: <T as Config>::RuntimeCall = notify.into();
3464		let max_weight = notify.get_dispatch_info().call_weight;
3465		let query_id = Self::new_notify_query(responder, notify, timeout, Here);
3466		let response_info = QueryResponseInfo { destination, query_id, max_weight };
3467		let report_error = Xcm(vec![ReportError(response_info)]);
3468		message.0.insert(0, SetAppendix(report_error));
3469		Ok(())
3470	}
3471
3472	/// Attempt to create a new query ID and register it as a query that is yet to respond, and
3473	/// which will call a dispatchable when a response happens.
3474	pub fn new_notify_query(
3475		responder: impl Into<Location>,
3476		notify: impl Into<<T as Config>::RuntimeCall>,
3477		timeout: BlockNumberFor<T>,
3478		match_querier: impl Into<Location>,
3479	) -> u64 {
3480		let notify = notify.into().using_encoded(|mut bytes| Decode::decode(&mut bytes)).expect(
3481			"decode input is output of Call encode; Call guaranteed to have two enums; qed",
3482		);
3483		Self::do_new_query(responder, Some(notify), timeout, match_querier)
3484	}
3485
3486	/// Note that a particular destination to whom we would like to send a message is unknown
3487	/// and queue it for version discovery.
3488	fn note_unknown_version(dest: &Location) {
3489		tracing::trace!(
3490			target: "xcm::pallet_xcm::note_unknown_version",
3491			?dest, "XCM version is unknown for destination"
3492		);
3493		let versioned_dest = VersionedLocation::from(dest.clone());
3494		VersionDiscoveryQueue::<T>::mutate(|q| {
3495			if let Some(index) = q.iter().position(|i| &i.0 == &versioned_dest) {
3496				// exists - just bump the count.
3497				q[index].1.saturating_inc();
3498			} else {
3499				let _ = q.try_push((versioned_dest, 1));
3500			}
3501		});
3502	}
3503
3504	/// Withdraw given `assets` from the given `location` and pay as XCM fees.
3505	///
3506	/// Fails if:
3507	/// - the `assets` are not known on this chain;
3508	/// - the `assets` cannot be withdrawn with that location as the Origin.
3509	fn charge_fees(location: Location, assets: Assets) -> DispatchResult {
3510		T::XcmExecutor::charge_fees(location.clone(), assets.clone()).map_err(|error| {
3511			tracing::debug!(
3512				target: "xcm::pallet_xcm::charge_fees", ?error,
3513				"Failed to charge fees for location with assets",
3514			);
3515			Error::<T>::FeesNotMet
3516		})?;
3517		Self::deposit_event(Event::FeesPaid { paying: location, fees: assets });
3518		Ok(())
3519	}
3520
3521	/// Ensure the correctness of the state of this pallet.
3522	///
3523	/// This should be valid before and after each state transition of this pallet.
3524	///
3525	/// ## Invariants
3526	///
3527	/// All entries stored in the `SupportedVersion` / `VersionNotifiers` / `VersionNotifyTargets`
3528	/// need to be migrated to the `XCM_VERSION`. If they are not, then `CurrentMigration` has to be
3529	/// set.
3530	#[cfg(any(feature = "try-runtime", test))]
3531	pub fn do_try_state() -> Result<(), TryRuntimeError> {
3532		use migration::data::NeedsMigration;
3533
3534		// Take the minimum version between `SafeXcmVersion` and `latest - 1` and ensure that the
3535		// operational data is stored at least at that version, for example, to prevent issues when
3536		// removing older XCM versions.
3537		let minimal_allowed_xcm_version = if let Some(safe_xcm_version) = SafeXcmVersion::<T>::get()
3538		{
3539			XCM_VERSION.saturating_sub(1).min(safe_xcm_version)
3540		} else {
3541			XCM_VERSION.saturating_sub(1)
3542		};
3543
3544		// check `Queries`
3545		ensure!(
3546			!Queries::<T>::iter_values()
3547				.any(|data| data.needs_migration(minimal_allowed_xcm_version)),
3548			TryRuntimeError::Other("`Queries` data should be migrated to the higher xcm version!")
3549		);
3550
3551		// check `LockedFungibles`
3552		ensure!(
3553			!LockedFungibles::<T>::iter_values()
3554				.any(|data| data.needs_migration(minimal_allowed_xcm_version)),
3555			TryRuntimeError::Other(
3556				"`LockedFungibles` data should be migrated to the higher xcm version!"
3557			)
3558		);
3559
3560		// check `RemoteLockedFungibles`
3561		ensure!(
3562			!RemoteLockedFungibles::<T>::iter()
3563				.any(|(key, data)| key.needs_migration(minimal_allowed_xcm_version) ||
3564					data.needs_migration(minimal_allowed_xcm_version)),
3565			TryRuntimeError::Other(
3566				"`RemoteLockedFungibles` data should be migrated to the higher xcm version!"
3567			)
3568		);
3569
3570		// if migration has been already scheduled, everything is ok and data will be eventually
3571		// migrated
3572		if CurrentMigration::<T>::exists() {
3573			return Ok(())
3574		}
3575
3576		// if migration has NOT been scheduled yet, we need to check all operational data
3577		for v in 0..XCM_VERSION {
3578			ensure!(
3579				SupportedVersion::<T>::iter_prefix(v).next().is_none(),
3580				TryRuntimeError::Other(
3581					"`SupportedVersion` data should be migrated to the `XCM_VERSION`!`"
3582				)
3583			);
3584			ensure!(
3585				VersionNotifiers::<T>::iter_prefix(v).next().is_none(),
3586				TryRuntimeError::Other(
3587					"`VersionNotifiers` data should be migrated to the `XCM_VERSION`!`"
3588				)
3589			);
3590			ensure!(
3591				VersionNotifyTargets::<T>::iter_prefix(v).next().is_none(),
3592				TryRuntimeError::Other(
3593					"`VersionNotifyTargets` data should be migrated to the `XCM_VERSION`!`"
3594				)
3595			);
3596		}
3597
3598		Ok(())
3599	}
3600}
3601
3602pub struct LockTicket<T: Config> {
3603	sovereign_account: T::AccountId,
3604	amount: BalanceOf<T>,
3605	unlocker: Location,
3606	item_index: Option<usize>,
3607}
3608
3609impl<T: Config> xcm_executor::traits::Enact for LockTicket<T> {
3610	fn enact(self) -> Result<(), xcm_executor::traits::LockError> {
3611		use xcm_executor::traits::LockError::UnexpectedState;
3612		let mut locks = LockedFungibles::<T>::get(&self.sovereign_account).unwrap_or_default();
3613		match self.item_index {
3614			Some(index) => {
3615				ensure!(locks.len() > index, UnexpectedState);
3616				ensure!(locks[index].1.try_as::<_>() == Ok(&self.unlocker), UnexpectedState);
3617				locks[index].0 = locks[index].0.max(self.amount);
3618			},
3619			None => {
3620				locks.try_push((self.amount, self.unlocker.into())).map_err(
3621					|(balance, location)| {
3622						tracing::debug!(
3623							target: "xcm::pallet_xcm::enact", ?balance, ?location,
3624							"Failed to lock fungibles",
3625						);
3626						UnexpectedState
3627					},
3628				)?;
3629			},
3630		}
3631		LockedFungibles::<T>::insert(&self.sovereign_account, locks);
3632		T::Currency::extend_lock(
3633			*b"py/xcmlk",
3634			&self.sovereign_account,
3635			self.amount,
3636			WithdrawReasons::all(),
3637		);
3638		Ok(())
3639	}
3640}
3641
3642pub struct UnlockTicket<T: Config> {
3643	sovereign_account: T::AccountId,
3644	amount: BalanceOf<T>,
3645	unlocker: Location,
3646}
3647
3648impl<T: Config> xcm_executor::traits::Enact for UnlockTicket<T> {
3649	fn enact(self) -> Result<(), xcm_executor::traits::LockError> {
3650		use xcm_executor::traits::LockError::UnexpectedState;
3651		let mut locks =
3652			LockedFungibles::<T>::get(&self.sovereign_account).ok_or(UnexpectedState)?;
3653		let mut maybe_remove_index = None;
3654		let mut locked = BalanceOf::<T>::zero();
3655		let mut found = false;
3656		// We could just as well do with an into_iter, filter_map and collect, however this way
3657		// avoids making an allocation.
3658		for (i, x) in locks.iter_mut().enumerate() {
3659			if x.1.try_as::<_>().defensive() == Ok(&self.unlocker) {
3660				x.0 = x.0.saturating_sub(self.amount);
3661				if x.0.is_zero() {
3662					maybe_remove_index = Some(i);
3663				}
3664				found = true;
3665			}
3666			locked = locked.max(x.0);
3667		}
3668		ensure!(found, UnexpectedState);
3669		if let Some(remove_index) = maybe_remove_index {
3670			locks.swap_remove(remove_index);
3671		}
3672		LockedFungibles::<T>::insert(&self.sovereign_account, locks);
3673		let reasons = WithdrawReasons::all();
3674		T::Currency::set_lock(*b"py/xcmlk", &self.sovereign_account, locked, reasons);
3675		Ok(())
3676	}
3677}
3678
3679pub struct ReduceTicket<T: Config> {
3680	key: (u32, T::AccountId, VersionedAssetId),
3681	amount: u128,
3682	locker: VersionedLocation,
3683	owner: VersionedLocation,
3684}
3685
3686impl<T: Config> xcm_executor::traits::Enact for ReduceTicket<T> {
3687	fn enact(self) -> Result<(), xcm_executor::traits::LockError> {
3688		use xcm_executor::traits::LockError::UnexpectedState;
3689		let mut record = RemoteLockedFungibles::<T>::get(&self.key).ok_or(UnexpectedState)?;
3690		ensure!(self.locker == record.locker && self.owner == record.owner, UnexpectedState);
3691		let new_amount = record.amount.checked_sub(self.amount).ok_or(UnexpectedState)?;
3692		ensure!(record.amount_held().map_or(true, |h| new_amount >= h), UnexpectedState);
3693		if new_amount == 0 {
3694			RemoteLockedFungibles::<T>::remove(&self.key);
3695		} else {
3696			record.amount = new_amount;
3697			RemoteLockedFungibles::<T>::insert(&self.key, &record);
3698		}
3699		Ok(())
3700	}
3701}
3702
3703impl<T: Config> xcm_executor::traits::AssetLock for Pallet<T> {
3704	type LockTicket = LockTicket<T>;
3705	type UnlockTicket = UnlockTicket<T>;
3706	type ReduceTicket = ReduceTicket<T>;
3707
3708	fn prepare_lock(
3709		unlocker: Location,
3710		asset: Asset,
3711		owner: Location,
3712	) -> Result<LockTicket<T>, xcm_executor::traits::LockError> {
3713		use xcm_executor::traits::LockError::*;
3714		let sovereign_account = T::SovereignAccountOf::convert_location(&owner).ok_or(BadOwner)?;
3715		let amount = T::CurrencyMatcher::matches_fungible(&asset).ok_or(UnknownAsset)?;
3716		ensure!(T::Currency::free_balance(&sovereign_account) >= amount, AssetNotOwned);
3717		let locks = LockedFungibles::<T>::get(&sovereign_account).unwrap_or_default();
3718		let item_index = locks.iter().position(|x| x.1.try_as::<_>() == Ok(&unlocker));
3719		ensure!(item_index.is_some() || locks.len() < T::MaxLockers::get() as usize, NoResources);
3720		Ok(LockTicket { sovereign_account, amount, unlocker, item_index })
3721	}
3722
3723	fn prepare_unlock(
3724		unlocker: Location,
3725		asset: Asset,
3726		owner: Location,
3727	) -> Result<UnlockTicket<T>, xcm_executor::traits::LockError> {
3728		use xcm_executor::traits::LockError::*;
3729		let sovereign_account = T::SovereignAccountOf::convert_location(&owner).ok_or(BadOwner)?;
3730		let amount = T::CurrencyMatcher::matches_fungible(&asset).ok_or(UnknownAsset)?;
3731		let locks = LockedFungibles::<T>::get(&sovereign_account).unwrap_or_default();
3732		let item_index =
3733			locks.iter().position(|x| x.1.try_as::<_>() == Ok(&unlocker)).ok_or(NotLocked)?;
3734		ensure!(locks[item_index].0 >= amount, NotLocked);
3735		Ok(UnlockTicket { sovereign_account, amount, unlocker })
3736	}
3737
3738	fn note_unlockable(
3739		locker: Location,
3740		asset: Asset,
3741		mut owner: Location,
3742	) -> Result<(), xcm_executor::traits::LockError> {
3743		use xcm_executor::traits::LockError::*;
3744		ensure!(T::TrustedLockers::contains(&locker, &asset), NotTrusted);
3745		let amount = match asset.fun {
3746			Fungible(a) => a,
3747			NonFungible(_) => return Err(Unimplemented),
3748		};
3749		owner.remove_network_id();
3750		let account = T::SovereignAccountOf::convert_location(&owner).ok_or(BadOwner)?;
3751		let locker = locker.into();
3752		let owner = owner.into();
3753		let id: VersionedAssetId = asset.id.into();
3754		let key = (XCM_VERSION, account, id);
3755		let mut record =
3756			RemoteLockedFungibleRecord { amount, owner, locker, consumers: BoundedVec::default() };
3757		if let Some(old) = RemoteLockedFungibles::<T>::get(&key) {
3758			// Make sure that the new record wouldn't clobber any old data.
3759			ensure!(old.locker == record.locker && old.owner == record.owner, WouldClobber);
3760			record.consumers = old.consumers;
3761			record.amount = record.amount.max(old.amount);
3762		}
3763		RemoteLockedFungibles::<T>::insert(&key, record);
3764		Ok(())
3765	}
3766
3767	fn prepare_reduce_unlockable(
3768		locker: Location,
3769		asset: Asset,
3770		mut owner: Location,
3771	) -> Result<Self::ReduceTicket, xcm_executor::traits::LockError> {
3772		use xcm_executor::traits::LockError::*;
3773		let amount = match asset.fun {
3774			Fungible(a) => a,
3775			NonFungible(_) => return Err(Unimplemented),
3776		};
3777		owner.remove_network_id();
3778		let sovereign_account = T::SovereignAccountOf::convert_location(&owner).ok_or(BadOwner)?;
3779		let locker = locker.into();
3780		let owner = owner.into();
3781		let id: VersionedAssetId = asset.id.into();
3782		let key = (XCM_VERSION, sovereign_account, id);
3783
3784		let record = RemoteLockedFungibles::<T>::get(&key).ok_or(NotLocked)?;
3785		// Make sure that the record contains what we expect and there's enough to unlock.
3786		ensure!(locker == record.locker && owner == record.owner, WouldClobber);
3787		ensure!(record.amount >= amount, NotEnoughLocked);
3788		ensure!(
3789			record.amount_held().map_or(true, |h| record.amount.saturating_sub(amount) >= h),
3790			InUse
3791		);
3792		Ok(ReduceTicket { key, amount, locker, owner })
3793	}
3794}
3795
3796impl<T: Config> WrapVersion for Pallet<T> {
3797	fn wrap_version<RuntimeCall: Decode + GetDispatchInfo>(
3798		dest: &Location,
3799		xcm: impl Into<VersionedXcm<RuntimeCall>>,
3800	) -> Result<VersionedXcm<RuntimeCall>, ()> {
3801		Self::get_version_for(dest)
3802			.or_else(|| {
3803				Self::note_unknown_version(dest);
3804				SafeXcmVersion::<T>::get()
3805			})
3806			.ok_or_else(|| {
3807				tracing::trace!(
3808					target: "xcm::pallet_xcm::wrap_version",
3809					?dest, "Could not determine a version to wrap XCM for destination",
3810				);
3811				()
3812			})
3813			.and_then(|v| xcm.into().into_version(v.min(XCM_VERSION)))
3814	}
3815}
3816
3817impl<T: Config> GetVersion for Pallet<T> {
3818	fn get_version_for(dest: &Location) -> Option<XcmVersion> {
3819		SupportedVersion::<T>::get(XCM_VERSION, LatestVersionedLocation(dest))
3820	}
3821}
3822
3823impl<T: Config> VersionChangeNotifier for Pallet<T> {
3824	/// Start notifying `location` should the XCM version of this chain change.
3825	///
3826	/// When it does, this type should ensure a `QueryResponse` message is sent with the given
3827	/// `query_id` & `max_weight` and with a `response` of `Response::Version`. This should happen
3828	/// until/unless `stop` is called with the correct `query_id`.
3829	///
3830	/// If the `location` has an ongoing notification and when this function is called, then an
3831	/// error should be returned.
3832	fn start(
3833		dest: &Location,
3834		query_id: QueryId,
3835		max_weight: Weight,
3836		_context: &XcmContext,
3837	) -> XcmResult {
3838		let versioned_dest = LatestVersionedLocation(dest);
3839		let already = VersionNotifyTargets::<T>::contains_key(XCM_VERSION, versioned_dest);
3840		ensure!(!already, XcmError::InvalidLocation);
3841
3842		let xcm_version = T::AdvertisedXcmVersion::get();
3843		let response = Response::Version(xcm_version);
3844		let instruction = QueryResponse { query_id, response, max_weight, querier: None };
3845		let (message_id, cost) = send_xcm::<T::XcmRouter>(dest.clone(), Xcm(vec![instruction]))?;
3846		Self::deposit_event(Event::<T>::VersionNotifyStarted {
3847			destination: dest.clone(),
3848			cost,
3849			message_id,
3850		});
3851
3852		let value = (query_id, max_weight, xcm_version);
3853		VersionNotifyTargets::<T>::insert(XCM_VERSION, versioned_dest, value);
3854		Ok(())
3855	}
3856
3857	/// Stop notifying `location` should the XCM change. This is a no-op if there was never a
3858	/// subscription.
3859	fn stop(dest: &Location, _context: &XcmContext) -> XcmResult {
3860		VersionNotifyTargets::<T>::remove(XCM_VERSION, LatestVersionedLocation(dest));
3861		Ok(())
3862	}
3863
3864	/// Return true if a location is subscribed to XCM version changes.
3865	fn is_subscribed(dest: &Location) -> bool {
3866		let versioned_dest = LatestVersionedLocation(dest);
3867		VersionNotifyTargets::<T>::contains_key(XCM_VERSION, versioned_dest)
3868	}
3869}
3870
3871impl<T: Config> DropAssets for Pallet<T> {
3872	fn drop_assets(origin: &Location, assets: AssetsInHolding, _context: &XcmContext) -> Weight {
3873		if assets.is_empty() {
3874			return Weight::zero()
3875		}
3876		let versioned = VersionedAssets::from(Assets::from(assets));
3877		let hash = BlakeTwo256::hash_of(&(&origin, &versioned));
3878		AssetTraps::<T>::mutate(hash, |n| *n += 1);
3879		Self::deposit_event(Event::AssetsTrapped {
3880			hash,
3881			origin: origin.clone(),
3882			assets: versioned,
3883		});
3884		// TODO #3735: Put the real weight in there.
3885		Weight::zero()
3886	}
3887}
3888
3889impl<T: Config> ClaimAssets for Pallet<T> {
3890	fn claim_assets(
3891		origin: &Location,
3892		ticket: &Location,
3893		assets: &Assets,
3894		_context: &XcmContext,
3895	) -> bool {
3896		let mut versioned = VersionedAssets::from(assets.clone());
3897		match ticket.unpack() {
3898			(0, [GeneralIndex(i)]) =>
3899				versioned = match versioned.into_version(*i as u32) {
3900					Ok(v) => v,
3901					Err(()) => return false,
3902				},
3903			(0, []) => (),
3904			_ => return false,
3905		};
3906		let hash = BlakeTwo256::hash_of(&(origin.clone(), versioned.clone()));
3907		match AssetTraps::<T>::get(hash) {
3908			0 => return false,
3909			1 => AssetTraps::<T>::remove(hash),
3910			n => AssetTraps::<T>::insert(hash, n - 1),
3911		}
3912		Self::deposit_event(Event::AssetsClaimed {
3913			hash,
3914			origin: origin.clone(),
3915			assets: versioned,
3916		});
3917		return true
3918	}
3919}
3920
3921impl<T: Config> OnResponse for Pallet<T> {
3922	fn expecting_response(
3923		origin: &Location,
3924		query_id: QueryId,
3925		querier: Option<&Location>,
3926	) -> bool {
3927		match Queries::<T>::get(query_id) {
3928			Some(QueryStatus::Pending { responder, maybe_match_querier, .. }) =>
3929				Location::try_from(responder).map_or(false, |r| origin == &r) &&
3930					maybe_match_querier.map_or(true, |match_querier| {
3931						Location::try_from(match_querier).map_or(false, |match_querier| {
3932							querier.map_or(false, |q| q == &match_querier)
3933						})
3934					}),
3935			Some(QueryStatus::VersionNotifier { origin: r, .. }) =>
3936				Location::try_from(r).map_or(false, |r| origin == &r),
3937			_ => false,
3938		}
3939	}
3940
3941	fn on_response(
3942		origin: &Location,
3943		query_id: QueryId,
3944		querier: Option<&Location>,
3945		response: Response,
3946		max_weight: Weight,
3947		_context: &XcmContext,
3948	) -> Weight {
3949		let origin = origin.clone();
3950		match (response, Queries::<T>::get(query_id)) {
3951			(
3952				Response::Version(v),
3953				Some(QueryStatus::VersionNotifier { origin: expected_origin, is_active }),
3954			) => {
3955				let origin: Location = match expected_origin.try_into() {
3956					Ok(o) if o == origin => o,
3957					Ok(o) => {
3958						Self::deposit_event(Event::InvalidResponder {
3959							origin: origin.clone(),
3960							query_id,
3961							expected_location: Some(o),
3962						});
3963						return Weight::zero()
3964					},
3965					_ => {
3966						Self::deposit_event(Event::InvalidResponder {
3967							origin: origin.clone(),
3968							query_id,
3969							expected_location: None,
3970						});
3971						// TODO #3735: Correct weight for this.
3972						return Weight::zero()
3973					},
3974				};
3975				// TODO #3735: Check max_weight is correct.
3976				if !is_active {
3977					Queries::<T>::insert(
3978						query_id,
3979						QueryStatus::VersionNotifier {
3980							origin: origin.clone().into(),
3981							is_active: true,
3982						},
3983					);
3984				}
3985				// We're being notified of a version change.
3986				SupportedVersion::<T>::insert(XCM_VERSION, LatestVersionedLocation(&origin), v);
3987				Self::deposit_event(Event::SupportedVersionChanged {
3988					location: origin,
3989					version: v,
3990				});
3991				Weight::zero()
3992			},
3993			(
3994				response,
3995				Some(QueryStatus::Pending { responder, maybe_notify, maybe_match_querier, .. }),
3996			) => {
3997				if let Some(match_querier) = maybe_match_querier {
3998					let match_querier = match Location::try_from(match_querier) {
3999						Ok(mq) => mq,
4000						Err(_) => {
4001							Self::deposit_event(Event::InvalidQuerierVersion {
4002								origin: origin.clone(),
4003								query_id,
4004							});
4005							return Weight::zero()
4006						},
4007					};
4008					if querier.map_or(true, |q| q != &match_querier) {
4009						Self::deposit_event(Event::InvalidQuerier {
4010							origin: origin.clone(),
4011							query_id,
4012							expected_querier: match_querier,
4013							maybe_actual_querier: querier.cloned(),
4014						});
4015						return Weight::zero()
4016					}
4017				}
4018				let responder = match Location::try_from(responder) {
4019					Ok(r) => r,
4020					Err(_) => {
4021						Self::deposit_event(Event::InvalidResponderVersion {
4022							origin: origin.clone(),
4023							query_id,
4024						});
4025						return Weight::zero()
4026					},
4027				};
4028				if origin != responder {
4029					Self::deposit_event(Event::InvalidResponder {
4030						origin: origin.clone(),
4031						query_id,
4032						expected_location: Some(responder),
4033					});
4034					return Weight::zero()
4035				}
4036				match maybe_notify {
4037					Some((pallet_index, call_index)) => {
4038						// This is a bit horrible, but we happen to know that the `Call` will
4039						// be built by `(pallet_index: u8, call_index: u8, QueryId, Response)`.
4040						// So we just encode that and then re-encode to a real Call.
4041						let bare = (pallet_index, call_index, query_id, response);
4042						if let Ok(call) = bare.using_encoded(|mut bytes| {
4043							<T as Config>::RuntimeCall::decode(&mut bytes)
4044						}) {
4045							Queries::<T>::remove(query_id);
4046							let weight = call.get_dispatch_info().call_weight;
4047							if weight.any_gt(max_weight) {
4048								let e = Event::NotifyOverweight {
4049									query_id,
4050									pallet_index,
4051									call_index,
4052									actual_weight: weight,
4053									max_budgeted_weight: max_weight,
4054								};
4055								Self::deposit_event(e);
4056								return Weight::zero()
4057							}
4058							let dispatch_origin = Origin::Response(origin.clone()).into();
4059							match call.dispatch(dispatch_origin) {
4060								Ok(post_info) => {
4061									let e = Event::Notified { query_id, pallet_index, call_index };
4062									Self::deposit_event(e);
4063									post_info.actual_weight
4064								},
4065								Err(error_and_info) => {
4066									let e = Event::NotifyDispatchError {
4067										query_id,
4068										pallet_index,
4069										call_index,
4070									};
4071									Self::deposit_event(e);
4072									// Not much to do with the result as it is. It's up to the
4073									// parachain to ensure that the message makes sense.
4074									error_and_info.post_info.actual_weight
4075								},
4076							}
4077							.unwrap_or(weight)
4078						} else {
4079							let e =
4080								Event::NotifyDecodeFailed { query_id, pallet_index, call_index };
4081							Self::deposit_event(e);
4082							Weight::zero()
4083						}
4084					},
4085					None => {
4086						let e = Event::ResponseReady { query_id, response: response.clone() };
4087						Self::deposit_event(e);
4088						let at = frame_system::Pallet::<T>::current_block_number();
4089						let response = response.into();
4090						Queries::<T>::insert(query_id, QueryStatus::Ready { response, at });
4091						Weight::zero()
4092					},
4093				}
4094			},
4095			_ => {
4096				let e = Event::UnexpectedResponse { origin: origin.clone(), query_id };
4097				Self::deposit_event(e);
4098				Weight::zero()
4099			},
4100		}
4101	}
4102}
4103
4104impl<T: Config> CheckSuspension for Pallet<T> {
4105	fn is_suspended<Call>(
4106		_origin: &Location,
4107		_instructions: &mut [Instruction<Call>],
4108		_max_weight: Weight,
4109		_properties: &mut Properties,
4110	) -> bool {
4111		XcmExecutionSuspended::<T>::get()
4112	}
4113}
4114
4115impl<T: Config> RecordXcm for Pallet<T> {
4116	fn should_record() -> bool {
4117		ShouldRecordXcm::<T>::get()
4118	}
4119
4120	fn set_record_xcm(enabled: bool) {
4121		ShouldRecordXcm::<T>::put(enabled);
4122	}
4123
4124	fn recorded_xcm() -> Option<Xcm<()>> {
4125		RecordedXcm::<T>::get()
4126	}
4127
4128	fn record(xcm: Xcm<()>) {
4129		RecordedXcm::<T>::put(xcm);
4130	}
4131}
4132
4133/// Ensure that the origin `o` represents an XCM (`Transact`) origin.
4134///
4135/// Returns `Ok` with the location of the XCM sender or an `Err` otherwise.
4136pub fn ensure_xcm<OuterOrigin>(o: OuterOrigin) -> Result<Location, BadOrigin>
4137where
4138	OuterOrigin: Into<Result<Origin, OuterOrigin>>,
4139{
4140	match o.into() {
4141		Ok(Origin::Xcm(location)) => Ok(location),
4142		_ => Err(BadOrigin),
4143	}
4144}
4145
4146/// Ensure that the origin `o` represents an XCM response origin.
4147///
4148/// Returns `Ok` with the location of the responder or an `Err` otherwise.
4149pub fn ensure_response<OuterOrigin>(o: OuterOrigin) -> Result<Location, BadOrigin>
4150where
4151	OuterOrigin: Into<Result<Origin, OuterOrigin>>,
4152{
4153	match o.into() {
4154		Ok(Origin::Response(location)) => Ok(location),
4155		_ => Err(BadOrigin),
4156	}
4157}
4158
4159/// Filter for `(origin: Location, target: Location)` to find whether `target` has explicitly
4160/// authorized `origin` to alias it.
4161///
4162/// Note: users can authorize other locations to alias them by using
4163/// `pallet_xcm::add_authorized_alias()`.
4164pub struct AuthorizedAliasers<T>(PhantomData<T>);
4165impl<L: Into<VersionedLocation> + Clone, T: Config> ContainsPair<L, L> for AuthorizedAliasers<T> {
4166	fn contains(origin: &L, target: &L) -> bool {
4167		let origin: VersionedLocation = origin.clone().into();
4168		let target: VersionedLocation = target.clone().into();
4169		tracing::trace!(target: "xcm::pallet_xcm::AuthorizedAliasers::contains", ?origin, ?target);
4170		// return true if the `origin` has been explicitly authorized by `target` as aliaser, and
4171		// the authorization has not expired
4172		Pallet::<T>::is_authorized_alias(origin, target).unwrap_or(false)
4173	}
4174}
4175
4176/// Filter for `Location` to find those which represent a strict majority approval of an
4177/// identified plurality.
4178///
4179/// May reasonably be used with `EnsureXcm`.
4180pub struct IsMajorityOfBody<Prefix, Body>(PhantomData<(Prefix, Body)>);
4181impl<Prefix: Get<Location>, Body: Get<BodyId>> Contains<Location>
4182	for IsMajorityOfBody<Prefix, Body>
4183{
4184	fn contains(l: &Location) -> bool {
4185		let maybe_suffix = l.match_and_split(&Prefix::get());
4186		matches!(maybe_suffix, Some(Plurality { id, part }) if id == &Body::get() && part.is_majority())
4187	}
4188}
4189
4190/// Filter for `Location` to find those which represent a voice of an identified plurality.
4191///
4192/// May reasonably be used with `EnsureXcm`.
4193pub struct IsVoiceOfBody<Prefix, Body>(PhantomData<(Prefix, Body)>);
4194impl<Prefix: Get<Location>, Body: Get<BodyId>> Contains<Location> for IsVoiceOfBody<Prefix, Body> {
4195	fn contains(l: &Location) -> bool {
4196		let maybe_suffix = l.match_and_split(&Prefix::get());
4197		matches!(maybe_suffix, Some(Plurality { id, part }) if id == &Body::get() && part == &BodyPart::Voice)
4198	}
4199}
4200
4201/// `EnsureOrigin` implementation succeeding with a `Location` value to recognize and filter
4202/// the `Origin::Xcm` item.
4203pub struct EnsureXcm<F, L = Location>(PhantomData<(F, L)>);
4204impl<
4205		O: OriginTrait + From<Origin>,
4206		F: Contains<L>,
4207		L: TryFrom<Location> + TryInto<Location> + Clone,
4208	> EnsureOrigin<O> for EnsureXcm<F, L>
4209where
4210	for<'a> &'a O::PalletsOrigin: TryInto<&'a Origin>,
4211{
4212	type Success = L;
4213
4214	fn try_origin(outer: O) -> Result<Self::Success, O> {
4215		match outer.caller().try_into() {
4216			Ok(Origin::Xcm(ref location)) =>
4217				if let Ok(location) = location.clone().try_into() {
4218					if F::contains(&location) {
4219						return Ok(location);
4220					}
4221				},
4222			_ => (),
4223		}
4224
4225		Err(outer)
4226	}
4227
4228	#[cfg(feature = "runtime-benchmarks")]
4229	fn try_successful_origin() -> Result<O, ()> {
4230		Ok(O::from(Origin::Xcm(Here.into())))
4231	}
4232}
4233
4234/// `EnsureOrigin` implementation succeeding with a `Location` value to recognize and filter
4235/// the `Origin::Response` item.
4236pub struct EnsureResponse<F>(PhantomData<F>);
4237impl<O: OriginTrait + From<Origin>, F: Contains<Location>> EnsureOrigin<O> for EnsureResponse<F>
4238where
4239	for<'a> &'a O::PalletsOrigin: TryInto<&'a Origin>,
4240{
4241	type Success = Location;
4242
4243	fn try_origin(outer: O) -> Result<Self::Success, O> {
4244		match outer.caller().try_into() {
4245			Ok(Origin::Response(responder)) => return Ok(responder.clone()),
4246			_ => (),
4247		}
4248
4249		Err(outer)
4250	}
4251
4252	#[cfg(feature = "runtime-benchmarks")]
4253	fn try_successful_origin() -> Result<O, ()> {
4254		Ok(O::from(Origin::Response(Here.into())))
4255	}
4256}
4257
4258/// A simple passthrough where we reuse the `Location`-typed XCM origin as the inner value of
4259/// this crate's `Origin::Xcm` value.
4260pub struct XcmPassthrough<RuntimeOrigin>(PhantomData<RuntimeOrigin>);
4261impl<RuntimeOrigin: From<crate::Origin>> ConvertOrigin<RuntimeOrigin>
4262	for XcmPassthrough<RuntimeOrigin>
4263{
4264	fn convert_origin(
4265		origin: impl Into<Location>,
4266		kind: OriginKind,
4267	) -> Result<RuntimeOrigin, Location> {
4268		let origin = origin.into();
4269		match kind {
4270			OriginKind::Xcm => Ok(crate::Origin::Xcm(origin).into()),
4271			_ => Err(origin),
4272		}
4273	}
4274}