referrerpolicy=no-referrer-when-downgrade

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