referrerpolicy=no-referrer-when-downgrade

pallet_hrmp_para/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! # Parachain HRMP deposit pallet
19//!
20//! Holds and release the deposits of parachain for the relay chain HRMP channel.
21//!
22//! [`Pallet::receive`] is called with [`MessageToPara`] from the relay chain and follows the
23//! protocol defined in hrmp-primitives.
24//! [`Call::force_set_deposit`] is called by governance to fix potential inconsistent state.
25
26#![cfg_attr(not(feature = "std"), no_std)]
27
28extern crate alloc;
29
30use core::cmp::Ordering;
31use frame_support::{
32	pallet_prelude::*,
33	storage::{transactional::with_transaction_opaque_err, with_storage_layer, TransactionOutcome},
34	traits::{
35		fungible::{InspectHold, MutateHold},
36		tokens::Precision,
37	},
38};
39use hrmp_primitives::{
40	Balance, ChannelId, DepositError, DepositKey, DepositSide, MessageToPara, MessageToParaV1,
41	MessageToRelay, MessageToRelayV1, ParaId, ReceiveMigratedDeposits,
42};
43use sp_runtime::{traits::Convert, DispatchError, DispatchResult, TokenError};
44
45pub use pallet::*;
46pub use weights::WeightInfo;
47
48pub mod weights;
49
50#[cfg(feature = "runtime-benchmarks")]
51mod benchmarking;
52#[cfg(test)]
53mod mock;
54#[cfg(test)]
55mod tests;
56
57/// The index of [`Call::receive`] that receives [`MessageToPara`].
58pub const RECEIVE_CALL_INDEX: u8 = 0;
59
60/// Used to send an XCM `Transact` to `pallet-hrmp-relay` on the relay chain.
61pub trait SendToRelay {
62	/// Send `message` to the relay chain.
63	#[allow(clippy::result_unit_err)]
64	fn send(message: MessageToRelay) -> Result<(), ()>;
65}
66
67#[cfg(feature = "std")]
68impl SendToRelay for () {
69	fn send(_message: MessageToRelay) -> Result<(), ()> {
70		Ok(())
71	}
72}
73
74/// Prepares the runtime for this pallet's benchmarks.
75#[cfg(feature = "runtime-benchmarks")]
76pub trait BenchmarkHelper {
77	/// Makes [`Config::SendToRelay`] take messages.
78	fn ensure_send_to_relay();
79}
80
81#[cfg(feature = "runtime-benchmarks")]
82impl BenchmarkHelper for () {
83	fn ensure_send_to_relay() {}
84}
85
86/// The hold reason type of [`Config::Currency`].
87pub type ReasonOf<T> =
88	<<T as Config>::Currency as InspectHold<<T as frame_system::Config>::AccountId>>::Reason;
89
90/// What one side of a channel holds, and from whose account.
91#[derive(Encode, Decode, Clone, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen)]
92pub struct Deposit<AccountId> {
93	/// What is held.
94	pub amount: Balance,
95	/// The account it is held from, and released to.
96	///
97	/// The depositor is always the sovereign account of the para and should be constant, but we
98	/// record it and use the recorded value defensively, and to help re-anchoring.
99	pub depositor: AccountId,
100}
101
102#[frame_support::pallet]
103pub mod pallet {
104	use super::*;
105	use frame_system::pallet_prelude::*;
106
107	#[pallet::config]
108	pub trait Config: frame_system::Config {
109		/// The currency the deposits are held in.
110		type Currency: MutateHold<Self::AccountId, Reason: From<HoldReason>, Balance = Balance>;
111
112		/// Sends messages to the relay chain.
113		type SendToRelay: SendToRelay;
114
115		/// A para's sovereign account on this chain, which pays its deposits.
116		///
117		/// It must be constant for a given para.
118		// Defensively, it is only consulted for a side that holds nothing: a side that holds
119		// something keeps holding from, and is released to, the account recorded in [`Deposits`].
120		type SovereignAccountOf: Convert<ParaId, Self::AccountId>;
121
122		/// Weight information for the operations in this pallet.
123		type WeightInfo: WeightInfo;
124
125		/// Prepares the runtime for the benchmarks.
126		#[cfg(feature = "runtime-benchmarks")]
127		type BenchmarkHelper: BenchmarkHelper;
128	}
129
130	#[pallet::pallet]
131	pub struct Pallet<T>(_);
132
133	/// A reason for this pallet placing a hold on funds.
134	#[pallet::composite_enum]
135	pub enum HoldReason {
136		/// An HRMP channel deposit.
137		#[codec(index = 0)]
138		ChannelDeposit,
139	}
140
141	/// What is held for each side of each channel, and from whose account.
142	///
143	/// A side holding nothing has no entry.
144	#[pallet::storage]
145	pub type Deposits<T: Config> =
146		StorageMap<_, Twox64Concat, (ChannelId, DepositSide), Deposit<T::AccountId>, OptionQuery>;
147
148	#[pallet::event]
149	#[pallet::generate_deposit(pub(super) fn deposit_event)]
150	pub enum Event<T: Config> {
151		/// A side now holds `amount`.
152		DepositSet { channel: ChannelId, side: DepositSide, amount: Balance },
153		/// The deposits of request `id` could not be set. Nothing changed.
154		DepositRefused { id: u64, channel: ChannelId },
155		/// A migrated deposit of `amount` was taken over: the side now holds `held`, which is
156		/// `amount` unless the hold to move from, the migration's or this pallet's, was short.
157		DepositMigrated { channel: ChannelId, side: DepositSide, amount: Balance, held: Balance },
158	}
159
160	#[pallet::error]
161	pub enum Error<T> {
162		/// The answer could not be handed to the transport.
163		SendFailed,
164		/// The side cannot cover its deposit.
165		InsufficientFunds,
166		/// The side's deposit could not be held or released for another reason.
167		CannotChangeDeposit,
168	}
169
170	#[pallet::hooks]
171	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
172		#[cfg(feature = "try-runtime")]
173		fn try_state(_: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
174			Self::do_try_state()
175		}
176	}
177
178	#[pallet::call]
179	impl<T: Config> Pallet<T> {
180		/// Receive a message from the relay chain.
181		///
182		/// The origin must be root.
183		// The index must equal `RECEIVE_CALL_INDEX`.
184		#[pallet::call_index(0)]
185		#[pallet::weight(match message {
186			MessageToPara::V1(MessageToParaV1::SetDeposits { .. }) =>
187				T::WeightInfo::receive_set_deposits(),
188			MessageToPara::V1(MessageToParaV1::Release { .. }) => T::WeightInfo::receive_release(),
189		})]
190		pub fn receive(origin: OriginFor<T>, message: MessageToPara) -> DispatchResult {
191			ensure_root(origin)?;
192
193			match message {
194				MessageToPara::V1(MessageToParaV1::SetDeposits {
195					id,
196					channel,
197					sender,
198					recipient,
199				}) => {
200					let result = with_transaction_opaque_err(|| {
201						if let Some(target) = sender {
202							if let Err(err) = Self::set_side(channel, DepositSide::Sender, target) {
203								return TransactionOutcome::Rollback(Err(err));
204							}
205						}
206						if let Some(target) = recipient {
207							if let Err(err) =
208								Self::set_side(channel, DepositSide::Recipient, target)
209							{
210								return TransactionOutcome::Rollback(Err(err));
211							}
212						}
213
214						TransactionOutcome::Commit(Ok(()))
215					})
216					.unwrap_or(Err(DepositError::Other)); // Too deep in nested transactions.
217
218					if result.is_err() {
219						Self::deposit_event(Event::DepositRefused { id, channel });
220					}
221					Self::send(MessageToRelayV1::DepositsSet { id, result })
222				},
223				MessageToPara::V1(MessageToParaV1::Release { channel, sender, recipient }) => {
224					if sender {
225						Self::release_side(channel, DepositSide::Sender);
226					}
227					if recipient {
228						Self::release_side(channel, DepositSide::Recipient);
229					}
230					Ok(())
231				},
232			}
233		}
234
235		/// Hold or release so that `side` of `channel` holds `amount`, for a side that holds other
236		/// than what the relay chain records.
237		#[pallet::call_index(1)]
238		#[pallet::weight(T::WeightInfo::receive_set_deposits())]
239		pub fn force_set_deposit(
240			origin: OriginFor<T>,
241			channel: ChannelId,
242			side: DepositSide,
243			amount: Balance,
244		) -> DispatchResult {
245			ensure_root(origin)?;
246
247			if Deposits::<T>::get((channel, side)).map_or(0, |d| d.amount) == amount {
248				return Ok(());
249			}
250			Self::set_side(channel, side, amount).map_err(|e| match e {
251				DepositError::InsufficientFunds => Error::<T>::InsufficientFunds.into(),
252				DepositError::Other => Error::<T>::CannotChangeDeposit.into(),
253			})
254		}
255	}
256}
257
258impl<T: Config> ReceiveMigratedDeposits<ReasonOf<T>> for Pallet<T> {
259	fn receive_deposit(key: DepositKey, amount: Balance, source: &ReasonOf<T>) -> DispatchResult {
260		let DepositKey { channel, side } = key;
261		let local = HoldReason::ChannelDeposit.into();
262		// As `set_side`: the recorded depositor, or the payer if nothing is held.
263		let (current, who) = match Deposits::<T>::get((channel, side)) {
264			Some(Deposit { amount, depositor }) => (amount, depositor),
265			None => (0, Self::payer(&channel, side)),
266		};
267		// What the side is missing comes from the migration's hold, what it holds in excess
268		// goes back to it; as much as the hold it comes from has.
269		let (from, to, wanted) = if amount > current {
270			(source, &local, amount - current)
271		} else {
272			(&local, source, current - amount)
273		};
274
275		let moved = wanted.min(T::Currency::balance_on_hold(from, &who));
276		if moved != 0 {
277			// Released from one hold and held again for the other, on the same account.
278			with_storage_layer(|| -> DispatchResult {
279				T::Currency::release(from, &who, moved, Precision::Exact)?;
280				T::Currency::hold(to, &who, moved)
281			})?;
282		}
283		let held = if amount > current {
284			current.saturating_add(moved)
285		} else {
286			current.saturating_sub(moved)
287		};
288
289		if moved != wanted {
290			frame_support::defensive!("hrmp-para: moved holds not as wanted", (wanted, moved));
291		}
292		if held != current {
293			if held == 0 {
294				Deposits::<T>::remove((channel, side));
295			} else {
296				Deposits::<T>::insert((channel, side), Deposit { amount: held, depositor: who });
297			}
298			Self::deposit_event(Event::DepositSet { channel, side, amount: held });
299		}
300		Self::deposit_event(Event::DepositMigrated { channel, side, amount, held });
301		Ok(())
302	}
303
304	fn weight_of_receive_deposit() -> Weight {
305		T::WeightInfo::receive_deposit()
306	}
307}
308
309impl<T: Config> Pallet<T> {
310	/// The account that pays for `side` of `channel` when it holds nothing yet.
311	fn payer(channel: &ChannelId, side: DepositSide) -> T::AccountId {
312		T::SovereignAccountOf::convert(side.para(channel))
313	}
314
315	fn send(message: MessageToRelayV1) -> DispatchResult {
316		T::SendToRelay::send(MessageToRelay::V1(message))
317			.map_err(|()| Error::<T>::SendFailed.into())
318	}
319
320	/// Holds or releases the difference between what `side` holds and `target`.
321	fn set_side(
322		channel: ChannelId,
323		side: DepositSide,
324		target: Balance,
325	) -> Result<(), DepositError> {
326		let reason = HoldReason::ChannelDeposit.into();
327		let (held, who) = match Deposits::<T>::get((channel, side)) {
328			Some(Deposit { amount, depositor }) => (amount, depositor),
329			None => (0, Self::payer(&channel, side)),
330		};
331
332		match target.cmp(&held) {
333			Ordering::Greater => {
334				T::Currency::hold(&reason, &who, target - held).map_err(|e| match e {
335					DispatchError::Token(TokenError::FundsUnavailable) => {
336						DepositError::InsufficientFunds
337					},
338					_ => DepositError::Other,
339				})?;
340			},
341			Ordering::Less => {
342				let to_release = held - target;
343				let released =
344					T::Currency::release(&reason, &who, to_release, Precision::BestEffort)
345						.map_err(|_| DepositError::Other)?;
346				if released != to_release {
347					frame_support::defensive!(
348						"hrmp-para: released less than recorded",
349						(to_release, released)
350					);
351				}
352			},
353			Ordering::Equal => {},
354		}
355
356		if target == 0 {
357			Deposits::<T>::remove((channel, side));
358		} else {
359			Deposits::<T>::insert((channel, side), Deposit { amount: target, depositor: who });
360		}
361		Self::deposit_event(Event::DepositSet { channel, side, amount: target });
362		Ok(())
363	}
364
365	/// Releases everything held for `side`.
366	///
367	/// Nothing held is not an error.
368	fn release_side(channel: ChannelId, side: DepositSide) {
369		let Some(Deposit { amount: held, depositor: who }) = Deposits::<T>::take((channel, side))
370		else {
371			return;
372		};
373		let reason = HoldReason::ChannelDeposit.into();
374
375		let released =
376			T::Currency::release(&reason, &who, held, Precision::BestEffort).unwrap_or_default();
377		if released != held {
378			frame_support::defensive!("hrmp-para: released less than recorded", (held, released));
379		}
380
381		Self::deposit_event(Event::DepositSet { channel, side, amount: 0 });
382	}
383
384	/// Checks that each depositor has exactly its recorded deposits on hold.
385	#[cfg(any(feature = "try-runtime", test))]
386	pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
387		use alloc::collections::btree_map::BTreeMap;
388		let mut per_depositor = BTreeMap::<T::AccountId, Balance>::new();
389
390		for (_, Deposit { amount, depositor }) in Deposits::<T>::iter() {
391			ensure!(amount != 0, "hrmp-para: a side holding nothing is recorded");
392			let total = per_depositor.entry(depositor).or_default();
393			*total = total.saturating_add(amount);
394		}
395
396		for (depositor, recorded) in per_depositor {
397			let on_hold =
398				T::Currency::balance_on_hold(&HoldReason::ChannelDeposit.into(), &depositor);
399			ensure!(on_hold == recorded, "hrmp-para: a depositor's hold differs from its deposits");
400		}
401
402		Ok(())
403	}
404}