referrerpolicy=no-referrer-when-downgrade

emulated_integration_tests_common/
macros.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
16pub use paste;
17
18// Substrate
19pub use frame_support::{pallet_prelude::Weight, weights::WeightToFee};
20pub use pallet_asset_conversion;
21pub use pallet_assets;
22pub use pallet_balances;
23pub use pallet_message_queue;
24pub use pallet_whitelist;
25pub use pallet_xcm;
26
27pub use frame_support::{
28	assert_ok,
29	storage::{with_transaction_unchecked, TransactionOutcome},
30};
31
32// Polkadot
33pub use polkadot_runtime_parachains::dmp::Pallet as Dmp;
34pub use xcm::{
35	latest::AssetTransferFilter,
36	prelude::{
37		AliasOrigin, All, AllCounted, Asset, AssetId, Assets, BuyExecution, DepositAsset,
38		ExpectTransactStatus, Fungible, GeneralIndex, Here, InitiateTransfer, Junction, Location,
39		MaybeErrorCode, OriginKind, Outcome, PalletInstance, Parachain, Parent, PayFees,
40		RefundSurplus, Transact, Unlimited, VersionedAssetId, VersionedAssets, VersionedLocation,
41		VersionedXcm, WeightLimit, Wild, WithdrawAsset, Xcm, XcmContext, XCM_VERSION,
42	},
43};
44
45pub use xcm_executor::traits::{DropAssets, TransferType};
46
47// Cumulus
48pub use asset_test_utils;
49pub use cumulus_pallet_xcmp_queue;
50pub use parachains_common::AccountId;
51pub use xcm_emulator::{
52	assert_expected_events, Chain, Parachain as Para, RelayChain, TestArgs, TestContext, TestExt,
53};
54
55pub use frame_support::{
56	dispatch::{GetDispatchInfo, RawOrigin},
57	BoundedVec,
58};
59pub use xcm_runtime_apis::{
60	dry_run::runtime_decl_for_dry_run_api::DryRunApiV2,
61	fees::{runtime_decl_for_xcm_payment_api::XcmPaymentApiV2, Error as XcmPaymentApiError},
62};
63
64pub use frame_support::traits::{fungible::Mutate, fungibles::Inspect, Currency};
65pub use sp_runtime::{traits::Dispatchable, AccountId32};
66
67pub use crate::{create_foreign_pool_with_native_on, ASSETS_PALLET_ID, USDT_ID};
68
69#[macro_export]
70macro_rules! test_parachain_is_trusted_teleporter {
71	( $sender_para:ty, vec![$( $receiver_para:ty ),+], ($assets:expr, $amount:expr), $xcm_call:ident ) => {
72		$crate::macros::paste::paste! {
73			// init Origin variables
74			let sender = [<$sender_para Sender>]::get();
75			let mut para_sender_balance_before =
76				<$sender_para as $crate::macros::Chain>::account_data_of(sender.clone()).free;
77			let origin = <$sender_para as $crate::macros::Chain>::RuntimeOrigin::signed(sender.clone());
78			let fee_asset_item = 0;
79			let weight_limit = $crate::macros::WeightLimit::Unlimited;
80
81			$(
82				{
83					// init Destination variables
84					let receiver = [<$receiver_para Receiver>]::get();
85					let para_receiver_balance_before =
86						<$receiver_para as $crate::macros::Chain>::account_data_of(receiver.clone()).free;
87					let para_destination =
88						<$sender_para as $crate::macros::Para>::sibling_location_of(
89							<$receiver_para as $crate::macros::Para>::para_id());
90					let beneficiary: $crate::macros::Location =
91						$crate::macros::Junction::AccountId32 { network: None, id: receiver.clone().into() }.into();
92
93					// Dry-run first.
94					let call = <$sender_para as $crate::macros::Chain>::RuntimeCall::PolkadotXcm(
95						$crate::macros::pallet_xcm::Call::$xcm_call {
96						dest: Box::new(para_destination.clone().into()),
97						beneficiary: Box::new(beneficiary.clone().into()),
98						assets: Box::new($assets.clone().into()),
99						fee_asset_item: fee_asset_item,
100						weight_limit: weight_limit.clone(),
101					});
102
103					// assume up to 90% of max weight
104					let max_weight_with_margin_for_error = ($crate::macros::Weight::MAX.ref_time() / 100) * 90;
105					assert!(<_ as $crate::macros::GetDispatchInfo>::get_dispatch_info(&call)
106						.call_weight.ref_time() < max_weight_with_margin_for_error);
107
108					let mut delivery_fees_amount = 0;
109					let mut remote_message = $crate::macros::VersionedXcm::from($crate::macros::Xcm(Vec::new()));
110					<$sender_para as $crate::macros::TestExt>::execute_with(|| {
111						type Runtime = <$sender_para as $crate::macros::Chain>::Runtime;
112						type OriginCaller = <$sender_para as $crate::macros::Chain>::OriginCaller;
113
114						let origin = OriginCaller::system($crate::macros::RawOrigin::Signed(sender.clone()));
115						let result = <Runtime as $crate::macros::DryRunApiV2<_,_,_,_>>::dry_run_call(origin, call.clone(),
116							$crate::macros::XCM_VERSION).unwrap();
117
118
119						// We filter the result to get only the messages we are interested in.
120						let (destination_to_query, messages_to_query) = &result
121							.forwarded_xcms
122							.iter()
123							.find(|(destination, _)| {
124								*destination == $crate::macros::VersionedLocation::from($crate::macros::Location::new(1,
125									[$crate::macros::Parachain(<$receiver_para as $crate::macros::Para>::para_id().into())]))
126							})
127							.unwrap();
128						assert_eq!(messages_to_query.len(), 1);
129						remote_message = messages_to_query[0].clone();
130						// The native asset of every system chain.
131						// We want to get the delivery fees in this asset.
132						let asset_id_for_delivery_fees = VersionedAssetId::from(Location::new(1, []));
133						let delivery_fees =
134							<Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_delivery_fees(
135								destination_to_query.clone(),
136								remote_message.clone(),
137								asset_id_for_delivery_fees
138							).unwrap();
139						let latest_delivery_fees: $crate::macros::Assets = delivery_fees.clone().try_into().unwrap();
140						let $crate::macros::Fungible(inner_delivery_fees_amount) = latest_delivery_fees.inner()[0].fun else {
141							unreachable!("asset is non-fungible");
142						};
143						delivery_fees_amount = inner_delivery_fees_amount;
144					});
145
146					let receiver_total_issuance_before = <$receiver_para as $crate::macros::TestExt>::execute_with(|| {
147						<<$receiver_para as [<$receiver_para Pallet>]>::Balances
148							as $crate::macros::Currency<_>>::total_issuance()
149					});
150					// Send XCM message from Origin Parachain
151					<$sender_para as $crate::macros::TestExt>::execute_with(|| {
152						let total_issuance_source_of_truth = <$sender_para as $crate::macros::Chain>::native_total_issuance_source_of_truth();
153						let total_issuance_before = <<$sender_para as [<$sender_para Pallet>]>::Balances
154							as $crate::macros::Currency<_>>::total_issuance();
155						let origin = <$sender_para as $crate::macros::Chain>::RuntimeOrigin::signed(sender.clone());
156						$crate::macros::assert_ok!(<_ as $crate::macros::Dispatchable>::dispatch(call, origin));
157						let total_issuance_after = <<$sender_para as [<$sender_para Pallet>]>::Balances
158							as $crate::macros::Currency<_>>::total_issuance();
159
160						type RuntimeEvent = <$sender_para as $crate::macros::Chain>::RuntimeEvent;
161
162						$crate::macros::assert_expected_events!(
163							$sender_para,
164							vec![
165								RuntimeEvent::PolkadotXcm(
166									$crate::macros::pallet_xcm::Event::Attempted { outcome: $crate::macros::Outcome::Complete { .. } }
167								) => {},
168								RuntimeEvent::XcmpQueue(
169									$crate::macros::cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. }
170								) => {},
171								RuntimeEvent::Balances(
172									$crate::macros::pallet_balances::Event::Withdraw { who, .. }
173								) => {
174									who: *who == sender,
175								},
176							]
177						);
178						if total_issuance_source_of_truth {
179							assert_eq!(
180								total_issuance_after, total_issuance_before,
181								"Unexpected change in sender native token total issuance source of truth"
182							);
183						} else {
184							assert_eq!(
185								total_issuance_after, total_issuance_before - $amount,
186								"Native token total issuance should have decreased on sender"
187							);
188						}
189					});
190
191					// Receive XCM message in Destination Parachain
192					<$receiver_para as $crate::macros::TestExt>::execute_with(|| {
193						type RuntimeEvent = <$receiver_para as $crate::macros::Chain>::RuntimeEvent;
194
195						$crate::macros::assert_expected_events!(
196							$receiver_para,
197							vec![
198								RuntimeEvent::Balances(
199									$crate::macros::pallet_balances::Event::Deposit { who, .. }
200								) => {
201									who: *who == receiver,
202								},
203								RuntimeEvent::MessageQueue(
204									$crate::macros::pallet_message_queue::Event::Processed { success: true, .. }
205								) => {},
206							]
207						);
208						let receiver_total_issuance_after = <<$receiver_para as [<$receiver_para Pallet>]>::Balances
209							as $crate::macros::Currency<_>>::total_issuance();
210						if <$receiver_para as $crate::macros::Chain>::native_total_issuance_source_of_truth() {
211							assert_eq!(
212								receiver_total_issuance_after, receiver_total_issuance_before,
213								"Unexpected change in receiver native token total issuance source of truth"
214							);
215						} else {
216							assert!(
217								receiver_total_issuance_after > receiver_total_issuance_before,
218								"Native token total issuance should have increased on receiver"
219							);
220						}
221					});
222
223					// Check if balances are updated accordingly in Origin and Destination Parachains
224					let para_sender_balance_after =
225						<$sender_para as $crate::macros::Chain>::account_data_of(sender.clone()).free;
226					let para_receiver_balance_after =
227						<$receiver_para as $crate::macros::Chain>::account_data_of(receiver.clone()).free;
228
229					assert_eq!(para_sender_balance_before - $amount - delivery_fees_amount, para_sender_balance_after);
230					assert!(para_receiver_balance_after > para_receiver_balance_before);
231
232					// Update sender balance
233					para_sender_balance_before = <$sender_para as $crate::macros::Chain>::account_data_of(sender.clone()).free;
234				}
235			)+
236		}
237	};
238}
239
240#[macro_export]
241macro_rules! test_relay_is_trusted_teleporter {
242	( $sender_relay:ty, vec![$( $receiver_para:ty ),+], ($assets:expr, $amount:expr), $xcm_call:ident ) => {
243		$crate::macros::paste::paste! {
244			// init Origin variables
245			let sender = [<$sender_relay Sender>]::get();
246			let mut relay_sender_balance_before =
247				<$sender_relay as $crate::macros::Chain>::account_data_of(sender.clone()).free;
248			let fee_asset_item = 0;
249			let weight_limit = $crate::macros::WeightLimit::Unlimited;
250
251			$(
252				{
253					// init Destination variables
254					let receiver = [<$receiver_para Receiver>]::get();
255					let para_receiver_balance_before =
256						<$receiver_para as $crate::macros::Chain>::account_data_of(receiver.clone()).free;
257					let para_destination =
258						<$sender_relay as $crate::macros::RelayChain>::child_location_of(
259							<$receiver_para as $crate::macros::Para>::para_id());
260					let beneficiary: $crate::macros::Location =
261						$crate::macros::Junction::AccountId32 { network: None, id: receiver.clone().into() }.into();
262
263					// Dry-run first.
264					let call = <$sender_relay as $crate::macros::Chain>::RuntimeCall::XcmPallet(
265						$crate::macros::pallet_xcm::Call::$xcm_call {
266						dest: Box::new(para_destination.clone().into()),
267						beneficiary: Box::new(beneficiary.clone().into()),
268						assets: Box::new($assets.clone().into()),
269						fee_asset_item: fee_asset_item,
270						weight_limit: weight_limit.clone(),
271					});
272
273					// verify sane weight for a call
274					// assume up to 90% of max weight
275					let max_weight_with_margin_for_error = ($crate::macros::Weight::MAX.ref_time() / 100) * 90;
276					assert!(<_ as $crate::macros::GetDispatchInfo>::get_dispatch_info(&call)
277						.call_weight.ref_time() < max_weight_with_margin_for_error);
278
279					let mut delivery_fees_amount = 0;
280					let mut remote_message = $crate::macros::VersionedXcm::from($crate::macros::Xcm(Vec::new()));
281					<$sender_relay as $crate::macros::TestExt>::execute_with(|| {
282						$crate::macros::Dmp::<<$sender_relay as $crate::macros::Chain>::Runtime>::make_parachain_reachable(
283							<$receiver_para as $crate::macros::Para>::para_id());
284						type Runtime = <$sender_relay as $crate::macros::Chain>::Runtime;
285						type OriginCaller = <$sender_relay as $crate::macros::Chain>::OriginCaller;
286
287						let origin = OriginCaller::system($crate::macros::RawOrigin::Signed(sender.clone()));
288						let result = <Runtime as $crate::macros::DryRunApiV2<_,_,_,_>>::dry_run_call(origin, call.clone(),
289							$crate::macros::XCM_VERSION).unwrap();
290						// We filter the result to get only the messages we are interested in.
291						let (destination_to_query, messages_to_query) = &result
292							.forwarded_xcms
293							.iter()
294							.find(|(destination, _)| {
295								*destination == $crate::macros::VersionedLocation::from($crate::macros::Location::new(0,
296									[$crate::macros::Parachain(<$receiver_para as $crate::macros::Para>::para_id().into())]))
297							})
298							.unwrap();
299						assert_eq!(messages_to_query.len(), 1);
300						remote_message = messages_to_query[0].clone();
301						// The native asset of every system chain.
302						// We want to get the delivery fees in this asset.
303						let asset_id_for_delivery_fees = VersionedAssetId::from(Location::new(0, []));
304						let delivery_fees =
305							<Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_delivery_fees(
306								destination_to_query.clone(),
307								remote_message.clone(),
308								asset_id_for_delivery_fees
309							).unwrap();
310						let latest_delivery_fees: $crate::macros::Assets = delivery_fees.clone().try_into().unwrap();
311						let $crate::macros::Fungible(inner_delivery_fees_amount) = latest_delivery_fees.inner()[0].fun else {
312							unreachable!("asset is non-fungible");
313						};
314						delivery_fees_amount = inner_delivery_fees_amount;
315					});
316
317					// Reset to send actual message.
318					<$sender_relay as $crate::macros::TestExt>::reset_ext();
319					<$receiver_para as $crate::macros::TestExt>::reset_ext();
320
321					// Send XCM message from Relay.
322					<$sender_relay as $crate::macros::TestExt>::execute_with(|| {
323						$crate::macros::Dmp::<<$sender_relay as $crate::macros::Chain>::Runtime>::make_parachain_reachable(
324							<$receiver_para as $crate::macros::Para>::para_id());
325						let origin = <$sender_relay as $crate::macros::Chain>::RuntimeOrigin::signed(sender.clone());
326						$crate::macros::assert_ok!(<_ as $crate::macros::Dispatchable>::dispatch(call, origin));
327
328						type RuntimeEvent = <$sender_relay as $crate::macros::Chain>::RuntimeEvent;
329
330						$crate::macros::assert_expected_events!(
331							$sender_relay,
332							vec![
333								RuntimeEvent::XcmPallet(
334									$crate::macros::pallet_xcm::Event::Attempted { outcome: $crate::macros::Outcome::Complete { .. } }
335								) => {},
336								RuntimeEvent::Balances(
337									$crate::macros::pallet_balances::Event::Withdraw { who, .. }
338								) => {
339									who: *who == sender,
340								},
341								RuntimeEvent::XcmPallet(
342									$crate::macros::pallet_xcm::Event::Sent { .. }
343								) => {},
344							]
345						);
346					});
347
348					// Receive XCM message in Destination Parachain
349					<$receiver_para as $crate::macros::TestExt>::execute_with(|| {
350						type RuntimeEvent = <$receiver_para as $crate::macros::Chain>::RuntimeEvent;
351
352						$crate::macros::assert_expected_events!(
353							$receiver_para,
354							vec![
355								RuntimeEvent::Balances(
356									$crate::macros::pallet_balances::Event::Deposit { who, .. }
357								) => {
358									who: *who == receiver,
359								},
360								RuntimeEvent::MessageQueue(
361									$crate::macros::pallet_message_queue::Event::Processed { success: true, .. }
362								) => {},
363							]
364						);
365					});
366
367					// Check if balances are updated accordingly in Origin and Parachain
368					let relay_sender_balance_after =
369						<$sender_relay as $crate::macros::Chain>::account_data_of(sender.clone()).free;
370					let para_receiver_balance_after =
371						<$receiver_para as $crate::macros::Chain>::account_data_of(receiver.clone()).free;
372
373					assert_eq!(relay_sender_balance_before - $amount - delivery_fees_amount, relay_sender_balance_after);
374					assert!(para_receiver_balance_after > para_receiver_balance_before);
375
376					// Update sender balance
377					relay_sender_balance_before = <$sender_relay as $crate::macros::Chain>::account_data_of(sender.clone()).free;
378				}
379			)+
380		}
381	};
382}
383
384#[macro_export]
385macro_rules! test_parachain_is_trusted_teleporter_for_relay {
386	( $sender_para:ty, $receiver_relay:ty, $amount:expr, $xcm_call:ident ) => {
387		$crate::macros::paste::paste! {
388			// init Origin variables
389			let sender = [<$sender_para Sender>]::get();
390			// Mint assets to `$sender_para` to succeed with teleport.
391			<$sender_para as $crate::macros::TestExt>::execute_with(|| {
392				$crate::macros::assert_ok!(<<$sender_para as [<$sender_para Pallet>]>::Balances
393					as $crate::macros::Mutate<_>>::mint_into(&sender, $amount + 10_000_000_000));
394
395			});
396			let mut para_sender_balance_before =
397				<$sender_para as $crate::macros::Chain>::account_data_of(sender.clone()).free;
398			let origin = <$sender_para as $crate::macros::Chain>::RuntimeOrigin::signed(sender.clone());
399			let assets: $crate::macros::Assets = ($crate::macros::Parent, $amount).into();
400			let fee_asset_item = 0;
401			let weight_limit = $crate::macros::WeightLimit::Unlimited;
402
403			// We need to mint funds into the checking account of `$receiver_relay`
404			// for it to accept a teleport from `$sender_para`.
405			// Else we'd get a `NotWithdrawable` error since it tries to reduce the check account balance, which
406			// would be 0.
407			<$receiver_relay as $crate::macros::TestExt>::execute_with(|| {
408				let check_account = <$receiver_relay as [<$receiver_relay Pallet>]>::XcmPallet::check_account();
409				$crate::macros::assert_ok!(<<$receiver_relay as [<$receiver_relay Pallet>]>::Balances
410					as $crate::macros::Mutate<_>>::mint_into(&check_account, $amount));
411			});
412
413			// Init destination variables.
414			let receiver = [<$receiver_relay Receiver>]::get();
415			let relay_receiver_balance_before =
416				<$receiver_relay as $crate::macros::Chain>::account_data_of(receiver.clone()).free;
417			let relay_destination: $crate::macros::Location = $crate::macros::Parent.into();
418			let beneficiary: $crate::macros::Location =
419				$crate::macros::Junction::AccountId32 { network: None, id: receiver.clone().into() }.into();
420
421			// Dry-run first.
422			let call = <$sender_para as $crate::macros::Chain>::RuntimeCall::PolkadotXcm($crate::macros::pallet_xcm::Call::$xcm_call {
423				dest: Box::new(relay_destination.clone().into()),
424				beneficiary: Box::new(beneficiary.clone().into()),
425				assets: Box::new(assets.clone().into()),
426				fee_asset_item: fee_asset_item,
427				weight_limit: weight_limit.clone(),
428			});
429
430			// verify sane weight for a call
431			// assume up to 90% of max weight
432			let max_weight_with_margin_for_error = ($crate::macros::Weight::MAX.ref_time() / 100) * 90;
433			assert!(<_ as $crate::macros::GetDispatchInfo>::get_dispatch_info(&call)
434				.call_weight.ref_time() < max_weight_with_margin_for_error);
435
436			// These will be filled in the closure.
437			let mut delivery_fees_amount = 0;
438			let mut remote_message = $crate::macros::VersionedXcm::from($crate::macros::Xcm(Vec::new()));
439			<$sender_para as $crate::macros::TestExt>::execute_with(|| {
440				type Runtime = <$sender_para as $crate::macros::Chain>::Runtime;
441				type OriginCaller = <$sender_para as $crate::macros::Chain>::OriginCaller;
442
443				let origin = OriginCaller::system($crate::macros::RawOrigin::Signed(sender.clone()));
444				let result = <Runtime as $crate::macros::DryRunApiV2<_,_,_,_>>::dry_run_call(origin, call.clone(),
445					$crate::macros::XCM_VERSION).unwrap();
446				// We filter the result to get only the messages we are interested in.
447				let (destination_to_query, messages_to_query) = &result
448					.forwarded_xcms
449					.iter()
450					.find(|(destination, _)| {
451						*destination == $crate::macros::VersionedLocation::from($crate::macros::Location::parent())
452					})
453					.unwrap();
454				assert_eq!(messages_to_query.len(), 1);
455				remote_message = messages_to_query[0].clone();
456				// The native asset of every system chain.
457				// We want to get the delivery fees in this asset.
458				let asset_id_for_delivery_fees = VersionedAssetId::from(Location::parent());
459				let delivery_fees =
460					<Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_delivery_fees(
461						destination_to_query.clone(),
462						remote_message.clone(),
463						asset_id_for_delivery_fees
464					).unwrap();
465				let latest_delivery_fees: $crate::macros::Assets = delivery_fees.clone().try_into().unwrap();
466				delivery_fees_amount = if let Some(first_asset) = latest_delivery_fees.inner().first() {
467					let $crate::macros::Fungible(inner_delivery_fees_amount) = first_asset.fun else {
468						unreachable!("asset is non-fungible");
469					};
470					inner_delivery_fees_amount
471				} else {
472					0
473				}
474			});
475
476			// Reset to send actual message.
477			<$sender_para as $crate::macros::TestExt>::reset_ext();
478			<$receiver_relay as $crate::macros::TestExt>::reset_ext();
479			// Mint assets to `$sender_para` to succeed with teleport.
480			<$sender_para as $crate::macros::TestExt>::execute_with(|| {
481				$crate::macros::assert_ok!(<<$sender_para as [<$sender_para Pallet>]>::Balances
482					as $crate::macros::Mutate<_>>::mint_into(&sender, $amount + 10_000_000_000));
483			});
484
485			// Since we reset everything, we need to mint funds into the checking account again.
486			<$receiver_relay as $crate::macros::TestExt>::execute_with(|| {
487				let check_account = <$receiver_relay as [<$receiver_relay Pallet>]>::XcmPallet::check_account();
488				$crate::macros::assert_ok!(<<$receiver_relay as [<$receiver_relay Pallet>]>::Balances
489					as $crate::macros::Mutate<_>>::mint_into(&check_account, $amount));
490			});
491
492			// Send XCM message from Parachain.
493			<$sender_para as $crate::macros::TestExt>::execute_with(|| {
494				let origin = <$sender_para as $crate::macros::Chain>::RuntimeOrigin::signed(sender.clone());
495				$crate::macros::assert_ok!(<_ as $crate::macros::Dispatchable>::dispatch(call, origin));
496
497				type RuntimeEvent = <$sender_para as $crate::macros::Chain>::RuntimeEvent;
498
499				$crate::macros::assert_expected_events!(
500					$sender_para,
501					vec![
502						RuntimeEvent::PolkadotXcm(
503							$crate::macros::pallet_xcm::Event::Attempted { outcome: $crate::macros::Outcome::Complete { .. } }
504						) => {},
505						RuntimeEvent::Balances(
506							$crate::macros::pallet_balances::Event::Withdraw { who, .. }
507						) => {
508							who: *who == sender,
509						},
510						RuntimeEvent::PolkadotXcm(
511							$crate::macros::pallet_xcm::Event::Sent { .. }
512						) => {},
513					]
514				);
515			});
516
517			// Receive XCM message in Destination Parachain
518			<$receiver_relay as $crate::macros::TestExt>::execute_with(|| {
519				type RuntimeEvent = <$receiver_relay as $crate::macros::Chain>::RuntimeEvent;
520
521				$crate::macros::assert_expected_events!(
522					$receiver_relay,
523					vec![
524						RuntimeEvent::Balances(
525							$crate::macros::pallet_balances::Event::Deposit { who, .. }
526						) => {
527							who: *who == receiver,
528						},
529						RuntimeEvent::MessageQueue(
530							$crate::macros::pallet_message_queue::Event::Processed { success: true, .. }
531						) => {},
532					]
533				);
534			});
535
536			// Check if balances are updated accordingly in Origin and Relay Chain
537			let para_sender_balance_after =
538				<$sender_para as $crate::macros::Chain>::account_data_of(sender.clone()).free;
539			let relay_receiver_balance_after =
540				<$receiver_relay as $crate::macros::Chain>::account_data_of(receiver.clone()).free;
541
542			assert_eq!(para_sender_balance_before - $amount - delivery_fees_amount, para_sender_balance_after);
543			assert!(relay_receiver_balance_after > relay_receiver_balance_before);
544
545			// Update sender balance
546			para_sender_balance_before = <$sender_para as $crate::macros::Chain>::account_data_of(sender.clone()).free;
547		}
548	};
549}
550
551#[macro_export]
552macro_rules! test_chain_can_claim_assets {
553	( $sender_para:ty, $xcm_config:ty, $network_id:expr, $asset:expr, $amount:expr ) => {
554		$crate::macros::paste::paste! {
555			use xcm_executor::traits::TransactAsset;
556			let sender = [<$sender_para Sender>]::get();
557			let origin = <$sender_para as $crate::macros::Chain>::RuntimeOrigin::signed(sender.clone());
558			// Receiver is the same as sender
559			let beneficiary: $crate::macros::Location =
560				$crate::macros::Junction::AccountId32 { network: Some($network_id), id: sender.clone().into() }.into();
561			let assets: $crate::macros::Assets = $asset.clone().into();
562			let versioned_assets: $crate::macros::VersionedAssets = assets.clone().into();
563			let context = $crate::macros::XcmContext { origin: None, message_id: Default::default(), topic: None };
564
565			<$sender_para as $crate::macros::TestExt>::execute_with(|| {
566				// Mint some assets to trap.
567				let holdings =
568					<$xcm_config as xcm_executor::Config>::AssetTransactor::mint_asset(
569						&$asset, &context,
570					).unwrap();
571				let total_issuance_before = <<$sender_para as [<$sender_para Pallet>]>::Balances
572					as $crate::macros::Currency<_>>::total_issuance();
573				// Assets are trapped for whatever reason.
574				// The possible reasons for this might differ from runtime to runtime, so here we just drop them directly.
575				<<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm as $crate::macros::DropAssets>::drop_assets(
576					&beneficiary, holdings, &context,
577				);
578				// assert trapping assets does not alter total issuance
579				let total_issuance_after = <<$sender_para as [<$sender_para Pallet>]>::Balances
580					as $crate::macros::Currency<_>>::total_issuance();
581				assert_eq!(total_issuance_before, total_issuance_after);
582
583				type RuntimeEvent = <$sender_para as $crate::macros::Chain>::RuntimeEvent;
584				$crate::macros::assert_expected_events!(
585					$sender_para,
586					vec![
587						RuntimeEvent::PolkadotXcm(
588							$crate::macros::pallet_xcm::Event::AssetsTrapped { origin, assets, .. }
589						) => {
590							origin: *origin == beneficiary,
591							assets: *assets == versioned_assets,
592						},
593					]
594				);
595
596				let balance_before = <<$sender_para as [<$sender_para Pallet>]>::Balances
597					as $crate::macros::Currency<_>>::free_balance(&sender);
598
599				// Different origin or different assets won't work.
600				let other_origin = <$sender_para as $crate::macros::Chain>::RuntimeOrigin::signed([<$sender_para Receiver>]::get());
601				assert!(<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::claim_assets(
602					other_origin,
603					Box::new(versioned_assets.clone().into()),
604					Box::new(beneficiary.clone().into()),
605				).is_err());
606				let other_versioned_assets: $crate::macros::VersionedAssets = $crate::macros::Assets::new().into();
607				assert!(<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::claim_assets(
608					origin.clone(),
609					Box::new(other_versioned_assets.into()),
610					Box::new(beneficiary.clone().into()),
611				).is_err());
612
613				// Assets will be claimed to `beneficiary`, which is the same as `sender`.
614				$crate::macros::assert_ok!(<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::claim_assets(
615					origin.clone(),
616					Box::new(versioned_assets.clone().into()),
617					Box::new(beneficiary.clone().into()),
618				));
619
620				$crate::macros::assert_expected_events!(
621					$sender_para,
622					vec![
623						RuntimeEvent::PolkadotXcm(
624							$crate::macros::pallet_xcm::Event::AssetsClaimed { origin, assets, .. }
625						) => {
626							origin: *origin == beneficiary,
627							assets: *assets == versioned_assets,
628						},
629					]
630				);
631
632				// After claiming the assets, the balance has increased.
633				let balance_after = <<$sender_para as [<$sender_para Pallet>]>::Balances
634					as $crate::macros::Currency<_>>::free_balance(&sender);
635				assert_eq!(balance_after, balance_before + $amount);
636
637				// assert claiming trapped assets does not alter total issuance
638				let total_issuance_after = <<$sender_para as [<$sender_para Pallet>]>::Balances
639					as $crate::macros::Currency<_>>::total_issuance();
640				assert_eq!(total_issuance_before, total_issuance_after);
641
642				// Claiming the assets again doesn't work.
643				assert!(<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::claim_assets(
644					origin.clone(),
645					Box::new(versioned_assets.clone().into()),
646					Box::new(beneficiary.clone().into()),
647				).is_err());
648
649				let balance = <<$sender_para as [<$sender_para Pallet>]>::Balances
650					as $crate::macros::Currency<_>>::free_balance(&sender);
651				assert_eq!(balance, balance_after);
652
653				let holdings =
654					<$xcm_config as xcm_executor::Config>::AssetTransactor::mint_asset(
655						&$asset, &context,
656					).unwrap();
657				let total_issuance_before = <<$sender_para as [<$sender_para Pallet>]>::Balances
658					as $crate::macros::Currency<_>>::total_issuance();
659				// You can also claim assets and send them to a different account.
660				<<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm as $crate::macros::DropAssets>::drop_assets(
661					&beneficiary, holdings, &context,
662				);
663				let receiver = [<$sender_para Receiver>]::get();
664				let other_beneficiary: $crate::macros::Location =
665					$crate::macros::Junction::AccountId32 { network: Some($network_id), id: receiver.clone().into() }.into();
666				let balance_before = <<$sender_para as [<$sender_para Pallet>]>::Balances
667					as $crate::macros::Currency<_>>::free_balance(&receiver);
668				$crate::macros::assert_ok!(<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::claim_assets(
669					origin.clone(),
670					Box::new(versioned_assets.clone().into()),
671					Box::new(other_beneficiary.clone().into()),
672				));
673				let balance_after = <<$sender_para as [<$sender_para Pallet>]>::Balances
674					as $crate::macros::Currency<_>>::free_balance(&receiver);
675				assert_eq!(balance_after, balance_before + $amount);
676				// assert claiming trapped assets does not alter total issuance
677				let total_issuance_after = <<$sender_para as [<$sender_para Pallet>]>::Balances
678					as $crate::macros::Currency<_>>::total_issuance();
679				assert_eq!(total_issuance_before, total_issuance_after);
680			});
681		}
682	};
683}
684
685#[macro_export]
686macro_rules! test_can_estimate_and_pay_exact_fees {
687	( $sender_para:ty, $asset_hub:ty, $receiver_para:ty, ($asset_id:expr, $amount:expr), $owner_prefix:ty ) => {
688		$crate::macros::paste::paste! {
689			// We first define the call we'll use throughout the test.
690			fn get_call(
691				estimated_local_fees: impl Into<$crate::macros::Asset>,
692				estimated_intermediate_fees: impl Into<$crate::macros::Asset>,
693				estimated_remote_fees: impl Into<$crate::macros::Asset>,
694			) -> <$sender_para as $crate::macros::Chain>::RuntimeCall {
695				type RuntimeCall = <$sender_para as $crate::macros::Chain>::RuntimeCall;
696
697				let beneficiary = [<$receiver_para Receiver>]::get();
698				let xcm_in_destination = $crate::macros::Xcm::<()>::builder_unsafe()
699					.pay_fees(estimated_remote_fees)
700					.deposit_asset($crate::macros::AllCounted(1), beneficiary)
701					.build();
702				let ah_to_receiver = <$asset_hub as $crate::macros::Para>::sibling_location_of(
703					<$receiver_para as $crate::macros::Para>::para_id());
704				let xcm_in_reserve = $crate::macros::Xcm::<()>::builder_unsafe()
705					.pay_fees(estimated_intermediate_fees)
706					.deposit_reserve_asset(
707						$crate::macros::AllCounted(1),
708						ah_to_receiver,
709						xcm_in_destination,
710					)
711					.build();
712				let sender_to_ah = <$sender_para as $crate::macros::Para>::sibling_location_of(
713					<$asset_hub as $crate::macros::Para>::para_id());
714				let local_xcm = $crate::macros::Xcm::<<$sender_para as $crate::macros::Chain>::RuntimeCall>::builder()
715					.withdraw_asset(($asset_id, $amount))
716					.pay_fees(estimated_local_fees)
717					.initiate_reserve_withdraw($crate::macros::AllCounted(1), sender_to_ah, xcm_in_reserve)
718					.build();
719
720				RuntimeCall::PolkadotXcm($crate::macros::pallet_xcm::Call::execute {
721					message: Box::new($crate::macros::VersionedXcm::from(local_xcm)),
722					max_weight: $crate::macros::Weight::from_parts(10_000_000_000, 500_000),
723				})
724			}
725
726			let destination = <$sender_para as $crate::macros::Para>::sibling_location_of(
727				<$receiver_para as $crate::macros::Para>::para_id());
728			let sender = [<$sender_para Sender>]::get();
729			let sender_as_seen_by_ah = <$asset_hub as $crate::macros::Para>::sibling_location_of(
730				<$sender_para as $crate::macros::Para>::para_id());
731			let sov_of_sender_on_ah = <$asset_hub as $crate::macros::Para>::sovereign_account_id_of(sender_as_seen_by_ah.clone());
732			let asset_owner = [<$owner_prefix AssetOwner>]::get();
733
734			// Fund parachain's sender account.
735			// TODO: consider mint_foreign_asset to be part of xcm_emulator::Chain trait
736			$sender_para::mint_foreign_asset(
737				<$sender_para as $crate::macros::Chain>::RuntimeOrigin::signed(asset_owner.clone()),
738				$asset_id.clone().into(),
739				sender.clone(),
740				$amount * 2,
741			);
742
743			// Fund the parachain origin's SA on Asset Hub with the native tokens.
744			// TODO: consider fund_accounts to be part of xcm_emulator::Chain trait
745			$asset_hub::fund_accounts(vec![(sov_of_sender_on_ah.clone(), $amount * 2)]);
746
747			let beneficiary_id = [<$receiver_para Receiver>]::get();
748
749			let test_args = $crate::macros::TestContext {
750				sender: sender.clone(),
751				receiver: beneficiary_id.clone(),
752				args: $crate::macros::TestArgs::new_para(
753					destination,
754					beneficiary_id.clone(),
755					$amount,
756					($asset_id, $amount).into(),
757					None,
758					0,
759				),
760			};
761			let mut test = ParaToParaThroughAHTest::new(test_args);
762
763			// We get these from the closure.
764			let mut local_execution_fees = 0;
765			let mut local_delivery_fees = 0;
766			let mut remote_message = $crate::macros::VersionedXcm::from($crate::macros::Xcm::<()>(Vec::new()));
767			<$sender_para as $crate::macros::TestExt>::execute_with(|| {
768				type Runtime = <$sender_para as $crate::macros::Chain>::Runtime;
769				type OriginCaller = <$sender_para as $crate::macros::Chain>::OriginCaller;
770
771				let call = get_call(
772					($crate::macros::Parent, 100_000_000_000u128),
773					($crate::macros::Parent, 100_000_000_000u128),
774					($crate::macros::Parent, 100_000_000_000u128),
775				);
776				let origin = OriginCaller::system($crate::macros::RawOrigin::Signed(sender.clone()));
777				let result = <Runtime as $crate::macros::DryRunApiV2<_,_,_,_>>::dry_run_call(origin, call.clone(),
778					$crate::macros::XCM_VERSION).unwrap();
779				let local_xcm = result.local_xcm.unwrap().clone();
780				let local_xcm_weight = <Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_xcm_weight(local_xcm).unwrap();
781				local_execution_fees = <Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_weight_to_asset_fee(
782					local_xcm_weight,
783					$crate::macros::VersionedAssetId::from($crate::macros::AssetId($crate::macros::Location::parent())),
784				)
785				.unwrap();
786				// We filter the result to get only the messages we are interested in.
787				let (destination_to_query, messages_to_query) = &result
788					.forwarded_xcms
789					.iter()
790					.find(|(destination, _)| {
791						*destination == $crate::macros::VersionedLocation::from(
792							$crate::macros::Location::new(1, [$crate::macros::Parachain(1000)]))
793					})
794					.unwrap();
795				assert_eq!(messages_to_query.len(), 1);
796				remote_message = messages_to_query[0].clone();
797				let del_fee_pen = {
798					let fees_in_pen =
799						<Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_delivery_fees(
800							destination_to_query.clone(),
801							remote_message.clone(),
802							$crate::macros::VersionedAssetId::from($crate::macros::AssetId(
803								$crate::macros::Location::here(),
804							)),
805						).unwrap();
806					$crate::xcm_helpers::get_amount_from_versioned_assets(fees_in_pen)
807				};
808				let exec_fee_pen =
809					<Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_weight_to_asset_fee(
810						local_xcm_weight,
811						$crate::macros::VersionedAssetId::from($crate::macros::AssetId(
812							$crate::macros::Location::here(),
813						)),
814					).unwrap();
815				local_delivery_fees = $crate::macros::with_transaction_unchecked(|| {
816					$crate::macros::assert_ok!(
817						$crate::macros::pallet_asset_conversion::Pallet::<Runtime>::swap_tokens_for_exact_tokens(
818							<$sender_para as $crate::macros::Chain>::RuntimeOrigin::from(
819								$crate::macros::RawOrigin::Signed(sender.clone()),
820							),
821							vec![
822								Box::new($crate::macros::Location::parent()),
823								Box::new($crate::macros::Location::here()),
824							],
825							exec_fee_pen,
826							local_execution_fees,
827							sender.clone(),
828							false,
829						)
830					);
831					let needed_wnd =
832						$crate::macros::pallet_asset_conversion::Pallet::<Runtime>::quote_price_tokens_for_exact_tokens(
833							$crate::macros::Location::parent(),
834							$crate::macros::Location::here(),
835							del_fee_pen,
836							true,
837						).expect("pool exists and del_fee_pen is nonzero; qed");
838					$crate::macros::TransactionOutcome::Rollback(needed_wnd)
839				});
840			});
841
842			// These are set in the AssetHub closure.
843			let mut intermediate_execution_fees = 0;
844			let mut intermediate_delivery_fees = 0;
845			let mut intermediate_remote_message = $crate::macros::VersionedXcm::from($crate::macros::Xcm::<()>(Vec::new()));
846			<$asset_hub as $crate::macros::TestExt>::execute_with(|| {
847				type Runtime = <$asset_hub as $crate::macros::Chain>::Runtime;
848				type RuntimeCall = <$asset_hub as $crate::macros::Chain>::RuntimeCall;
849
850				// First we get the execution fees.
851				let weight = <Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_xcm_weight(remote_message.clone()).unwrap();
852				intermediate_execution_fees = <Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_weight_to_asset_fee(
853					weight,
854					$crate::macros::VersionedAssetId::from($crate::macros::AssetId($crate::macros::Location::new(1, []))),
855				)
856				.unwrap();
857
858				// We have to do this to turn `VersionedXcm<()>` into `VersionedXcm<RuntimeCall>`.
859				let xcm_program =
860					$crate::macros::VersionedXcm::from($crate::macros::Xcm::<RuntimeCall>::from(
861						remote_message.clone().try_into().unwrap()));
862
863				// Now we get the delivery fees to the final destination.
864				let result = <Runtime as $crate::macros::DryRunApiV2<_,_,_,_>>::dry_run_xcm(
865					sender_as_seen_by_ah.clone().into(), xcm_program).unwrap();
866				let (destination_to_query, messages_to_query) = &result
867					.forwarded_xcms
868					.iter()
869					.find(|(destination, _)| {
870						*destination == $crate::macros::VersionedLocation::from($crate::macros::Location::new(1,
871							[$crate::macros::Parachain(2001)]))
872					})
873					.unwrap();
874				// There's actually two messages here.
875				// One created when the message we sent from `$sender_para` arrived and was executed.
876				// The second one when we dry-run the xcm.
877				// We could've gotten the message from the queue without having to dry-run, but
878				// offchain applications would have to dry-run, so we do it here as well.
879				intermediate_remote_message = messages_to_query[0].clone();
880				let asset_id_for_delivery_fees = VersionedAssetId::from(Location::parent());
881				let delivery_fees = <Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_delivery_fees(
882					destination_to_query.clone(),
883					intermediate_remote_message.clone(),
884					asset_id_for_delivery_fees,
885				)
886				.unwrap();
887				intermediate_delivery_fees = $crate::xcm_helpers::get_amount_from_versioned_assets(delivery_fees);
888			});
889
890			// Dry-running is done.
891			<$sender_para as $crate::macros::TestExt>::reset_ext();
892			<$asset_hub as $crate::macros::TestExt>::reset_ext();
893			<$receiver_para as $crate::macros::TestExt>::reset_ext();
894
895			// Fund accounts again.
896			$sender_para::mint_foreign_asset(
897				<$sender_para as $crate::macros::Chain>::RuntimeOrigin::signed(asset_owner.clone()),
898				$asset_id.clone().into(),
899				sender.clone(),
900				$amount * 2,
901			);
902			$sender_para::fund_accounts(vec![(sender.clone(), $amount * 2)]);
903
904			$asset_hub::fund_accounts(vec![(sov_of_sender_on_ah, $amount * 2)]);
905
906			// Get the final execution fees at the destination.
907			//
908			// Note: We need to do this after resetting the externalities to get an accurate value here.
909			// Workaround for https://github.com/paritytech/polkadot-sdk/issues/11486.
910			let mut final_execution_fees = 0;
911			<$receiver_para as $crate::macros::TestExt>::execute_with(|| {
912				type Runtime = <$receiver_para as $crate::macros::Chain>::Runtime;
913
914				let weight = <Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_xcm_weight(
915					intermediate_remote_message.clone()).expect("`query_xcm_weight` returned none");
916				final_execution_fees =
917					<Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_weight_to_asset_fee(weight,
918						$crate::macros::VersionedAssetId::from($crate::macros::AssetId($crate::macros::Location::parent())))
919						.expect("`query_weight_to_asset_fee` returned none");
920			});
921
922			// Actually run the extrinsic.
923			let sender_assets_before = <$sender_para as $crate::macros::TestExt>::execute_with(|| {
924				type Assets = <$sender_para as [<$sender_para Pallet>]>::Assets;
925				<Assets as $crate::macros::Inspect<_>>::balance($asset_id.clone().into(), &sender)
926			});
927			let receiver_assets_before = <$receiver_para as $crate::macros::TestExt>::execute_with(|| {
928				type Assets = <$receiver_para as [<$receiver_para Pallet>]>::Assets;
929				<Assets as $crate::macros::Inspect<_>>::balance($asset_id.clone().into(), &beneficiary_id)
930			});
931
932			test.set_assertion::<$sender_para>(sender_assertions);
933			test.set_assertion::<$asset_hub>(hop_assertions);
934			test.set_assertion::<$receiver_para>(receiver_assertions);
935			let call = get_call(
936				($crate::macros::Parent, local_execution_fees + local_delivery_fees),
937				($crate::macros::Parent, intermediate_execution_fees + intermediate_delivery_fees),
938				($crate::macros::Parent, final_execution_fees),
939			);
940			test.set_call(call);
941			test.assert();
942
943			let sender_assets_after = <$sender_para as $crate::macros::TestExt>::execute_with(|| {
944				type Assets = <$sender_para as [<$sender_para Pallet>]>::Assets;
945				<Assets as $crate::macros::Inspect<_>>::balance($asset_id.clone().into(), &sender)
946			});
947			let receiver_assets_after = <$receiver_para as $crate::macros::TestExt>::execute_with(|| {
948				type Assets = <$receiver_para as [<$receiver_para Pallet>]>::Assets;
949				<Assets as $crate::macros::Inspect<_>>::balance($asset_id.into(), &beneficiary_id)
950			});
951
952			// We know the exact fees on every hop.
953			assert_eq!(sender_assets_after, sender_assets_before - $amount);
954			assert_eq!(
955				receiver_assets_after,
956				receiver_assets_before + $amount -
957					local_execution_fees -
958					local_delivery_fees -
959					intermediate_execution_fees -
960					intermediate_delivery_fees -
961					final_execution_fees
962			);
963		}
964	};
965}
966
967#[macro_export]
968macro_rules! test_dry_run_transfer_across_pk_bridge {
969	( $sender_asset_hub:ty, $sender_bridge_hub:ty, $destination:expr ) => {
970		$crate::macros::paste::paste! {
971
972			let who = $crate::macros::AccountId32::new([1u8; 32]);
973			let transfer_amount = 10_000_000_000_000u128;
974			let initial_balance = transfer_amount * 10;
975
976			// AssetHub setup.
977			$sender_asset_hub::force_xcm_version($destination, $crate::macros::XCM_VERSION);
978
979			<$sender_asset_hub as $crate::macros::TestExt>::execute_with(|| {
980				type Runtime = <$sender_asset_hub as $crate::macros::Chain>::Runtime;
981				type RuntimeCall = <$sender_asset_hub as $crate::macros::Chain>::RuntimeCall;
982				type OriginCaller = <$sender_asset_hub as $crate::macros::Chain>::OriginCaller;
983				type Balances = <$sender_asset_hub as [<$sender_asset_hub Pallet>]>::Balances;
984
985				// Give some initial funds.
986				<Balances as $crate::macros::Mutate<_>>::set_balance(&who, initial_balance);
987
988				let beneficiary: $crate::macros::Location = $crate::macros::Junction::AccountId32 {
989						id: who.clone().into(),
990						network: None,
991					}.into();
992
993				let call = RuntimeCall::PolkadotXcm($crate::macros::pallet_xcm::Call::transfer_assets_using_type_and_then {
994					dest: Box::new($crate::macros::VersionedLocation::from($destination)),
995					assets: Box::new($crate::macros::VersionedAssets::from(vec![
996						($crate::macros::Parent, transfer_amount).into(),
997					])),
998					assets_transfer_type: Box::new($crate::macros::TransferType::LocalReserve),
999					remote_fees_id: Box::new($crate::macros::VersionedAssetId::from($crate::macros::Parent)),
1000					fees_transfer_type: Box::new($crate::macros::TransferType::LocalReserve),
1001					custom_xcm_on_dest: Box::new($crate::macros::VersionedXcm::<()>::from($crate::macros::Xcm::<()>::builder_unsafe().deposit_asset(AllCounted(1), beneficiary).build())),
1002					weight_limit: $crate::macros::Unlimited,
1003				});
1004				let origin = OriginCaller::system($crate::macros::RawOrigin::Signed(who));
1005				let result = <Runtime as $crate::macros::DryRunApiV2<_,_,_,_>>::dry_run_call(origin, call.clone(),
1006					$crate::macros::XCM_VERSION).unwrap();
1007
1008				// We assert the dry run succeeds and sends only one message to the local bridge hub.
1009				assert!(result.execution_result.is_ok());
1010				assert_eq!(result.forwarded_xcms.len(), 1);
1011				assert_eq!(result.forwarded_xcms[0].0, $crate::macros::VersionedLocation::from(
1012					$crate::macros::Location::new(1, [$crate::macros::Parachain(
1013						<$sender_bridge_hub as $crate::macros::Para>::para_id().into())])));
1014			});
1015		}
1016	};
1017}
1018
1019#[macro_export]
1020macro_rules! test_xcm_fee_querying_apis_work_for_asset_hub {
1021	( $asset_hub:ty ) => {
1022		$crate::macros::paste::paste! {
1023
1024			<$asset_hub as $crate::macros::TestExt>::execute_with(|| {
1025				// Setup a pool between USDT and WND.
1026				type RuntimeOrigin = <$asset_hub as $crate::macros::Chain>::RuntimeOrigin;
1027				type Assets = <$asset_hub as [<$asset_hub Pallet>]>::Assets;
1028				type AssetConversion = <$asset_hub as [<$asset_hub Pallet>]>::AssetConversion;
1029				let wnd = $crate::macros::Location::new(1, []);
1030				let usdt = $crate::macros::Location::new(0, [$crate::macros::PalletInstance($crate::macros::ASSETS_PALLET_ID),
1031					$crate::macros::GeneralIndex($crate::macros::USDT_ID.into())]);
1032				let sender = [<$asset_hub Sender>]::get();
1033				$crate::macros::assert_ok!(AssetConversion::create_pool(
1034					RuntimeOrigin::signed(sender.clone()),
1035					Box::new(wnd.clone()),
1036					Box::new(usdt.clone()),
1037				));
1038
1039				type Runtime = <$asset_hub as $crate::macros::Chain>::Runtime;
1040				let acceptable_payment_assets = <Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_acceptable_payment_assets(
1041					$crate::macros::XCM_VERSION).unwrap();
1042				assert_eq!(acceptable_payment_assets, vec![
1043					$crate::macros::VersionedAssetId::from($crate::macros::AssetId(wnd.clone())),
1044					$crate::macros::VersionedAssetId::from($crate::macros::AssetId(usdt.clone())),
1045				]);
1046
1047				let program = $crate::macros::Xcm::<()>::builder()
1048					.withdraw_asset(($crate::macros::Parent, 100u128))
1049					.buy_execution(($crate::macros::Parent, 10u128), $crate::macros::Unlimited)
1050					.deposit_asset($crate::macros::All, [0u8; 32])
1051					.build();
1052				let weight = <Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_xcm_weight(
1053					$crate::macros::VersionedXcm::from(program)).unwrap();
1054				let fee_in_wnd = <Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_weight_to_asset_fee(weight,
1055					$crate::macros::VersionedAssetId::from($crate::macros::AssetId(wnd.clone()))).unwrap();
1056				// Assets not in a pool don't work.
1057				assert!(<Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_weight_to_asset_fee(weight,
1058					$crate::macros::VersionedAssetId::from(
1059						$crate::macros::AssetId($crate::macros::Location::new(0,
1060							[$crate::macros::PalletInstance($crate::macros::ASSETS_PALLET_ID),
1061								$crate::macros::GeneralIndex(1)]
1062							)
1063						)
1064					)
1065				).is_err());
1066				let fee_in_usdt_fail = <Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_weight_to_asset_fee(weight,
1067					$crate::macros::VersionedAssetId::from($crate::macros::AssetId(usdt.clone())));
1068				// Weight to asset fee fails because there's not enough asset in the pool.
1069				// We just created it, there's none.
1070				assert_eq!(fee_in_usdt_fail, Err($crate::macros::XcmPaymentApiError::AssetNotFound));
1071				// We add some.
1072				$crate::macros::assert_ok!(Assets::mint(
1073					RuntimeOrigin::signed(sender.clone()),
1074					$crate::macros::USDT_ID.into(),
1075					sender.clone().into(),
1076					5_000_000_000_000
1077				));
1078				// We make 1 WND = 4 USDT.
1079				$crate::macros::assert_ok!(AssetConversion::add_liquidity(
1080					RuntimeOrigin::signed(sender.clone()),
1081					Box::new(wnd),
1082					Box::new(usdt.clone()),
1083					1_000_000_000_000,
1084					4_000_000_000_000,
1085					0,
1086					0,
1087					sender.into()
1088				));
1089				// Now it works.
1090				let fee_in_usdt = <Runtime as $crate::macros::XcmPaymentApiV2<_>>::query_weight_to_asset_fee(weight,
1091					$crate::macros::VersionedAssetId::from($crate::macros::AssetId(usdt))
1092				);
1093				$crate::macros::assert_ok!(fee_in_usdt);
1094				assert!(fee_in_usdt.unwrap() > fee_in_wnd);
1095			});
1096		}
1097	};
1098}
1099
1100#[macro_export]
1101macro_rules! test_cross_chain_alias {
1102	( vec![$( ($sender_para:ty, $receiver_para:ty, $is_teleport:expr, $expected_success:expr) ),+], $origin:expr, $target:expr, $fees:expr ) => {
1103		$crate::macros::paste::paste! {
1104			$(
1105				{
1106					let para_destination = <$sender_para as $crate::macros::Para>::sibling_location_of(
1107						<$receiver_para as $crate::macros::Para>::para_id());
1108					let account: $crate::macros::AccountId = $origin.clone().into();
1109					$sender_para::fund_accounts(vec![(account.clone(), $fees * 10)]);
1110					let total_fees: $crate::macros::Asset = ($crate::macros::Location::parent(), $fees).into();
1111					let fees: $crate::macros::Asset = ($crate::macros::Location::parent(), $fees / 2).into();
1112
1113					let remote_fees = if $is_teleport {
1114						Some($crate::macros::AssetTransferFilter::Teleport(fees.clone().into()))
1115					} else {
1116						let source_para_sa = <$receiver_para as $crate::macros::Para>::sovereign_account_id_of(
1117							<$receiver_para as $crate::macros::Para>::sibling_location_of(
1118								<$sender_para as $crate::macros::Para>::para_id()),
1119						);
1120						$receiver_para::fund_accounts(vec![(source_para_sa, $fees * 10)]);
1121						Some($crate::macros::AssetTransferFilter::ReserveWithdraw(fees.clone().into()))
1122					};
1123					<$sender_para as $crate::macros::TestExt>::execute_with(|| {
1124						type RuntimeEvent = <$sender_para as $crate::macros::Chain>::RuntimeEvent;
1125						let xcm_message = $crate::macros::Xcm::<()>(vec![
1126							$crate::macros::WithdrawAsset(total_fees.into()),
1127							$crate::macros::PayFees { asset: fees.clone() },
1128							$crate::macros::InitiateTransfer {
1129								destination: para_destination,
1130								remote_fees,
1131								preserve_origin: true,
1132								assets: $crate::macros::BoundedVec::new(),
1133								remote_xcm: $crate::macros::Xcm(vec![
1134									// try to alias into `account`
1135									$crate::macros::AliasOrigin($target.clone().into()),
1136									$crate::macros::RefundSurplus,
1137									$crate::macros::DepositAsset {
1138										assets: $crate::macros::Wild($crate::macros::AllCounted(1)),
1139										beneficiary: $target.clone().into(),
1140									},
1141								]),
1142							},
1143							$crate::macros::RefundSurplus,
1144							$crate::macros::DepositAsset { assets: $crate::macros::Wild($crate::macros::AllCounted(1)),
1145								beneficiary: account.clone().into() },
1146						]);
1147
1148						let signed_origin = <$sender_para as $crate::macros::Chain>::RuntimeOrigin::signed(account.into());
1149						$crate::macros::assert_ok!(<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::execute(
1150							signed_origin,
1151							Box::new($crate::macros::VersionedXcm::from(xcm_message.into())),
1152							$crate::macros::Weight::MAX
1153						));
1154						$crate::macros::assert_expected_events!(
1155							$sender_para,
1156							vec![
1157								RuntimeEvent::PolkadotXcm($crate::macros::pallet_xcm::Event::Sent { .. }) => {},
1158							]
1159						);
1160					});
1161
1162					<$receiver_para as $crate::macros::TestExt>::execute_with(|| {
1163						type RuntimeEvent = <$receiver_para as $crate::macros::Chain>::RuntimeEvent;
1164						$crate::macros::assert_expected_events!(
1165							$receiver_para,
1166							vec![
1167								RuntimeEvent::MessageQueue($crate::macros::pallet_message_queue::Event::Processed {
1168									success, ..
1169								}) => { success: *success == $expected_success, },
1170							]
1171						);
1172					});
1173				}
1174			)+
1175		}
1176	};
1177}
1178
1179#[macro_export]
1180macro_rules! assert_whitelisted {
1181    ($chain:ident, $expected_call_hash:expr) => {
1182		type RuntimeEvent = <$chain as $crate::macros::Chain>::RuntimeEvent;
1183		$crate::macros::assert_expected_events!(
1184			$chain,
1185			vec![
1186				RuntimeEvent::Whitelist($crate::macros::pallet_whitelist::Event::CallWhitelisted { call_hash }) => {
1187						call_hash: *call_hash == $expected_call_hash,
1188				},
1189			]
1190		);
1191    };
1192}
1193
1194/// Read the balance of the `Assets`-pallet asset `$id` for `$who` on `$chain`.
1195#[macro_export]
1196macro_rules! assets_balance_on {
1197	( $chain:ident, $id:expr, $who:expr ) => {
1198		$crate::macros::paste::paste! {
1199			<$chain as $crate::macros::TestExt>::ext_wrapper(|| {
1200				type Assets = <$chain as [<$chain Pallet>]>::Assets;
1201				<Assets as frame_support::traits::fungibles::Inspect<_>>::balance($id, $who)
1202			})
1203		}
1204	};
1205}
1206
1207/// Read the balance of the `ForeignAssets`-pallet asset `$id` for `$who` on `$chain`.
1208#[macro_export]
1209macro_rules! foreign_balance_on {
1210	( $chain:ident, $id:expr, $who:expr ) => {
1211		$crate::macros::paste::paste! {
1212			<$chain as $crate::macros::TestExt>::ext_wrapper(|| {
1213				type ForeignAssets = <$chain as [<$chain Pallet>]>::ForeignAssets;
1214				<ForeignAssets as frame_support::traits::fungibles::Inspect<_>>::balance($id, $who)
1215			})
1216		}
1217	};
1218}
1219
1220/// Read the total issuance of the `Assets`-pallet asset `$id` on `$chain`.
1221#[macro_export]
1222macro_rules! assets_issuance_on {
1223	( $chain:ident, $id:expr ) => {
1224		$crate::macros::paste::paste! {
1225			<$chain as $crate::macros::TestExt>::ext_wrapper(|| {
1226				type Assets = <$chain as [<$chain Pallet>]>::Assets;
1227				<Assets as frame_support::traits::fungibles::Inspect<_>>::total_issuance($id)
1228			})
1229		}
1230	};
1231}
1232
1233/// Read the total issuance of the `ForeignAssets`-pallet asset `$id` on `$chain`.
1234#[macro_export]
1235macro_rules! foreign_issuance_on {
1236	( $chain:ident, $id:expr ) => {
1237		$crate::macros::paste::paste! {
1238			<$chain as $crate::macros::TestExt>::ext_wrapper(|| {
1239				type ForeignAssets = <$chain as [<$chain Pallet>]>::ForeignAssets;
1240				<ForeignAssets as frame_support::traits::fungibles::Inspect<_>>::total_issuance($id)
1241			})
1242		}
1243	};
1244}
1245
1246/// Read the total native-balance issuance on `$chain`.
1247#[macro_export]
1248macro_rules! balances_issuance_on {
1249	( $chain:ident ) => {
1250		$crate::macros::paste::paste! {
1251			<$chain as $crate::macros::TestExt>::ext_wrapper(|| {
1252				type Balances = <$chain as [<$chain Pallet>]>::Balances;
1253				<Balances as frame_support::traits::fungible::Inspect<_>>::total_issuance()
1254			})
1255		}
1256	};
1257}
1258
1259/// Whether the `Assets`-pallet asset `$id` exists on `$chain`.
1260#[macro_export]
1261macro_rules! asset_exists_on {
1262	( $chain:ident, $id:expr ) => {
1263		$crate::macros::paste::paste! {
1264			<$chain as $crate::macros::TestExt>::ext_wrapper(|| {
1265				type Assets = <$chain as [<$chain Pallet>]>::Assets;
1266				<Assets as frame_support::traits::fungibles::Inspect<_>>::asset_exists($id)
1267			})
1268		}
1269	};
1270}