referrerpolicy=no-referrer-when-downgrade

emulated_integration_tests_common/
xcm_helpers.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// SPDX-License-Identifier: Apache-2.0
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// 	http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16// Cumulus
17use parachains_common::AccountId;
18
19// Polkadot
20use sp_core::H256;
21use xcm::{prelude::*, DoubleEncoded};
22use xcm_emulator::Chain;
23
24use crate::impls::{bx, Encode};
25use frame_support::dispatch::{DispatchResultWithPostInfo, PostDispatchInfo};
26use sp_runtime::traits::{Dispatchable, Hash};
27use xcm::{VersionedLocation, VersionedXcm};
28
29/// Helper method to build a XCM with a `Transact` instruction and paying for its execution
30pub fn xcm_transact_paid_execution(
31	call: DoubleEncoded<()>,
32	origin_kind: OriginKind,
33	fees: Asset,
34	beneficiary: AccountId,
35) -> VersionedXcm<()> {
36	let weight_limit = WeightLimit::Unlimited;
37
38	VersionedXcm::from(Xcm(vec![
39		WithdrawAsset(fees.clone().into()),
40		BuyExecution { fees, weight_limit },
41		Transact { origin_kind, call, fallback_max_weight: None },
42		RefundSurplus,
43		DepositAsset {
44			assets: All.into(),
45			beneficiary: Location {
46				parents: 0,
47				interior: [AccountId32 { network: None, id: beneficiary.into() }].into(),
48			},
49		},
50	]))
51}
52
53/// Helper method to build a XCM with a `Transact` instruction without paying for its execution
54pub fn xcm_transact_unpaid_execution(
55	call: DoubleEncoded<()>,
56	origin_kind: OriginKind,
57) -> VersionedXcm<()> {
58	let weight_limit = WeightLimit::Unlimited;
59	let check_origin = None;
60
61	VersionedXcm::from(Xcm(vec![
62		UnpaidExecution { weight_limit, check_origin },
63		Transact { origin_kind, call, fallback_max_weight: None },
64	]))
65}
66
67/// Helper method to get the non-fee asset used in multiple assets transfer
68pub fn non_fee_asset(assets: &Assets, fee_idx: usize) -> Option<(Location, u128)> {
69	let asset = assets.inner().into_iter().enumerate().find(|a| a.0 != fee_idx)?.1.clone();
70	let asset_amount = match asset.fun {
71		Fungible(amount) => amount,
72		_ => return None,
73	};
74	Some((asset.id.0, asset_amount))
75}
76
77/// Helper method to get the fee asset used in multiple assets transfer
78pub fn fee_asset(assets: &Assets, fee_idx: usize) -> Option<(Location, u128)> {
79	let asset = assets.get(fee_idx)?;
80	let asset_amount = match asset.fun {
81		Fungible(amount) => amount,
82		_ => return None,
83	};
84	Some((asset.id.0.clone(), asset_amount))
85}
86
87pub fn get_amount_from_versioned_assets(assets: VersionedAssets) -> u128 {
88	let latest_assets: Assets = assets.try_into().unwrap();
89	let Fungible(amount) = latest_assets.inner()[0].fun else {
90		unreachable!("asset is non-fungible");
91	};
92	amount
93}
94
95fn to_mq_processed_id<C: Chain>(event: C::RuntimeEvent) -> Option<H256>
96where
97	<C as Chain>::Runtime: pallet_message_queue::Config,
98	C::RuntimeEvent: TryInto<pallet_message_queue::Event<<C as Chain>::Runtime>>,
99{
100	if let Ok(pallet_message_queue::Event::Processed { id, .. }) = event.try_into() {
101		Some(id)
102	} else {
103		None
104	}
105}
106
107/// Helper method to find all `Event::Processed` IDs from the chain's events.
108pub fn find_all_mq_processed_ids<C: Chain>() -> Vec<H256>
109where
110	<C as Chain>::Runtime: pallet_message_queue::Config,
111	C::RuntimeEvent: TryInto<pallet_message_queue::Event<<C as Chain>::Runtime>>,
112{
113	C::events().into_iter().filter_map(to_mq_processed_id::<C>).collect()
114}
115
116/// Helper method to find the ID of the first `Event::Processed` event in the chain's events.
117pub fn find_mq_processed_id<C: Chain>() -> Option<H256>
118where
119	<C as Chain>::Runtime: pallet_message_queue::Config,
120	C::RuntimeEvent: TryInto<pallet_message_queue::Event<<C as Chain>::Runtime>>,
121{
122	C::events().into_iter().find_map(to_mq_processed_id::<C>)
123}
124
125/// Helper method to find the message ID of the first `Event::Sent` event in the chain's events.
126pub fn find_xcm_sent_message_id<
127	C: Chain<RuntimeEvent = <<C as Chain>::Runtime as pallet_xcm::Config>::RuntimeEvent>,
128>() -> Option<XcmHash>
129where
130	C::Runtime: pallet_xcm::Config,
131	C::RuntimeEvent: TryInto<pallet_xcm::Event<C::Runtime>>,
132{
133	pallet_xcm::xcm_helpers::find_xcm_sent_message_id::<<C as Chain>::Runtime>(C::events())
134}
135
136/// Wraps a runtime call in a whitelist preimage call and dispatches it
137pub fn dispatch_whitelisted_call_with_preimage<T>(
138	call: T::RuntimeCall,
139	origin: T::RuntimeOrigin,
140) -> DispatchResultWithPostInfo
141where
142	T: Chain,
143	T::Runtime: pallet_whitelist::Config,
144	T::RuntimeCall: From<pallet_whitelist::Call<T::Runtime>>
145		+ Into<<T::Runtime as pallet_whitelist::Config>::RuntimeCall>
146		+ Dispatchable<RuntimeOrigin = T::RuntimeOrigin, PostInfo = PostDispatchInfo>,
147{
148	T::execute_with(|| {
149		let whitelist_call: T::RuntimeCall =
150			pallet_whitelist::Call::<T::Runtime>::dispatch_whitelisted_call_with_preimage {
151				call: Box::new(call.into()),
152			}
153			.into();
154		whitelist_call.dispatch(origin)
155	})
156}
157
158/// Builds a `pallet_xcm::send` call to authorize an upgrade at the provided location,
159/// wrapped in an unpaid XCM `Transact` with `OriginKind::Superuser`.
160pub fn build_xcm_send_authorize_upgrade_call<T, D>(
161	location: Location,
162	code_hash: &H256,
163	fallback_max_weight: Option<Weight>,
164) -> T::RuntimeCall
165where
166	T: Chain,
167	T::Runtime: pallet_xcm::Config,
168	T::RuntimeCall: Encode + From<pallet_xcm::Call<T::Runtime>>,
169	D: Chain,
170	D::Runtime: frame_system::Config<Hash = H256>,
171	D::RuntimeCall: Encode + From<frame_system::Call<D::Runtime>>,
172{
173	let transact_call: D::RuntimeCall =
174		frame_system::Call::authorize_upgrade { code_hash: *code_hash }.into();
175
176	let call: T::RuntimeCall = pallet_xcm::Call::send {
177		dest: bx!(VersionedLocation::from(location)),
178		message: bx!(VersionedXcm::from(Xcm(vec![
179			UnpaidExecution { weight_limit: Unlimited, check_origin: None },
180			Transact {
181				origin_kind: OriginKind::Superuser,
182				fallback_max_weight,
183				call: transact_call.encode().into(),
184			}
185		]))),
186	}
187	.into();
188	call
189}
190
191/// Encodes a runtime call and returns its H256 hash
192pub fn call_hash_of<T>(call: &T::RuntimeCall) -> H256
193where
194	T: Chain,
195	T::Runtime: frame_system::Config<Hash = H256>,
196	T::RuntimeCall: Encode,
197{
198	<T::Runtime as frame_system::Config>::Hashing::hash_of(&call)
199}