referrerpolicy=no-referrer-when-downgrade

staging_xcm_builder/
forwarder.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//! XCM adapters for the accumulate-and-forward pallet.
18//!
19//! - [`TeleportForwarderForAccountId32`]: accumulation-account-side forwarding adapter.
20
21use alloc::vec;
22use core::marker::PhantomData;
23use frame_support::{
24	storage::{with_transaction, TransactionOutcome},
25	traits::Get,
26	BoundedVec,
27};
28use sp_runtime::DispatchError;
29use xcm::latest::{prelude::*, AssetTransferFilter};
30use xcm_executor::XcmExecutor;
31
32const LOG_TARGET: &str = "xcm::accumulate-forward";
33
34/// XCM adapter that implements [`pallet_accumulate_and_forward::Forwarder`] for AccountId32-type
35/// source accounts by teleporting native tokens to a target account on a destination chain.
36/// Local-execution failures roll back all local state changes. Once the local executor reports
37/// success, the message is queued and any destination-side rejection results in trapped assets
38/// at the destination with no automatic recovery path.
39///
40/// NOTE: This adapter passes `Weight::MAX` to the XCM executor, relying on the call site to
41/// enforce a weight budget before invoking it. It is designed to be called only from rate-limited
42/// internal hooks such as `on_idle` and should never be wired to user-callable extrinsics.
43pub struct TeleportForwarderForAccountId32<XcmConfig, Dest, NativeAsset, StagingLocation>(
44	PhantomData<(XcmConfig, Dest, NativeAsset, StagingLocation)>,
45);
46
47impl<XcmConfig, Dest, NativeAsset, StagingLocation, AccountId, Balance>
48	pallet_accumulate_and_forward::Forwarder<AccountId, Balance>
49	for TeleportForwarderForAccountId32<XcmConfig, Dest, NativeAsset, StagingLocation>
50where
51	XcmConfig: xcm_executor::Config,
52	Dest: Get<Location>,
53	NativeAsset: Get<Location>,
54	StagingLocation: Get<InteriorLocation>,
55	AccountId: Into<[u8; 32]> + Clone,
56	Balance: Into<u128> + Copy,
57{
58	fn forward(source: AccountId, amount: Balance) -> Result<(), ()> {
59		let dest = Dest::get();
60		let asset = Asset { id: AssetId(NativeAsset::get()), fun: Fungible(amount.into()) };
61		let beneficiary: Location = StagingLocation::get().into_location();
62
63		let remote_xcm = Xcm(vec![DepositAsset { assets: Wild(AllCounted(1)), beneficiary }]);
64
65		// The XCM flow: `ReceiveTeleportedAsset โ†’ AliasOrigin(source) โ†’ UnpaidExecution โ†’
66		// DepositAsset`. `preserve_origin: true` causes `InitiateTransfer` to prepend
67		// `AliasOrigin(source_location)` to the remote XCM.
68		let xcm: Xcm<XcmConfig::RuntimeCall> = Xcm(vec![
69			UnpaidExecution { weight_limit: WeightLimit::Unlimited, check_origin: None },
70			DescendOrigin(Junction::AccountId32 { network: None, id: source.into() }.into()),
71			WithdrawAsset(asset.into()),
72			InitiateTransfer {
73				destination: dest,
74				remote_fees: None,
75				preserve_origin: true,
76				assets: BoundedVec::truncate_from(alloc::vec![AssetTransferFilter::Teleport(
77					Wild(AllCounted(1))
78				),]),
79				remote_xcm,
80			},
81		]);
82
83		with_transaction(|| -> TransactionOutcome<Result<(), DispatchError>> {
84			let outcome = XcmExecutor::<XcmConfig>::prepare_and_execute(
85				Location::here(),
86				xcm,
87				&mut [0u8; 32],
88				Weight::MAX,
89				Weight::MAX,
90			);
91
92			match outcome {
93				Outcome::Complete { .. } => TransactionOutcome::Commit(Ok(())),
94				exec_error => {
95					tracing::debug!(
96						target: LOG_TARGET,
97						?exec_error,
98						"accumulate-forward: XCM execution failed"
99					);
100
101					TransactionOutcome::Rollback(Err(DispatchError::Other("XCM execution failed")))
102				},
103			}
104		})
105		.map_err(|_| ())
106	}
107}
108
109/// Benchmark helper for [`TeleportForwarderForAccountId32`] that makes `Dest` reachable through
110/// `DeliveryHelper`.
111#[cfg(feature = "runtime-benchmarks")]
112pub struct TeleportForwarderBenchmarkHelper<DeliveryHelper, Dest>(
113	PhantomData<(DeliveryHelper, Dest)>,
114);
115
116#[cfg(feature = "runtime-benchmarks")]
117impl<DeliveryHelper, Dest, AccountId> pallet_accumulate_and_forward::BenchmarkHelper<AccountId>
118	for TeleportForwarderBenchmarkHelper<DeliveryHelper, Dest>
119where
120	DeliveryHelper: crate::EnsureDelivery,
121	Dest: Get<Location>,
122	AccountId: Into<[u8; 32]> + Clone,
123{
124	fn ensure_successful_forward(source: &AccountId) {
125		let origin: Location =
126			Junction::AccountId32 { network: None, id: source.clone().into() }.into();
127		DeliveryHelper::ensure_successful_delivery(
128			&origin,
129			&Dest::get(),
130			xcm_executor::traits::FeeReason::InitiateTransfer,
131		);
132	}
133}