pallet_skip_feeless_payment/
lib.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//! # Skip Feeless Payment Pallet
17//!
18//! This pallet allows runtimes that include it to skip payment of transaction fees for
19//! dispatchables marked by
20//! [`#[pallet::feeless_if]`](frame_support::pallet_prelude::feeless_if).
21//!
22//! ## Overview
23//!
24//! It does this by wrapping an existing [`TransactionExtension`] implementation (e.g.
25//! [`pallet-transaction-payment`]) and checking if the dispatchable is feeless before applying the
26//! wrapped extension. If the dispatchable is indeed feeless, the extension is skipped and a custom
27//! event is emitted instead. Otherwise, the extension is applied as usual.
28//!
29//!
30//! ## Integration
31//!
32//! This pallet wraps an existing transaction payment pallet. This means you should both pallets
33//! in your [`construct_runtime`](frame_support::construct_runtime) macro and
34//! include this pallet's [`TransactionExtension`] ([`SkipCheckIfFeeless`]) that would accept the
35//! existing one as an argument.
36
37#![cfg_attr(not(feature = "std"), no_std)]
38
39extern crate alloc;
40
41use codec::{Decode, DecodeWithMemTracking, Encode};
42use frame_support::{
43	dispatch::{CheckIfFeeless, DispatchResult},
44	pallet_prelude::TransactionSource,
45	traits::{IsType, OriginTrait},
46	weights::Weight,
47};
48use scale_info::{StaticTypeInfo, TypeInfo};
49use sp_runtime::{
50	traits::{
51		DispatchInfoOf, DispatchOriginOf, Implication, PostDispatchInfoOf, TransactionExtension,
52		ValidateResult,
53	},
54	transaction_validity::TransactionValidityError,
55};
56
57#[cfg(test)]
58mod mock;
59#[cfg(test)]
60mod tests;
61
62pub use pallet::*;
63
64#[frame_support::pallet]
65pub mod pallet {
66	use super::*;
67
68	#[pallet::config]
69	pub trait Config: frame_system::Config {
70		/// The overarching event type.
71		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
72	}
73
74	#[pallet::pallet]
75	pub struct Pallet<T>(_);
76
77	#[pallet::event]
78	#[pallet::generate_deposit(pub(super) fn deposit_event)]
79	pub enum Event<T: Config> {
80		/// A transaction fee was skipped.
81		FeeSkipped { origin: <T::RuntimeOrigin as OriginTrait>::PalletsOrigin },
82	}
83}
84
85/// A [`TransactionExtension`] that skips the wrapped extension if the dispatchable is feeless.
86#[derive(Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq)]
87pub struct SkipCheckIfFeeless<T, S>(pub S, core::marker::PhantomData<T>);
88
89// Make this extension "invisible" from the outside (ie metadata type information)
90impl<T, S: StaticTypeInfo> TypeInfo for SkipCheckIfFeeless<T, S> {
91	type Identity = S;
92	fn type_info() -> scale_info::Type {
93		S::type_info()
94	}
95}
96
97impl<T, S: Encode> core::fmt::Debug for SkipCheckIfFeeless<T, S> {
98	#[cfg(feature = "std")]
99	fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
100		write!(f, "SkipCheckIfFeeless<{:?}>", self.0.encode())
101	}
102	#[cfg(not(feature = "std"))]
103	fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result {
104		Ok(())
105	}
106}
107
108impl<T, S> From<S> for SkipCheckIfFeeless<T, S> {
109	fn from(s: S) -> Self {
110		Self(s, core::marker::PhantomData)
111	}
112}
113
114pub enum Intermediate<T, O> {
115	/// The wrapped extension should be applied.
116	Apply(T),
117	/// The wrapped extension should be skipped.
118	Skip(O),
119}
120use Intermediate::*;
121
122impl<T: Config + Send + Sync, S: TransactionExtension<T::RuntimeCall>>
123	TransactionExtension<T::RuntimeCall> for SkipCheckIfFeeless<T, S>
124where
125	T::RuntimeCall: CheckIfFeeless<Origin = frame_system::pallet_prelude::OriginFor<T>>,
126{
127	// From the outside this extension should be "invisible", because it just extends the wrapped
128	// extension with an extra check in `pre_dispatch` and `post_dispatch`. Thus, we should forward
129	// the identifier of the wrapped extension to let wallets see this extension as it would only be
130	// the wrapped extension itself.
131	const IDENTIFIER: &'static str = S::IDENTIFIER;
132	type Implicit = S::Implicit;
133
134	fn metadata() -> alloc::vec::Vec<sp_runtime::traits::TransactionExtensionMetadata> {
135		S::metadata()
136	}
137
138	fn implicit(&self) -> Result<Self::Implicit, TransactionValidityError> {
139		self.0.implicit()
140	}
141	type Val =
142		Intermediate<S::Val, <DispatchOriginOf<T::RuntimeCall> as OriginTrait>::PalletsOrigin>;
143	type Pre =
144		Intermediate<S::Pre, <DispatchOriginOf<T::RuntimeCall> as OriginTrait>::PalletsOrigin>;
145
146	fn weight(&self, call: &T::RuntimeCall) -> frame_support::weights::Weight {
147		self.0.weight(call)
148	}
149
150	fn validate(
151		&self,
152		origin: DispatchOriginOf<T::RuntimeCall>,
153		call: &T::RuntimeCall,
154		info: &DispatchInfoOf<T::RuntimeCall>,
155		len: usize,
156		self_implicit: S::Implicit,
157		inherited_implication: &impl Implication,
158		source: TransactionSource,
159	) -> ValidateResult<Self::Val, T::RuntimeCall> {
160		if call.is_feeless(&origin) {
161			Ok((Default::default(), Skip(origin.caller().clone()), origin))
162		} else {
163			let (x, y, z) = self.0.validate(
164				origin,
165				call,
166				info,
167				len,
168				self_implicit,
169				inherited_implication,
170				source,
171			)?;
172			Ok((x, Apply(y), z))
173		}
174	}
175
176	fn prepare(
177		self,
178		val: Self::Val,
179		origin: &DispatchOriginOf<T::RuntimeCall>,
180		call: &T::RuntimeCall,
181		info: &DispatchInfoOf<T::RuntimeCall>,
182		len: usize,
183	) -> Result<Self::Pre, TransactionValidityError> {
184		match val {
185			Apply(val) => self.0.prepare(val, origin, call, info, len).map(Apply),
186			Skip(origin) => Ok(Skip(origin)),
187		}
188	}
189
190	fn post_dispatch_details(
191		pre: Self::Pre,
192		info: &DispatchInfoOf<T::RuntimeCall>,
193		post_info: &PostDispatchInfoOf<T::RuntimeCall>,
194		len: usize,
195		result: &DispatchResult,
196	) -> Result<Weight, TransactionValidityError> {
197		match pre {
198			Apply(pre) => S::post_dispatch_details(pre, info, post_info, len, result),
199			Skip(origin) => {
200				Pallet::<T>::deposit_event(Event::<T>::FeeSkipped { origin });
201				Ok(Weight::zero())
202			},
203		}
204	}
205}