staging_xcm/v5/
mod.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//! Version 5 of the Cross-Consensus Message format data structures.
18
19pub use super::v3::GetWeight;
20use super::v4::{
21	Instruction as OldInstruction, PalletInfo as OldPalletInfo,
22	QueryResponseInfo as OldQueryResponseInfo, Response as OldResponse, Xcm as OldXcm,
23};
24use crate::{utils::decode_xcm_instructions, DoubleEncoded};
25use alloc::{vec, vec::Vec};
26use bounded_collections::{parameter_types, BoundedVec};
27use codec::{
28	self, Decode, DecodeWithMemTracking, Encode, Error as CodecError, Input as CodecInput,
29	MaxEncodedLen,
30};
31use core::{fmt::Debug, result};
32use derive_where::derive_where;
33use scale_info::TypeInfo;
34
35mod asset;
36mod junction;
37pub(crate) mod junctions;
38mod location;
39mod traits;
40
41pub use asset::{
42	Asset, AssetFilter, AssetId, AssetInstance, AssetTransferFilter, Assets, Fungibility,
43	WildAsset, WildFungibility, MAX_ITEMS_IN_ASSETS,
44};
45pub use junction::{
46	BodyId, BodyPart, Junction, NetworkId, ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH,
47};
48pub use junctions::Junctions;
49pub use location::{Ancestor, AncestorThen, InteriorLocation, Location, Parent, ParentThen};
50pub use traits::{
51	send_xcm, validate_send, Error, ExecuteXcm, Outcome, PreparedMessage, Reanchorable, Result,
52	SendError, SendResult, SendXcm, Weight, XcmHash,
53};
54// These parts of XCM v4 are unchanged in XCM v5, and are re-imported here.
55pub use super::v4::{MaxDispatchErrorLen, MaybeErrorCode, OriginKind, WeightLimit};
56
57pub const VERSION: super::Version = 5;
58
59/// An identifier for a query.
60pub type QueryId = u64;
61
62#[derive(Default, DecodeWithMemTracking, Encode, TypeInfo)]
63#[derive_where(Clone, Eq, PartialEq, Debug)]
64#[codec(encode_bound())]
65#[codec(decode_bound())]
66#[scale_info(bounds(), skip_type_params(Call))]
67pub struct Xcm<Call>(pub Vec<Instruction<Call>>);
68
69impl<Call> Decode for Xcm<Call> {
70	fn decode<I: CodecInput>(input: &mut I) -> core::result::Result<Self, CodecError> {
71		Ok(Xcm(decode_xcm_instructions(input)?))
72	}
73}
74
75impl<Call> Xcm<Call> {
76	/// Create an empty instance.
77	pub fn new() -> Self {
78		Self(vec![])
79	}
80
81	/// Return `true` if no instructions are held in `self`.
82	pub fn is_empty(&self) -> bool {
83		self.0.is_empty()
84	}
85
86	/// Return the number of instructions held in `self`.
87	pub fn len(&self) -> usize {
88		self.0.len()
89	}
90
91	/// Return a reference to the inner value.
92	pub fn inner(&self) -> &[Instruction<Call>] {
93		&self.0
94	}
95
96	/// Return a mutable reference to the inner value.
97	pub fn inner_mut(&mut self) -> &mut Vec<Instruction<Call>> {
98		&mut self.0
99	}
100
101	/// Consume and return the inner value.
102	pub fn into_inner(self) -> Vec<Instruction<Call>> {
103		self.0
104	}
105
106	/// Return an iterator over references to the items.
107	pub fn iter(&self) -> impl Iterator<Item = &Instruction<Call>> {
108		self.0.iter()
109	}
110
111	/// Return an iterator over mutable references to the items.
112	pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Instruction<Call>> {
113		self.0.iter_mut()
114	}
115
116	/// Consume and return an iterator over the items.
117	pub fn into_iter(self) -> impl Iterator<Item = Instruction<Call>> {
118		self.0.into_iter()
119	}
120
121	/// Consume and either return `self` if it contains some instructions, or if it's empty, then
122	/// instead return the result of `f`.
123	pub fn or_else(self, f: impl FnOnce() -> Self) -> Self {
124		if self.0.is_empty() {
125			f()
126		} else {
127			self
128		}
129	}
130
131	/// Return the first instruction, if any.
132	pub fn first(&self) -> Option<&Instruction<Call>> {
133		self.0.first()
134	}
135
136	/// Return the last instruction, if any.
137	pub fn last(&self) -> Option<&Instruction<Call>> {
138		self.0.last()
139	}
140
141	/// Return the only instruction, contained in `Self`, iff only one exists (`None` otherwise).
142	pub fn only(&self) -> Option<&Instruction<Call>> {
143		if self.0.len() == 1 {
144			self.0.first()
145		} else {
146			None
147		}
148	}
149
150	/// Return the only instruction, contained in `Self`, iff only one exists (returns `self`
151	/// otherwise).
152	pub fn into_only(mut self) -> core::result::Result<Instruction<Call>, Self> {
153		if self.0.len() == 1 {
154			self.0.pop().ok_or(self)
155		} else {
156			Err(self)
157		}
158	}
159}
160
161impl<Call> From<Vec<Instruction<Call>>> for Xcm<Call> {
162	fn from(c: Vec<Instruction<Call>>) -> Self {
163		Self(c)
164	}
165}
166
167impl<Call> From<Xcm<Call>> for Vec<Instruction<Call>> {
168	fn from(c: Xcm<Call>) -> Self {
169		c.0
170	}
171}
172
173/// A prelude for importing all types typically used when interacting with XCM messages.
174pub mod prelude {
175	mod contents {
176		pub use super::super::{
177			send_xcm, validate_send, Ancestor, AncestorThen, Asset,
178			AssetFilter::{self, *},
179			AssetId,
180			AssetInstance::{self, *},
181			Assets, BodyId, BodyPart, Error as XcmError, ExecuteXcm,
182			Fungibility::{self, *},
183			Hint::{self, *},
184			HintNumVariants,
185			Instruction::*,
186			InteriorLocation,
187			Junction::{self, *},
188			Junctions::{self, Here},
189			Location, MaxAssetTransferFilters, MaybeErrorCode,
190			NetworkId::{self, *},
191			OriginKind, Outcome, PalletInfo, Parent, ParentThen, PreparedMessage, QueryId,
192			QueryResponseInfo, Reanchorable, Response, Result as XcmResult, SendError, SendResult,
193			SendXcm, Weight,
194			WeightLimit::{self, *},
195			WildAsset::{self, *},
196			WildFungibility::{self, Fungible as WildFungible, NonFungible as WildNonFungible},
197			XcmContext, XcmHash, XcmWeightInfo, VERSION as XCM_VERSION,
198		};
199	}
200	pub use super::{Instruction, Xcm};
201	pub use contents::*;
202	pub mod opaque {
203		pub use super::{
204			super::opaque::{Instruction, Xcm},
205			contents::*,
206		};
207	}
208}
209
210parameter_types! {
211	pub MaxPalletNameLen: u32 = 48;
212	pub MaxPalletsInfo: u32 = 64;
213	pub MaxAssetTransferFilters: u32 = 6;
214}
215
216#[derive(
217	Clone, Eq, PartialEq, Encode, Decode, DecodeWithMemTracking, Debug, TypeInfo, MaxEncodedLen,
218)]
219pub struct PalletInfo {
220	#[codec(compact)]
221	pub index: u32,
222	pub name: BoundedVec<u8, MaxPalletNameLen>,
223	pub module_name: BoundedVec<u8, MaxPalletNameLen>,
224	#[codec(compact)]
225	pub major: u32,
226	#[codec(compact)]
227	pub minor: u32,
228	#[codec(compact)]
229	pub patch: u32,
230}
231
232impl TryInto<OldPalletInfo> for PalletInfo {
233	type Error = ();
234
235	fn try_into(self) -> result::Result<OldPalletInfo, Self::Error> {
236		OldPalletInfo::new(
237			self.index,
238			self.name.into_inner(),
239			self.module_name.into_inner(),
240			self.major,
241			self.minor,
242			self.patch,
243		)
244		.map_err(|_| ())
245	}
246}
247
248impl PalletInfo {
249	pub fn new(
250		index: u32,
251		name: Vec<u8>,
252		module_name: Vec<u8>,
253		major: u32,
254		minor: u32,
255		patch: u32,
256	) -> result::Result<Self, Error> {
257		let name = BoundedVec::try_from(name).map_err(|_| Error::Overflow)?;
258		let module_name = BoundedVec::try_from(module_name).map_err(|_| Error::Overflow)?;
259
260		Ok(Self { index, name, module_name, major, minor, patch })
261	}
262}
263
264/// Response data to a query.
265#[derive(
266	Clone, Eq, PartialEq, Encode, Decode, DecodeWithMemTracking, Debug, TypeInfo, MaxEncodedLen,
267)]
268pub enum Response {
269	/// No response. Serves as a neutral default.
270	Null,
271	/// Some assets.
272	Assets(Assets),
273	/// The outcome of an XCM instruction.
274	ExecutionResult(Option<(u32, Error)>),
275	/// An XCM version.
276	Version(super::Version),
277	/// The index, instance name, pallet name and version of some pallets.
278	PalletsInfo(BoundedVec<PalletInfo, MaxPalletsInfo>),
279	/// The status of a dispatch attempt using `Transact`.
280	DispatchResult(MaybeErrorCode),
281}
282
283impl Default for Response {
284	fn default() -> Self {
285		Self::Null
286	}
287}
288
289impl TryFrom<OldResponse> for Response {
290	type Error = ();
291
292	fn try_from(old: OldResponse) -> result::Result<Self, Self::Error> {
293		use OldResponse::*;
294		Ok(match old {
295			Null => Self::Null,
296			Assets(assets) => Self::Assets(assets.try_into()?),
297			ExecutionResult(result) => Self::ExecutionResult(
298				result
299					.map(|(num, old_error)| (num, old_error.try_into()))
300					.map(|(num, result)| result.map(|inner| (num, inner)))
301					.transpose()?,
302			),
303			Version(version) => Self::Version(version),
304			PalletsInfo(pallet_info) => {
305				let inner = pallet_info
306					.into_iter()
307					.map(TryInto::try_into)
308					.collect::<result::Result<Vec<_>, _>>()?;
309				Self::PalletsInfo(
310					BoundedVec::<PalletInfo, MaxPalletsInfo>::try_from(inner).map_err(|_| ())?,
311				)
312			},
313			DispatchResult(maybe_error) => Self::DispatchResult(maybe_error),
314		})
315	}
316}
317
318/// Information regarding the composition of a query response.
319#[derive(Clone, Eq, PartialEq, Encode, Decode, DecodeWithMemTracking, Debug, TypeInfo)]
320pub struct QueryResponseInfo {
321	/// The destination to which the query response message should be send.
322	pub destination: Location,
323	/// The `query_id` field of the `QueryResponse` message.
324	#[codec(compact)]
325	pub query_id: QueryId,
326	/// The `max_weight` field of the `QueryResponse` message.
327	pub max_weight: Weight,
328}
329
330impl TryFrom<OldQueryResponseInfo> for QueryResponseInfo {
331	type Error = ();
332
333	fn try_from(old: OldQueryResponseInfo) -> result::Result<Self, Self::Error> {
334		Ok(Self {
335			destination: old.destination.try_into()?,
336			query_id: old.query_id,
337			max_weight: old.max_weight,
338		})
339	}
340}
341
342/// Contextual data pertaining to a specific list of XCM instructions.
343#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug)]
344pub struct XcmContext {
345	/// The current value of the Origin register of the `XCVM`.
346	pub origin: Option<Location>,
347	/// The identity of the XCM; this may be a hash of its versioned encoding but could also be
348	/// a high-level identity set by an appropriate barrier.
349	pub message_id: XcmHash,
350	/// The current value of the Topic register of the `XCVM`.
351	pub topic: Option<[u8; 32]>,
352}
353
354impl XcmContext {
355	/// Constructor which sets the message ID to the supplied parameter and leaves the origin and
356	/// topic unset.
357	pub fn with_message_id(message_id: XcmHash) -> XcmContext {
358		XcmContext { origin: None, message_id, topic: None }
359	}
360}
361
362/// Cross-Consensus Message: A message from one consensus system to another.
363///
364/// Consensus systems that may send and receive messages include blockchains and smart contracts.
365///
366/// All messages are delivered from a known *origin*, expressed as a `Location`.
367///
368/// This is the inner XCM format and is version-sensitive. Messages are typically passed using the
369/// outer XCM format, known as `VersionedXcm`.
370#[derive(
371	Encode,
372	Decode,
373	DecodeWithMemTracking,
374	TypeInfo,
375	xcm_procedural::XcmWeightInfoTrait,
376	xcm_procedural::Builder,
377)]
378#[derive_where(Clone, Eq, PartialEq, Debug)]
379#[codec(encode_bound())]
380#[codec(decode_bound())]
381#[codec(decode_with_mem_tracking_bound())]
382#[scale_info(bounds(), skip_type_params(Call))]
383pub enum Instruction<Call> {
384	/// Withdraw asset(s) (`assets`) from the ownership of `origin` and place them into the Holding
385	/// Register.
386	///
387	/// - `assets`: The asset(s) to be withdrawn into holding.
388	///
389	/// Kind: *Command*.
390	///
391	/// Errors:
392	#[builder(loads_holding)]
393	WithdrawAsset(Assets),
394
395	/// Asset(s) (`assets`) have been received into the ownership of this system on the `origin`
396	/// system and equivalent derivatives should be placed into the Holding Register.
397	///
398	/// - `assets`: The asset(s) that are minted into holding.
399	///
400	/// Safety: `origin` must be trusted to have received and be storing `assets` such that they
401	/// may later be withdrawn should this system send a corresponding message.
402	///
403	/// Kind: *Trusted Indication*.
404	///
405	/// Errors:
406	#[builder(loads_holding)]
407	ReserveAssetDeposited(Assets),
408
409	/// Asset(s) (`assets`) have been destroyed on the `origin` system and equivalent assets should
410	/// be created and placed into the Holding Register.
411	///
412	/// - `assets`: The asset(s) that are minted into the Holding Register.
413	///
414	/// Safety: `origin` must be trusted to have irrevocably destroyed the corresponding `assets`
415	/// prior as a consequence of sending this message.
416	///
417	/// Kind: *Trusted Indication*.
418	///
419	/// Errors:
420	#[builder(loads_holding)]
421	ReceiveTeleportedAsset(Assets),
422
423	/// Respond with information that the local system is expecting.
424	///
425	/// - `query_id`: The identifier of the query that resulted in this message being sent.
426	/// - `response`: The message content.
427	/// - `max_weight`: The maximum weight that handling this response should take.
428	/// - `querier`: The location responsible for the initiation of the response, if there is one.
429	///   In general this will tend to be the same location as the receiver of this message. NOTE:
430	///   As usual, this is interpreted from the perspective of the receiving consensus system.
431	///
432	/// Safety: Since this is information only, there are no immediate concerns. However, it should
433	/// be remembered that even if the Origin behaves reasonably, it can always be asked to make
434	/// a response to a third-party chain who may or may not be expecting the response. Therefore
435	/// the `querier` should be checked to match the expected value.
436	///
437	/// Kind: *Information*.
438	///
439	/// Errors:
440	QueryResponse {
441		#[codec(compact)]
442		query_id: QueryId,
443		response: Response,
444		max_weight: Weight,
445		querier: Option<Location>,
446	},
447
448	/// Withdraw asset(s) (`assets`) from the ownership of `origin` and place equivalent assets
449	/// under the ownership of `beneficiary`.
450	///
451	/// - `assets`: The asset(s) to be withdrawn.
452	/// - `beneficiary`: The new owner for the assets.
453	///
454	/// Safety: No concerns.
455	///
456	/// Kind: *Command*.
457	///
458	/// Errors:
459	TransferAsset { assets: Assets, beneficiary: Location },
460
461	/// Withdraw asset(s) (`assets`) from the ownership of `origin` and place equivalent assets
462	/// under the ownership of `dest` within this consensus system (i.e. its sovereign account).
463	///
464	/// Send an onward XCM message to `dest` of `ReserveAssetDeposited` with the given
465	/// `xcm`.
466	///
467	/// - `assets`: The asset(s) to be withdrawn.
468	/// - `dest`: The location whose sovereign account will own the assets and thus the effective
469	///   beneficiary for the assets and the notification target for the reserve asset deposit
470	///   message.
471	/// - `xcm`: The instructions that should follow the `ReserveAssetDeposited` instruction, which
472	///   is sent onwards to `dest`.
473	///
474	/// Safety: No concerns.
475	///
476	/// Kind: *Command*.
477	///
478	/// Errors:
479	TransferReserveAsset { assets: Assets, dest: Location, xcm: Xcm<()> },
480
481	/// Apply the encoded transaction `call`, whose dispatch-origin should be `origin` as expressed
482	/// by the kind of origin `origin_kind`.
483	///
484	/// The Transact Status Register is set according to the result of dispatching the call.
485	///
486	/// - `origin_kind`: The means of expressing the message origin as a dispatch origin.
487	/// - `call`: The encoded transaction to be applied.
488	/// - `fallback_max_weight`: Used for compatibility with previous versions. Corresponds to the
489	///   `require_weight_at_most` parameter in previous versions. If you don't care about
490	///   compatibility you can just put `None`. WARNING: If you do, your XCM might not work with
491	///   older versions. Make sure to dry-run and validate.
492	///
493	/// Safety: No concerns.
494	///
495	/// Kind: *Command*.
496	///
497	/// Errors:
498	Transact {
499		origin_kind: OriginKind,
500		fallback_max_weight: Option<Weight>,
501		call: DoubleEncoded<Call>,
502	},
503
504	/// A message to notify about a new incoming HRMP channel. This message is meant to be sent by
505	/// the relay-chain to a para.
506	///
507	/// - `sender`: The sender in the to-be opened channel. Also, the initiator of the channel
508	///   opening.
509	/// - `max_message_size`: The maximum size of a message proposed by the sender.
510	/// - `max_capacity`: The maximum number of messages that can be queued in the channel.
511	///
512	/// Safety: The message should originate directly from the relay-chain.
513	///
514	/// Kind: *System Notification*
515	HrmpNewChannelOpenRequest {
516		#[codec(compact)]
517		sender: u32,
518		#[codec(compact)]
519		max_message_size: u32,
520		#[codec(compact)]
521		max_capacity: u32,
522	},
523
524	/// A message to notify about that a previously sent open channel request has been accepted by
525	/// the recipient. That means that the channel will be opened during the next relay-chain
526	/// session change. This message is meant to be sent by the relay-chain to a para.
527	///
528	/// Safety: The message should originate directly from the relay-chain.
529	///
530	/// Kind: *System Notification*
531	///
532	/// Errors:
533	HrmpChannelAccepted {
534		// NOTE: We keep this as a structured item to a) keep it consistent with the other Hrmp
535		// items; and b) because the field's meaning is not obvious/mentioned from the item name.
536		#[codec(compact)]
537		recipient: u32,
538	},
539
540	/// A message to notify that the other party in an open channel decided to close it. In
541	/// particular, `initiator` is going to close the channel opened from `sender` to the
542	/// `recipient`. The close will be enacted at the next relay-chain session change. This message
543	/// is meant to be sent by the relay-chain to a para.
544	///
545	/// Safety: The message should originate directly from the relay-chain.
546	///
547	/// Kind: *System Notification*
548	///
549	/// Errors:
550	HrmpChannelClosing {
551		#[codec(compact)]
552		initiator: u32,
553		#[codec(compact)]
554		sender: u32,
555		#[codec(compact)]
556		recipient: u32,
557	},
558
559	/// Clear the origin.
560	///
561	/// This may be used by the XCM author to ensure that later instructions cannot command the
562	/// authority of the origin (e.g. if they are being relayed from an untrusted source, as often
563	/// the case with `ReserveAssetDeposited`).
564	///
565	/// Safety: No concerns.
566	///
567	/// Kind: *Command*.
568	///
569	/// Errors:
570	ClearOrigin,
571
572	/// Mutate the origin to some interior location.
573	///
574	/// Kind: *Command*
575	///
576	/// Errors:
577	DescendOrigin(InteriorLocation),
578
579	/// Immediately report the contents of the Error Register to the given destination via XCM.
580	///
581	/// A `QueryResponse` message of type `ExecutionOutcome` is sent to the described destination.
582	///
583	/// - `response_info`: Information for making the response.
584	///
585	/// Kind: *Command*
586	///
587	/// Errors:
588	ReportError(QueryResponseInfo),
589
590	/// Remove the asset(s) (`assets`) from the Holding Register and place equivalent assets under
591	/// the ownership of `beneficiary` within this consensus system.
592	///
593	/// - `assets`: The asset(s) to remove from holding.
594	/// - `beneficiary`: The new owner for the assets.
595	///
596	/// Kind: *Command*
597	///
598	/// Errors:
599	DepositAsset { assets: AssetFilter, beneficiary: Location },
600
601	/// Remove the asset(s) (`assets`) from the Holding Register and place equivalent assets under
602	/// the ownership of `dest` within this consensus system (i.e. deposit them into its sovereign
603	/// account).
604	///
605	/// Send an onward XCM message to `dest` of `ReserveAssetDeposited` with the given `effects`.
606	///
607	/// - `assets`: The asset(s) to remove from holding.
608	/// - `dest`: The location whose sovereign account will own the assets and thus the effective
609	///   beneficiary for the assets and the notification target for the reserve asset deposit
610	///   message.
611	/// - `xcm`: The orders that should follow the `ReserveAssetDeposited` instruction which is
612	///   sent onwards to `dest`.
613	///
614	/// Kind: *Command*
615	///
616	/// Errors:
617	DepositReserveAsset { assets: AssetFilter, dest: Location, xcm: Xcm<()> },
618
619	/// Remove the asset(s) (`want`) from the Holding Register and replace them with alternative
620	/// assets.
621	///
622	/// The minimum amount of assets to be received into the Holding Register for the order not to
623	/// fail may be stated.
624	///
625	/// - `give`: The maximum amount of assets to remove from holding.
626	/// - `want`: The minimum amount of assets which `give` should be exchanged for.
627	/// - `maximal`: If `true`, then prefer to give as much as possible up to the limit of `give`
628	///   and receive accordingly more. If `false`, then prefer to give as little as possible in
629	///   order to receive as little as possible while receiving at least `want`.
630	///
631	/// Kind: *Command*
632	///
633	/// Errors:
634	ExchangeAsset { give: AssetFilter, want: Assets, maximal: bool },
635
636	/// Remove the asset(s) (`assets`) from holding and send a `WithdrawAsset` XCM message to a
637	/// reserve location.
638	///
639	/// - `assets`: The asset(s) to remove from holding.
640	/// - `reserve`: A valid location that acts as a reserve for all asset(s) in `assets`. The
641	///   sovereign account of this consensus system *on the reserve location* will have
642	///   appropriate assets withdrawn and `effects` will be executed on them. There will typically
643	///   be only one valid location on any given asset/chain combination.
644	/// - `xcm`: The instructions to execute on the assets once withdrawn *on the reserve
645	///   location*.
646	///
647	/// Kind: *Command*
648	///
649	/// Errors:
650	InitiateReserveWithdraw { assets: AssetFilter, reserve: Location, xcm: Xcm<()> },
651
652	/// Remove the asset(s) (`assets`) from holding and send a `ReceiveTeleportedAsset` XCM message
653	/// to a `dest` location.
654	///
655	/// - `assets`: The asset(s) to remove from holding.
656	/// - `dest`: A valid location that respects teleports coming from this location.
657	/// - `xcm`: The instructions to execute on the assets once arrived *on the destination
658	///   location*.
659	///
660	/// NOTE: The `dest` location *MUST* respect this origin as a valid teleportation origin for
661	/// all `assets`. If it does not, then the assets may be lost.
662	///
663	/// Kind: *Command*
664	///
665	/// Errors:
666	InitiateTeleport { assets: AssetFilter, dest: Location, xcm: Xcm<()> },
667
668	/// Report to a given destination the contents of the Holding Register.
669	///
670	/// A `QueryResponse` message of type `Assets` is sent to the described destination.
671	///
672	/// - `response_info`: Information for making the response.
673	/// - `assets`: A filter for the assets that should be reported back. The assets reported back
674	///   will be, asset-wise, *the lesser of this value and the holding register*. No wildcards
675	///   will be used when reporting assets back.
676	///
677	/// Kind: *Command*
678	///
679	/// Errors:
680	ReportHolding { response_info: QueryResponseInfo, assets: AssetFilter },
681
682	/// Pay for the execution of some XCM `xcm` and `orders` with up to `weight`
683	/// picoseconds of execution time, paying for this with up to `fees` from the Holding Register.
684	///
685	/// - `fees`: The asset(s) to remove from the Holding Register to pay for fees.
686	/// - `weight_limit`: The maximum amount of weight to purchase; this must be at least the
687	///   expected maximum weight of the total XCM to be executed for the
688	///   `AllowTopLevelPaidExecutionFrom` barrier to allow the XCM be executed.
689	///
690	/// Kind: *Command*
691	///
692	/// Errors:
693	#[builder(pays_fees)]
694	BuyExecution { fees: Asset, weight_limit: WeightLimit },
695
696	/// Refund any surplus weight previously bought with `BuyExecution`.
697	///
698	/// Kind: *Command*
699	///
700	/// Errors: None.
701	RefundSurplus,
702
703	/// Set the Error Handler Register. This is code that should be called in the case of an error
704	/// happening.
705	///
706	/// An error occurring within execution of this code will _NOT_ result in the error register
707	/// being set, nor will an error handler be called due to it. The error handler and appendix
708	/// may each still be set.
709	///
710	/// The apparent weight of this instruction is inclusive of the inner `Xcm`; the executing
711	/// weight however includes only the difference between the previous handler and the new
712	/// handler, which can reasonably be negative, which would result in a surplus.
713	///
714	/// Kind: *Command*
715	///
716	/// Errors: None.
717	SetErrorHandler(Xcm<Call>),
718
719	/// Set the Appendix Register. This is code that should be called after code execution
720	/// (including the error handler if any) is finished. This will be called regardless of whether
721	/// an error occurred.
722	///
723	/// Any error occurring due to execution of this code will result in the error register being
724	/// set, and the error handler (if set) firing.
725	///
726	/// The apparent weight of this instruction is inclusive of the inner `Xcm`; the executing
727	/// weight however includes only the difference between the previous appendix and the new
728	/// appendix, which can reasonably be negative, which would result in a surplus.
729	///
730	/// Kind: *Command*
731	///
732	/// Errors: None.
733	SetAppendix(Xcm<Call>),
734
735	/// Clear the Error Register.
736	///
737	/// Kind: *Command*
738	///
739	/// Errors: None.
740	ClearError,
741
742	/// Create some assets which are being held on behalf of the origin.
743	///
744	/// - `assets`: The assets which are to be claimed. This must match exactly with the assets
745	///   claimable by the origin of the ticket.
746	/// - `ticket`: The ticket of the asset; this is an abstract identifier to help locate the
747	///   asset.
748	///
749	/// Kind: *Command*
750	///
751	/// Errors:
752	#[builder(loads_holding)]
753	ClaimAsset { assets: Assets, ticket: Location },
754
755	/// Always throws an error of type `Trap`.
756	///
757	/// Kind: *Command*
758	///
759	/// Errors:
760	/// - `Trap`: All circumstances, whose inner value is the same as this item's inner value.
761	Trap(#[codec(compact)] u64),
762
763	/// Ask the destination system to respond with the most recent version of XCM that they
764	/// support in a `QueryResponse` instruction. Any changes to this should also elicit similar
765	/// responses when they happen.
766	///
767	/// - `query_id`: An identifier that will be replicated into the returned XCM message.
768	/// - `max_response_weight`: The maximum amount of weight that the `QueryResponse` item which
769	///   is sent as a reply may take to execute. NOTE: If this is unexpectedly large then the
770	///   response may not execute at all.
771	///
772	/// Kind: *Command*
773	///
774	/// Errors: *Fallible*
775	SubscribeVersion {
776		#[codec(compact)]
777		query_id: QueryId,
778		max_response_weight: Weight,
779	},
780
781	/// Cancel the effect of a previous `SubscribeVersion` instruction.
782	///
783	/// Kind: *Command*
784	///
785	/// Errors: *Fallible*
786	UnsubscribeVersion,
787
788	/// Reduce Holding by up to the given assets.
789	///
790	/// Holding is reduced by as much as possible up to the assets in the parameter. It is not an
791	/// error if the Holding does not contain the assets (to make this an error, use `ExpectAsset`
792	/// prior).
793	///
794	/// Kind: *Command*
795	///
796	/// Errors: *Infallible*
797	BurnAsset(Assets),
798
799	/// Throw an error if Holding does not contain at least the given assets.
800	///
801	/// Kind: *Command*
802	///
803	/// Errors:
804	/// - `ExpectationFalse`: If Holding Register does not contain the assets in the parameter.
805	ExpectAsset(Assets),
806
807	/// Ensure that the Origin Register equals some given value and throw an error if not.
808	///
809	/// Kind: *Command*
810	///
811	/// Errors:
812	/// - `ExpectationFalse`: If Origin Register is not equal to the parameter.
813	ExpectOrigin(Option<Location>),
814
815	/// Ensure that the Error Register equals some given value and throw an error if not.
816	///
817	/// Kind: *Command*
818	///
819	/// Errors:
820	/// - `ExpectationFalse`: If the value of the Error Register is not equal to the parameter.
821	ExpectError(Option<(u32, Error)>),
822
823	/// Ensure that the Transact Status Register equals some given value and throw an error if
824	/// not.
825	///
826	/// Kind: *Command*
827	///
828	/// Errors:
829	/// - `ExpectationFalse`: If the value of the Transact Status Register is not equal to the
830	///   parameter.
831	ExpectTransactStatus(MaybeErrorCode),
832
833	/// Query the existence of a particular pallet type.
834	///
835	/// - `module_name`: The module name of the pallet to query.
836	/// - `response_info`: Information for making the response.
837	///
838	/// Sends a `QueryResponse` to Origin whose data field `PalletsInfo` containing the information
839	/// of all pallets on the local chain whose name is equal to `name`. This is empty in the case
840	/// that the local chain is not based on Substrate Frame.
841	///
842	/// Safety: No concerns.
843	///
844	/// Kind: *Command*
845	///
846	/// Errors: *Fallible*.
847	QueryPallet { module_name: Vec<u8>, response_info: QueryResponseInfo },
848
849	/// Ensure that a particular pallet with a particular version exists.
850	///
851	/// - `index: Compact`: The index which identifies the pallet. An error if no pallet exists at
852	///   this index.
853	/// - `name: Vec<u8>`: Name which must be equal to the name of the pallet.
854	/// - `module_name: Vec<u8>`: Module name which must be equal to the name of the module in
855	///   which the pallet exists.
856	/// - `crate_major: Compact`: Version number which must be equal to the major version of the
857	///   crate which implements the pallet.
858	/// - `min_crate_minor: Compact`: Version number which must be at most the minor version of the
859	///   crate which implements the pallet.
860	///
861	/// Safety: No concerns.
862	///
863	/// Kind: *Command*
864	///
865	/// Errors:
866	/// - `ExpectationFalse`: In case any of the expectations are broken.
867	ExpectPallet {
868		#[codec(compact)]
869		index: u32,
870		name: Vec<u8>,
871		module_name: Vec<u8>,
872		#[codec(compact)]
873		crate_major: u32,
874		#[codec(compact)]
875		min_crate_minor: u32,
876	},
877
878	/// Send a `QueryResponse` message containing the value of the Transact Status Register to some
879	/// destination.
880	///
881	/// - `query_response_info`: The information needed for constructing and sending the
882	///   `QueryResponse` message.
883	///
884	/// Safety: No concerns.
885	///
886	/// Kind: *Command*
887	///
888	/// Errors: *Fallible*.
889	ReportTransactStatus(QueryResponseInfo),
890
891	/// Set the Transact Status Register to its default, cleared, value.
892	///
893	/// Safety: No concerns.
894	///
895	/// Kind: *Command*
896	///
897	/// Errors: *Infallible*.
898	ClearTransactStatus,
899
900	/// Set the Origin Register to be some child of the Universal Ancestor.
901	///
902	/// Safety: Should only be usable if the Origin is trusted to represent the Universal Ancestor
903	/// child in general. In general, no Origin should be able to represent the Universal Ancestor
904	/// child which is the root of the local consensus system since it would by extension
905	/// allow it to act as any location within the local consensus.
906	///
907	/// The `Junction` parameter should generally be a `GlobalConsensus` variant since it is only
908	/// these which are children of the Universal Ancestor.
909	///
910	/// Kind: *Command*
911	///
912	/// Errors: *Fallible*.
913	UniversalOrigin(Junction),
914
915	/// Send a message on to Non-Local Consensus system.
916	///
917	/// This will tend to utilize some extra-consensus mechanism, the obvious one being a bridge.
918	/// A fee may be charged; this may be determined based on the contents of `xcm`. It will be
919	/// taken from the Holding register.
920	///
921	/// - `network`: The remote consensus system to which the message should be exported.
922	/// - `destination`: The location relative to the remote consensus system to which the message
923	///   should be sent on arrival.
924	/// - `xcm`: The message to be exported.
925	///
926	/// As an example, to export a message for execution on Statemine (parachain #1000 in the
927	/// Kusama network), you would call with `network: NetworkId::Kusama` and
928	/// `destination: [Parachain(1000)].into()`. Alternatively, to export a message for execution
929	/// on Polkadot, you would call with `network: NetworkId:: Polkadot` and `destination: Here`.
930	///
931	/// Kind: *Command*
932	///
933	/// Errors: *Fallible*.
934	ExportMessage { network: NetworkId, destination: InteriorLocation, xcm: Xcm<()> },
935
936	/// Lock the locally held asset and prevent further transfer or withdrawal.
937	///
938	/// This restriction may be removed by the `UnlockAsset` instruction being called with an
939	/// Origin of `unlocker` and a `target` equal to the current `Origin`.
940	///
941	/// If the locking is successful, then a `NoteUnlockable` instruction is sent to `unlocker`.
942	///
943	/// - `asset`: The asset(s) which should be locked.
944	/// - `unlocker`: The value which the Origin must be for a corresponding `UnlockAsset`
945	///   instruction to work.
946	///
947	/// Kind: *Command*.
948	///
949	/// Errors:
950	LockAsset { asset: Asset, unlocker: Location },
951
952	/// Remove the lock over `asset` on this chain and (if nothing else is preventing it) allow the
953	/// asset to be transferred.
954	///
955	/// - `asset`: The asset to be unlocked.
956	/// - `target`: The owner of the asset on the local chain.
957	///
958	/// Safety: No concerns.
959	///
960	/// Kind: *Command*.
961	///
962	/// Errors:
963	UnlockAsset { asset: Asset, target: Location },
964
965	/// Asset (`asset`) has been locked on the `origin` system and may not be transferred. It may
966	/// only be unlocked with the receipt of the `UnlockAsset` instruction from this chain.
967	///
968	/// - `asset`: The asset(s) which are now unlockable from this origin.
969	/// - `owner`: The owner of the asset on the chain in which it was locked. This may be a
970	///   location specific to the origin network.
971	///
972	/// Safety: `origin` must be trusted to have locked the corresponding `asset`
973	/// prior as a consequence of sending this message.
974	///
975	/// Kind: *Trusted Indication*.
976	///
977	/// Errors:
978	NoteUnlockable { asset: Asset, owner: Location },
979
980	/// Send an `UnlockAsset` instruction to the `locker` for the given `asset`.
981	///
982	/// This may fail if the local system is making use of the fact that the asset is locked or,
983	/// of course, if there is no record that the asset actually is locked.
984	///
985	/// - `asset`: The asset(s) to be unlocked.
986	/// - `locker`: The location from which a previous `NoteUnlockable` was sent and to which an
987	///   `UnlockAsset` should be sent.
988	///
989	/// Kind: *Command*.
990	///
991	/// Errors:
992	RequestUnlock { asset: Asset, locker: Location },
993
994	/// Sets the Fees Mode Register.
995	///
996	/// - `jit_withdraw`: The fees mode item; if set to `true` then fees for any instructions are
997	///   withdrawn as needed using the same mechanism as `WithdrawAssets`.
998	///
999	/// Kind: *Command*.
1000	///
1001	/// Errors:
1002	SetFeesMode { jit_withdraw: bool },
1003
1004	/// Set the Topic Register.
1005	///
1006	/// The 32-byte array identifier in the parameter is not guaranteed to be
1007	/// unique; if such a property is desired, it is up to the code author to
1008	/// enforce uniqueness.
1009	///
1010	/// Safety: No concerns.
1011	///
1012	/// Kind: *Command*
1013	///
1014	/// Errors:
1015	SetTopic([u8; 32]),
1016
1017	/// Clear the Topic Register.
1018	///
1019	/// Kind: *Command*
1020	///
1021	/// Errors: None.
1022	ClearTopic,
1023
1024	/// Alter the current Origin to another given origin.
1025	///
1026	/// Kind: *Command*
1027	///
1028	/// Errors: If the existing state would not allow such a change.
1029	AliasOrigin(Location),
1030
1031	/// A directive to indicate that the origin expects free execution of the message.
1032	///
1033	/// At execution time, this instruction just does a check on the Origin register.
1034	/// However, at the barrier stage messages starting with this instruction can be disregarded if
1035	/// the origin is not acceptable for free execution or the `weight_limit` is `Limited` and
1036	/// insufficient.
1037	///
1038	/// Kind: *Indication*
1039	///
1040	/// Errors: If the given origin is `Some` and not equal to the current Origin register.
1041	UnpaidExecution { weight_limit: WeightLimit, check_origin: Option<Location> },
1042
1043	/// Takes an asset, uses it to pay for execution and puts the rest in the fees register.
1044	///
1045	/// Successor to `BuyExecution`.
1046	/// Defined in [Fellowship RFC 105](https://github.com/polkadot-fellows/RFCs/pull/105).
1047	/// Subsequent `PayFees` after the first one are noops.
1048	#[builder(pays_fees)]
1049	PayFees { asset: Asset },
1050
1051	/// Initiates cross-chain transfer as follows:
1052	///
1053	/// Assets in the holding register are matched using the given list of `AssetTransferFilter`s,
1054	/// they are then transferred based on their specified transfer type:
1055	///
1056	/// - teleport: burn local assets and append a `ReceiveTeleportedAsset` XCM instruction to the
1057	///   XCM program to be sent onward to the `destination` location,
1058	///
1059	/// - reserve deposit: place assets under the ownership of `destination` within this consensus
1060	///   system (i.e. its sovereign account), and append a `ReserveAssetDeposited` XCM instruction
1061	///   to the XCM program to be sent onward to the `destination` location,
1062	///
1063	/// - reserve withdraw: burn local assets and append a `WithdrawAsset` XCM instruction to the
1064	///   XCM program to be sent onward to the `destination` location,
1065	///
1066	/// The onward XCM is then appended a `ClearOrigin` to allow safe execution of any following
1067	/// custom XCM instructions provided in `remote_xcm`.
1068	///
1069	/// The onward XCM also contains either a `PayFees` or `UnpaidExecution` instruction based
1070	/// on the presence of the `remote_fees` parameter (see below).
1071	///
1072	/// If an XCM program requires going through multiple hops, it can compose this instruction to
1073	/// be used at every chain along the path, describing that specific leg of the flow.
1074	///
1075	/// Parameters:
1076	/// - `destination`: The location of the program next hop.
1077	/// - `remote_fees`: If set to `Some(asset_xfer_filter)`, the single asset matching
1078	///   `asset_xfer_filter` in the holding register will be transferred first in the remote XCM
1079	///   program, followed by a `PayFees(fee)`, then rest of transfers follow. This guarantees
1080	///   `remote_xcm` will successfully pass a `AllowTopLevelPaidExecutionFrom` barrier. If set to
1081	///   `None`, a `UnpaidExecution` instruction is appended instead. Please note that these
1082	///   assets are **reserved** for fees, they are sent to the fees register rather than holding.
1083	///   Best practice is to only add here enough to cover fees, and transfer the rest through the
1084	///   `assets` parameter.
1085	/// - `preserve_origin`: Specifies whether the original origin should be preserved or cleared,
1086	///   using the instructions `AliasOrigin` or `ClearOrigin` respectively.
1087	/// - `assets`: List of asset filters matched against existing assets in holding. These are
1088	///   transferred over to `destination` using the specified transfer type, and deposited to
1089	///   holding on `destination`.
1090	/// - `remote_xcm`: Custom instructions that will be executed on the `destination` chain. Note
1091	///   that these instructions will be executed after a `ClearOrigin` so their origin will be
1092	///   `None`.
1093	///
1094	/// Safety: No concerns.
1095	///
1096	/// Kind: *Command*
1097	InitiateTransfer {
1098		destination: Location,
1099		remote_fees: Option<AssetTransferFilter>,
1100		preserve_origin: bool,
1101		assets: BoundedVec<AssetTransferFilter, MaxAssetTransferFilters>,
1102		remote_xcm: Xcm<()>,
1103	},
1104
1105	/// Executes inner `xcm` with origin set to the provided `descendant_origin`. Once the inner
1106	/// `xcm` is executed, the original origin (the one active for this instruction) is restored.
1107	///
1108	/// Parameters:
1109	/// - `descendant_origin`: The origin that will be used during the execution of the inner
1110	///   `xcm`. If set to `None`, the inner `xcm` is executed with no origin. If set to `Some(o)`,
1111	///   the inner `xcm` is executed as if there was a `DescendOrigin(o)` executed before it, and
1112	///   runs the inner xcm with origin: `original_origin.append_with(o)`.
1113	/// - `xcm`: Inner instructions that will be executed with the origin modified according to
1114	///   `descendant_origin`.
1115	///
1116	/// Safety: No concerns.
1117	///
1118	/// Kind: *Command*
1119	///
1120	/// Errors:
1121	/// - `BadOrigin`
1122	ExecuteWithOrigin { descendant_origin: Option<InteriorLocation>, xcm: Xcm<Call> },
1123
1124	/// Set hints for XCM execution.
1125	///
1126	/// These hints change the behaviour of the XCM program they are present in.
1127	///
1128	/// Parameters:
1129	///
1130	/// - `hints`: A bounded vector of `ExecutionHint`, specifying the different hints that will
1131	/// be activated.
1132	SetHints { hints: BoundedVec<Hint, HintNumVariants> },
1133}
1134
1135#[derive(
1136	Encode,
1137	Decode,
1138	DecodeWithMemTracking,
1139	TypeInfo,
1140	Debug,
1141	PartialEq,
1142	Eq,
1143	Clone,
1144	xcm_procedural::NumVariants,
1145)]
1146pub enum Hint {
1147	/// Set asset claimer for all the trapped assets during the execution.
1148	///
1149	/// - `location`: The claimer of any assets potentially trapped during the execution of current
1150	///   XCM. It can be an arbitrary location, not necessarily the caller or origin.
1151	AssetClaimer { location: Location },
1152}
1153
1154impl<Call> Xcm<Call> {
1155	pub fn into<C>(self) -> Xcm<C> {
1156		Xcm::from(self)
1157	}
1158	pub fn from<C>(xcm: Xcm<C>) -> Self {
1159		Self(xcm.0.into_iter().map(Instruction::<Call>::from).collect())
1160	}
1161}
1162
1163impl<Call> Instruction<Call> {
1164	pub fn into<C>(self) -> Instruction<C> {
1165		Instruction::from(self)
1166	}
1167	pub fn from<C>(xcm: Instruction<C>) -> Self {
1168		use Instruction::*;
1169		match xcm {
1170			WithdrawAsset(assets) => WithdrawAsset(assets),
1171			ReserveAssetDeposited(assets) => ReserveAssetDeposited(assets),
1172			ReceiveTeleportedAsset(assets) => ReceiveTeleportedAsset(assets),
1173			QueryResponse { query_id, response, max_weight, querier } =>
1174				QueryResponse { query_id, response, max_weight, querier },
1175			TransferAsset { assets, beneficiary } => TransferAsset { assets, beneficiary },
1176			TransferReserveAsset { assets, dest, xcm } =>
1177				TransferReserveAsset { assets, dest, xcm },
1178			HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } =>
1179				HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity },
1180			HrmpChannelAccepted { recipient } => HrmpChannelAccepted { recipient },
1181			HrmpChannelClosing { initiator, sender, recipient } =>
1182				HrmpChannelClosing { initiator, sender, recipient },
1183			Transact { origin_kind, call, fallback_max_weight } =>
1184				Transact { origin_kind, call: call.into(), fallback_max_weight },
1185			ReportError(response_info) => ReportError(response_info),
1186			DepositAsset { assets, beneficiary } => DepositAsset { assets, beneficiary },
1187			DepositReserveAsset { assets, dest, xcm } => DepositReserveAsset { assets, dest, xcm },
1188			ExchangeAsset { give, want, maximal } => ExchangeAsset { give, want, maximal },
1189			InitiateReserveWithdraw { assets, reserve, xcm } =>
1190				InitiateReserveWithdraw { assets, reserve, xcm },
1191			InitiateTeleport { assets, dest, xcm } => InitiateTeleport { assets, dest, xcm },
1192			ReportHolding { response_info, assets } => ReportHolding { response_info, assets },
1193			BuyExecution { fees, weight_limit } => BuyExecution { fees, weight_limit },
1194			ClearOrigin => ClearOrigin,
1195			DescendOrigin(who) => DescendOrigin(who),
1196			RefundSurplus => RefundSurplus,
1197			SetErrorHandler(xcm) => SetErrorHandler(xcm.into()),
1198			SetAppendix(xcm) => SetAppendix(xcm.into()),
1199			ClearError => ClearError,
1200			SetHints { hints } => SetHints { hints },
1201			ClaimAsset { assets, ticket } => ClaimAsset { assets, ticket },
1202			Trap(code) => Trap(code),
1203			SubscribeVersion { query_id, max_response_weight } =>
1204				SubscribeVersion { query_id, max_response_weight },
1205			UnsubscribeVersion => UnsubscribeVersion,
1206			BurnAsset(assets) => BurnAsset(assets),
1207			ExpectAsset(assets) => ExpectAsset(assets),
1208			ExpectOrigin(origin) => ExpectOrigin(origin),
1209			ExpectError(error) => ExpectError(error),
1210			ExpectTransactStatus(transact_status) => ExpectTransactStatus(transact_status),
1211			QueryPallet { module_name, response_info } =>
1212				QueryPallet { module_name, response_info },
1213			ExpectPallet { index, name, module_name, crate_major, min_crate_minor } =>
1214				ExpectPallet { index, name, module_name, crate_major, min_crate_minor },
1215			ReportTransactStatus(response_info) => ReportTransactStatus(response_info),
1216			ClearTransactStatus => ClearTransactStatus,
1217			UniversalOrigin(j) => UniversalOrigin(j),
1218			ExportMessage { network, destination, xcm } =>
1219				ExportMessage { network, destination, xcm },
1220			LockAsset { asset, unlocker } => LockAsset { asset, unlocker },
1221			UnlockAsset { asset, target } => UnlockAsset { asset, target },
1222			NoteUnlockable { asset, owner } => NoteUnlockable { asset, owner },
1223			RequestUnlock { asset, locker } => RequestUnlock { asset, locker },
1224			SetFeesMode { jit_withdraw } => SetFeesMode { jit_withdraw },
1225			SetTopic(topic) => SetTopic(topic),
1226			ClearTopic => ClearTopic,
1227			AliasOrigin(location) => AliasOrigin(location),
1228			UnpaidExecution { weight_limit, check_origin } =>
1229				UnpaidExecution { weight_limit, check_origin },
1230			PayFees { asset } => PayFees { asset },
1231			InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm } =>
1232				InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm },
1233			ExecuteWithOrigin { descendant_origin, xcm } =>
1234				ExecuteWithOrigin { descendant_origin, xcm: xcm.into() },
1235		}
1236	}
1237}
1238
1239// TODO: Automate Generation
1240impl<Call, W: XcmWeightInfo<Call>> GetWeight<W> for Instruction<Call> {
1241	fn weight(&self) -> Weight {
1242		use Instruction::*;
1243		match self {
1244			WithdrawAsset(assets) => W::withdraw_asset(assets),
1245			ReserveAssetDeposited(assets) => W::reserve_asset_deposited(assets),
1246			ReceiveTeleportedAsset(assets) => W::receive_teleported_asset(assets),
1247			QueryResponse { query_id, response, max_weight, querier } =>
1248				W::query_response(query_id, response, max_weight, querier),
1249			TransferAsset { assets, beneficiary } => W::transfer_asset(assets, beneficiary),
1250			TransferReserveAsset { assets, dest, xcm } =>
1251				W::transfer_reserve_asset(&assets, dest, xcm),
1252			Transact { origin_kind, fallback_max_weight, call } =>
1253				W::transact(origin_kind, fallback_max_weight, call),
1254			HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } =>
1255				W::hrmp_new_channel_open_request(sender, max_message_size, max_capacity),
1256			HrmpChannelAccepted { recipient } => W::hrmp_channel_accepted(recipient),
1257			HrmpChannelClosing { initiator, sender, recipient } =>
1258				W::hrmp_channel_closing(initiator, sender, recipient),
1259			ClearOrigin => W::clear_origin(),
1260			DescendOrigin(who) => W::descend_origin(who),
1261			ReportError(response_info) => W::report_error(&response_info),
1262			DepositAsset { assets, beneficiary } => W::deposit_asset(assets, beneficiary),
1263			DepositReserveAsset { assets, dest, xcm } =>
1264				W::deposit_reserve_asset(assets, dest, xcm),
1265			ExchangeAsset { give, want, maximal } => W::exchange_asset(give, want, maximal),
1266			InitiateReserveWithdraw { assets, reserve, xcm } =>
1267				W::initiate_reserve_withdraw(assets, reserve, xcm),
1268			InitiateTeleport { assets, dest, xcm } => W::initiate_teleport(assets, dest, xcm),
1269			ReportHolding { response_info, assets } => W::report_holding(&response_info, &assets),
1270			BuyExecution { fees, weight_limit } => W::buy_execution(fees, weight_limit),
1271			RefundSurplus => W::refund_surplus(),
1272			SetErrorHandler(xcm) => W::set_error_handler(xcm),
1273			SetAppendix(xcm) => W::set_appendix(xcm),
1274			ClearError => W::clear_error(),
1275			SetHints { hints } => W::set_hints(hints),
1276			ClaimAsset { assets, ticket } => W::claim_asset(assets, ticket),
1277			Trap(code) => W::trap(code),
1278			SubscribeVersion { query_id, max_response_weight } =>
1279				W::subscribe_version(query_id, max_response_weight),
1280			UnsubscribeVersion => W::unsubscribe_version(),
1281			BurnAsset(assets) => W::burn_asset(assets),
1282			ExpectAsset(assets) => W::expect_asset(assets),
1283			ExpectOrigin(origin) => W::expect_origin(origin),
1284			ExpectError(error) => W::expect_error(error),
1285			ExpectTransactStatus(transact_status) => W::expect_transact_status(transact_status),
1286			QueryPallet { module_name, response_info } =>
1287				W::query_pallet(module_name, response_info),
1288			ExpectPallet { index, name, module_name, crate_major, min_crate_minor } =>
1289				W::expect_pallet(index, name, module_name, crate_major, min_crate_minor),
1290			ReportTransactStatus(response_info) => W::report_transact_status(response_info),
1291			ClearTransactStatus => W::clear_transact_status(),
1292			UniversalOrigin(j) => W::universal_origin(j),
1293			ExportMessage { network, destination, xcm } =>
1294				W::export_message(network, destination, xcm),
1295			LockAsset { asset, unlocker } => W::lock_asset(asset, unlocker),
1296			UnlockAsset { asset, target } => W::unlock_asset(asset, target),
1297			NoteUnlockable { asset, owner } => W::note_unlockable(asset, owner),
1298			RequestUnlock { asset, locker } => W::request_unlock(asset, locker),
1299			SetFeesMode { jit_withdraw } => W::set_fees_mode(jit_withdraw),
1300			SetTopic(topic) => W::set_topic(topic),
1301			ClearTopic => W::clear_topic(),
1302			AliasOrigin(location) => W::alias_origin(location),
1303			UnpaidExecution { weight_limit, check_origin } =>
1304				W::unpaid_execution(weight_limit, check_origin),
1305			PayFees { asset } => W::pay_fees(asset),
1306			InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm } =>
1307				W::initiate_transfer(destination, remote_fees, preserve_origin, assets, remote_xcm),
1308			ExecuteWithOrigin { descendant_origin, xcm } =>
1309				W::execute_with_origin(descendant_origin, xcm),
1310		}
1311	}
1312}
1313
1314pub mod opaque {
1315	/// The basic concrete type of `Xcm`, which doesn't make any assumptions about the
1316	/// format of a call other than it is pre-encoded.
1317	pub type Xcm = super::Xcm<()>;
1318
1319	/// The basic concrete type of `Instruction`, which doesn't make any assumptions about the
1320	/// format of a call other than it is pre-encoded.
1321	pub type Instruction = super::Instruction<()>;
1322}
1323
1324// Convert from a v4 XCM to a v5 XCM
1325impl<Call> TryFrom<OldXcm<Call>> for Xcm<Call> {
1326	type Error = ();
1327	fn try_from(old_xcm: OldXcm<Call>) -> result::Result<Self, Self::Error> {
1328		Ok(Xcm(old_xcm.0.into_iter().map(TryInto::try_into).collect::<result::Result<_, _>>()?))
1329	}
1330}
1331
1332// Convert from a v4 instruction to a v5 instruction
1333impl<Call> TryFrom<OldInstruction<Call>> for Instruction<Call> {
1334	type Error = ();
1335	fn try_from(old_instruction: OldInstruction<Call>) -> result::Result<Self, Self::Error> {
1336		use OldInstruction::*;
1337		Ok(match old_instruction {
1338			WithdrawAsset(assets) => Self::WithdrawAsset(assets.try_into()?),
1339			ReserveAssetDeposited(assets) => Self::ReserveAssetDeposited(assets.try_into()?),
1340			ReceiveTeleportedAsset(assets) => Self::ReceiveTeleportedAsset(assets.try_into()?),
1341			QueryResponse { query_id, response, max_weight, querier: Some(querier) } =>
1342				Self::QueryResponse {
1343					query_id,
1344					querier: querier.try_into()?,
1345					response: response.try_into()?,
1346					max_weight,
1347				},
1348			QueryResponse { query_id, response, max_weight, querier: None } =>
1349				Self::QueryResponse {
1350					query_id,
1351					querier: None,
1352					response: response.try_into()?,
1353					max_weight,
1354				},
1355			TransferAsset { assets, beneficiary } => Self::TransferAsset {
1356				assets: assets.try_into()?,
1357				beneficiary: beneficiary.try_into()?,
1358			},
1359			TransferReserveAsset { assets, dest, xcm } => Self::TransferReserveAsset {
1360				assets: assets.try_into()?,
1361				dest: dest.try_into()?,
1362				xcm: xcm.try_into()?,
1363			},
1364			HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } =>
1365				Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity },
1366			HrmpChannelAccepted { recipient } => Self::HrmpChannelAccepted { recipient },
1367			HrmpChannelClosing { initiator, sender, recipient } =>
1368				Self::HrmpChannelClosing { initiator, sender, recipient },
1369			Transact { origin_kind, require_weight_at_most, call } => Self::Transact {
1370				origin_kind,
1371				call: call.into(),
1372				fallback_max_weight: Some(require_weight_at_most),
1373			},
1374			ReportError(response_info) => Self::ReportError(QueryResponseInfo {
1375				query_id: response_info.query_id,
1376				destination: response_info.destination.try_into().map_err(|_| ())?,
1377				max_weight: response_info.max_weight,
1378			}),
1379			DepositAsset { assets, beneficiary } => {
1380				let beneficiary = beneficiary.try_into()?;
1381				let assets = assets.try_into()?;
1382				Self::DepositAsset { assets, beneficiary }
1383			},
1384			DepositReserveAsset { assets, dest, xcm } => {
1385				let dest = dest.try_into()?;
1386				let xcm = xcm.try_into()?;
1387				let assets = assets.try_into()?;
1388				Self::DepositReserveAsset { assets, dest, xcm }
1389			},
1390			ExchangeAsset { give, want, maximal } => {
1391				let give = give.try_into()?;
1392				let want = want.try_into()?;
1393				Self::ExchangeAsset { give, want, maximal }
1394			},
1395			InitiateReserveWithdraw { assets, reserve, xcm } => {
1396				let assets = assets.try_into()?;
1397				let reserve = reserve.try_into()?;
1398				let xcm = xcm.try_into()?;
1399				Self::InitiateReserveWithdraw { assets, reserve, xcm }
1400			},
1401			InitiateTeleport { assets, dest, xcm } => {
1402				let assets = assets.try_into()?;
1403				let dest = dest.try_into()?;
1404				let xcm = xcm.try_into()?;
1405				Self::InitiateTeleport { assets, dest, xcm }
1406			},
1407			ReportHolding { response_info, assets } => {
1408				let response_info = QueryResponseInfo {
1409					destination: response_info.destination.try_into().map_err(|_| ())?,
1410					query_id: response_info.query_id,
1411					max_weight: response_info.max_weight,
1412				};
1413				Self::ReportHolding { response_info, assets: assets.try_into()? }
1414			},
1415			BuyExecution { fees, weight_limit } => {
1416				let fees = fees.try_into()?;
1417				let weight_limit = weight_limit.into();
1418				Self::BuyExecution { fees, weight_limit }
1419			},
1420			ClearOrigin => Self::ClearOrigin,
1421			DescendOrigin(who) => Self::DescendOrigin(who.try_into()?),
1422			RefundSurplus => Self::RefundSurplus,
1423			SetErrorHandler(xcm) => Self::SetErrorHandler(xcm.try_into()?),
1424			SetAppendix(xcm) => Self::SetAppendix(xcm.try_into()?),
1425			ClearError => Self::ClearError,
1426			ClaimAsset { assets, ticket } => {
1427				let assets = assets.try_into()?;
1428				let ticket = ticket.try_into()?;
1429				Self::ClaimAsset { assets, ticket }
1430			},
1431			Trap(code) => Self::Trap(code),
1432			SubscribeVersion { query_id, max_response_weight } =>
1433				Self::SubscribeVersion { query_id, max_response_weight },
1434			UnsubscribeVersion => Self::UnsubscribeVersion,
1435			BurnAsset(assets) => Self::BurnAsset(assets.try_into()?),
1436			ExpectAsset(assets) => Self::ExpectAsset(assets.try_into()?),
1437			ExpectOrigin(maybe_location) => Self::ExpectOrigin(
1438				maybe_location.map(|location| location.try_into()).transpose().map_err(|_| ())?,
1439			),
1440			ExpectError(maybe_error) => Self::ExpectError(
1441				maybe_error
1442					.map(|(num, old_error)| (num, old_error.try_into()))
1443					.map(|(num, result)| result.map(|inner| (num, inner)))
1444					.transpose()
1445					.map_err(|_| ())?,
1446			),
1447			ExpectTransactStatus(maybe_error_code) => Self::ExpectTransactStatus(maybe_error_code),
1448			QueryPallet { module_name, response_info } => Self::QueryPallet {
1449				module_name,
1450				response_info: response_info.try_into().map_err(|_| ())?,
1451			},
1452			ExpectPallet { index, name, module_name, crate_major, min_crate_minor } =>
1453				Self::ExpectPallet { index, name, module_name, crate_major, min_crate_minor },
1454			ReportTransactStatus(response_info) =>
1455				Self::ReportTransactStatus(response_info.try_into().map_err(|_| ())?),
1456			ClearTransactStatus => Self::ClearTransactStatus,
1457			UniversalOrigin(junction) =>
1458				Self::UniversalOrigin(junction.try_into().map_err(|_| ())?),
1459			ExportMessage { network, destination, xcm } => Self::ExportMessage {
1460				network: network.into(),
1461				destination: destination.try_into().map_err(|_| ())?,
1462				xcm: xcm.try_into().map_err(|_| ())?,
1463			},
1464			LockAsset { asset, unlocker } => Self::LockAsset {
1465				asset: asset.try_into().map_err(|_| ())?,
1466				unlocker: unlocker.try_into().map_err(|_| ())?,
1467			},
1468			UnlockAsset { asset, target } => Self::UnlockAsset {
1469				asset: asset.try_into().map_err(|_| ())?,
1470				target: target.try_into().map_err(|_| ())?,
1471			},
1472			NoteUnlockable { asset, owner } => Self::NoteUnlockable {
1473				asset: asset.try_into().map_err(|_| ())?,
1474				owner: owner.try_into().map_err(|_| ())?,
1475			},
1476			RequestUnlock { asset, locker } => Self::RequestUnlock {
1477				asset: asset.try_into().map_err(|_| ())?,
1478				locker: locker.try_into().map_err(|_| ())?,
1479			},
1480			SetFeesMode { jit_withdraw } => Self::SetFeesMode { jit_withdraw },
1481			SetTopic(topic) => Self::SetTopic(topic),
1482			ClearTopic => Self::ClearTopic,
1483			AliasOrigin(location) => Self::AliasOrigin(location.try_into().map_err(|_| ())?),
1484			UnpaidExecution { weight_limit, check_origin } => Self::UnpaidExecution {
1485				weight_limit,
1486				check_origin: check_origin
1487					.map(|location| location.try_into())
1488					.transpose()
1489					.map_err(|_| ())?,
1490			},
1491		})
1492	}
1493}
1494
1495#[cfg(test)]
1496mod tests {
1497	use super::{prelude::*, *};
1498	use crate::{
1499		v4::{
1500			AssetFilter as OldAssetFilter, Junctions::Here as OldHere, WildAsset as OldWildAsset,
1501		},
1502		MAX_INSTRUCTIONS_TO_DECODE,
1503	};
1504
1505	#[test]
1506	fn basic_roundtrip_works() {
1507		let xcm = Xcm::<()>(vec![TransferAsset {
1508			assets: (Here, 1u128).into(),
1509			beneficiary: Here.into(),
1510		}]);
1511		let old_xcm = OldXcm::<()>(vec![OldInstruction::TransferAsset {
1512			assets: (OldHere, 1u128).into(),
1513			beneficiary: OldHere.into(),
1514		}]);
1515		assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap());
1516		let new_xcm: Xcm<()> = old_xcm.try_into().unwrap();
1517		assert_eq!(new_xcm, xcm);
1518	}
1519
1520	#[test]
1521	fn teleport_roundtrip_works() {
1522		let xcm = Xcm::<()>(vec![
1523			ReceiveTeleportedAsset((Here, 1u128).into()),
1524			ClearOrigin,
1525			DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Here.into() },
1526		]);
1527		let old_xcm: OldXcm<()> = OldXcm::<()>(vec![
1528			OldInstruction::ReceiveTeleportedAsset((OldHere, 1u128).into()),
1529			OldInstruction::ClearOrigin,
1530			OldInstruction::DepositAsset {
1531				assets: crate::v4::AssetFilter::Wild(crate::v4::WildAsset::AllCounted(1)),
1532				beneficiary: OldHere.into(),
1533			},
1534		]);
1535		assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap());
1536		let new_xcm: Xcm<()> = old_xcm.try_into().unwrap();
1537		assert_eq!(new_xcm, xcm);
1538	}
1539
1540	#[test]
1541	fn reserve_deposit_roundtrip_works() {
1542		let xcm = Xcm::<()>(vec![
1543			ReserveAssetDeposited((Here, 1u128).into()),
1544			ClearOrigin,
1545			BuyExecution {
1546				fees: (Here, 1u128).into(),
1547				weight_limit: Some(Weight::from_parts(1, 1)).into(),
1548			},
1549			DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Here.into() },
1550		]);
1551		let old_xcm = OldXcm::<()>(vec![
1552			OldInstruction::ReserveAssetDeposited((OldHere, 1u128).into()),
1553			OldInstruction::ClearOrigin,
1554			OldInstruction::BuyExecution {
1555				fees: (OldHere, 1u128).into(),
1556				weight_limit: WeightLimit::Limited(Weight::from_parts(1, 1)),
1557			},
1558			OldInstruction::DepositAsset {
1559				assets: crate::v4::AssetFilter::Wild(crate::v4::WildAsset::AllCounted(1)),
1560				beneficiary: OldHere.into(),
1561			},
1562		]);
1563		assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap());
1564		let new_xcm: Xcm<()> = old_xcm.try_into().unwrap();
1565		assert_eq!(new_xcm, xcm);
1566	}
1567
1568	#[test]
1569	fn deposit_asset_roundtrip_works() {
1570		let xcm = Xcm::<()>(vec![
1571			WithdrawAsset((Here, 1u128).into()),
1572			DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Here.into() },
1573		]);
1574		let old_xcm = OldXcm::<()>(vec![
1575			OldInstruction::WithdrawAsset((OldHere, 1u128).into()),
1576			OldInstruction::DepositAsset {
1577				assets: OldAssetFilter::Wild(OldWildAsset::AllCounted(1)),
1578				beneficiary: OldHere.into(),
1579			},
1580		]);
1581		assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap());
1582		let new_xcm: Xcm<()> = old_xcm.try_into().unwrap();
1583		assert_eq!(new_xcm, xcm);
1584	}
1585
1586	#[test]
1587	fn deposit_reserve_asset_roundtrip_works() {
1588		let xcm = Xcm::<()>(vec![
1589			WithdrawAsset((Here, 1u128).into()),
1590			DepositReserveAsset {
1591				assets: Wild(AllCounted(1)),
1592				dest: Here.into(),
1593				xcm: Xcm::<()>(vec![]),
1594			},
1595		]);
1596		let old_xcm = OldXcm::<()>(vec![
1597			OldInstruction::WithdrawAsset((OldHere, 1u128).into()),
1598			OldInstruction::DepositReserveAsset {
1599				assets: OldAssetFilter::Wild(OldWildAsset::AllCounted(1)),
1600				dest: OldHere.into(),
1601				xcm: OldXcm::<()>(vec![]),
1602			},
1603		]);
1604		assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap());
1605		let new_xcm: Xcm<()> = old_xcm.try_into().unwrap();
1606		assert_eq!(new_xcm, xcm);
1607	}
1608
1609	#[test]
1610	fn transact_roundtrip_works() {
1611		// We can convert as long as there's a fallback.
1612		let xcm = Xcm::<()>(vec![
1613			WithdrawAsset((Here, 1u128).into()),
1614			Transact {
1615				origin_kind: OriginKind::SovereignAccount,
1616				call: vec![200, 200, 200].into(),
1617				fallback_max_weight: Some(Weight::from_parts(1_000_000, 1_024)),
1618			},
1619		]);
1620		let old_xcm = OldXcm::<()>(vec![
1621			OldInstruction::WithdrawAsset((OldHere, 1u128).into()),
1622			OldInstruction::Transact {
1623				origin_kind: OriginKind::SovereignAccount,
1624				call: vec![200, 200, 200].into(),
1625				require_weight_at_most: Weight::from_parts(1_000_000, 1_024),
1626			},
1627		]);
1628		assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap());
1629		let new_xcm: Xcm<()> = old_xcm.try_into().unwrap();
1630		assert_eq!(new_xcm, xcm);
1631
1632		// If we have no fallback the resulting message won't know the weight.
1633		let xcm_without_fallback = Xcm::<()>(vec![
1634			WithdrawAsset((Here, 1u128).into()),
1635			Transact {
1636				origin_kind: OriginKind::SovereignAccount,
1637				call: vec![200, 200, 200].into(),
1638				fallback_max_weight: None,
1639			},
1640		]);
1641		let old_xcm = OldXcm::<()>(vec![
1642			OldInstruction::WithdrawAsset((OldHere, 1u128).into()),
1643			OldInstruction::Transact {
1644				origin_kind: OriginKind::SovereignAccount,
1645				call: vec![200, 200, 200].into(),
1646				require_weight_at_most: Weight::MAX,
1647			},
1648		]);
1649		assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm_without_fallback.clone()).unwrap());
1650		let new_xcm: Xcm<()> = old_xcm.try_into().unwrap();
1651		let xcm_with_max_weight_fallback = Xcm::<()>(vec![
1652			WithdrawAsset((Here, 1u128).into()),
1653			Transact {
1654				origin_kind: OriginKind::SovereignAccount,
1655				call: vec![200, 200, 200].into(),
1656				fallback_max_weight: Some(Weight::MAX),
1657			},
1658		]);
1659		assert_eq!(new_xcm, xcm_with_max_weight_fallback);
1660	}
1661
1662	#[test]
1663	fn decoding_respects_limit() {
1664		let max_xcm = Xcm::<()>(vec![ClearOrigin; MAX_INSTRUCTIONS_TO_DECODE as usize]);
1665		let encoded = max_xcm.encode();
1666		assert!(Xcm::<()>::decode(&mut &encoded[..]).is_ok());
1667
1668		let big_xcm = Xcm::<()>(vec![ClearOrigin; MAX_INSTRUCTIONS_TO_DECODE as usize + 1]);
1669		let encoded = big_xcm.encode();
1670		assert!(Xcm::<()>::decode(&mut &encoded[..]).is_err());
1671
1672		let nested_xcm = Xcm::<()>(vec![
1673			DepositReserveAsset {
1674				assets: All.into(),
1675				dest: Here.into(),
1676				xcm: max_xcm,
1677			};
1678			(MAX_INSTRUCTIONS_TO_DECODE / 2) as usize
1679		]);
1680		let encoded = nested_xcm.encode();
1681		assert!(Xcm::<()>::decode(&mut &encoded[..]).is_err());
1682
1683		let even_more_nested_xcm = Xcm::<()>(vec![SetAppendix(nested_xcm); 64]);
1684		let encoded = even_more_nested_xcm.encode();
1685		assert_eq!(encoded.len(), 342530);
1686		// This should not decode since the limit is 100
1687		assert_eq!(MAX_INSTRUCTIONS_TO_DECODE, 100, "precondition");
1688		assert!(Xcm::<()>::decode(&mut &encoded[..]).is_err());
1689	}
1690}