1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
use sp_runtime::{
traits::{
Convert, DispatchInfoOf, Dispatchable, One, PostDispatchInfoOf, SaturatedConversion,
Saturating, SignedExtension, Zero,
},
transaction_validity::{
TransactionPriority, TransactionValidity, TransactionValidityError, ValidTransaction,
},
FixedPointNumber, FixedPointOperand, FixedU128, Perquintill, RuntimeDebug,
};
use sp_std::prelude::*;
use frame_support::{
dispatch::{
DispatchClass, DispatchInfo, DispatchResult, GetDispatchInfo, Pays, PostDispatchInfo,
},
traits::{EstimateCallFee, Get},
weights::{Weight, WeightToFee},
};
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
mod payment;
mod types;
pub use pallet::*;
pub use payment::*;
pub use types::{FeeDetails, InclusionFee, RuntimeDispatchInfo};
pub type Multiplier = FixedU128;
type BalanceOf<T> = <<T as Config>::OnChargeTransaction as OnChargeTransaction<T>>::Balance;
pub struct TargetedFeeAdjustment<T, S, V, M, X>(sp_std::marker::PhantomData<(T, S, V, M, X)>);
pub trait MultiplierUpdate: Convert<Multiplier, Multiplier> {
fn min() -> Multiplier;
fn max() -> Multiplier;
fn target() -> Perquintill;
fn variability() -> Multiplier;
}
impl MultiplierUpdate for () {
fn min() -> Multiplier {
Default::default()
}
fn max() -> Multiplier {
<Multiplier as sp_runtime::traits::Bounded>::max_value()
}
fn target() -> Perquintill {
Default::default()
}
fn variability() -> Multiplier {
Default::default()
}
}
impl<T, S, V, M, X> MultiplierUpdate for TargetedFeeAdjustment<T, S, V, M, X>
where
T: frame_system::Config,
S: Get<Perquintill>,
V: Get<Multiplier>,
M: Get<Multiplier>,
X: Get<Multiplier>,
{
fn min() -> Multiplier {
M::get()
}
fn max() -> Multiplier {
X::get()
}
fn target() -> Perquintill {
S::get()
}
fn variability() -> Multiplier {
V::get()
}
}
impl<T, S, V, M, X> Convert<Multiplier, Multiplier> for TargetedFeeAdjustment<T, S, V, M, X>
where
T: frame_system::Config,
S: Get<Perquintill>,
V: Get<Multiplier>,
M: Get<Multiplier>,
X: Get<Multiplier>,
{
fn convert(previous: Multiplier) -> Multiplier {
let min_multiplier = M::get();
let max_multiplier = X::get();
let previous = previous.max(min_multiplier);
let weights = T::BlockWeights::get();
let normal_max_weight =
weights.get(DispatchClass::Normal).max_total.unwrap_or(weights.max_block);
let current_block_weight = <frame_system::Pallet<T>>::block_weight();
let normal_block_weight =
current_block_weight.get(DispatchClass::Normal).min(normal_max_weight);
let normal_max_weight = normal_max_weight.ref_time();
let normal_block_weight = normal_block_weight.ref_time();
let s = S::get();
let v = V::get();
let target_weight = (s * normal_max_weight) as u128;
let block_weight = normal_block_weight as u128;
let positive = block_weight >= target_weight;
let diff_abs = block_weight.max(target_weight) - block_weight.min(target_weight);
let diff = Multiplier::saturating_from_rational(diff_abs, normal_max_weight.max(1));
let diff_squared = diff.saturating_mul(diff);
let v_squared_2 = v.saturating_mul(v) / Multiplier::saturating_from_integer(2);
let first_term = v.saturating_mul(diff);
let second_term = v_squared_2.saturating_mul(diff_squared);
if positive {
let excess = first_term.saturating_add(second_term).saturating_mul(previous);
previous.saturating_add(excess).clamp(min_multiplier, max_multiplier)
} else {
let negative = first_term.saturating_sub(second_term).saturating_mul(previous);
previous.saturating_sub(negative).clamp(min_multiplier, max_multiplier)
}
}
}
pub struct ConstFeeMultiplier<M: Get<Multiplier>>(sp_std::marker::PhantomData<M>);
impl<M: Get<Multiplier>> MultiplierUpdate for ConstFeeMultiplier<M> {
fn min() -> Multiplier {
M::get()
}
fn max() -> Multiplier {
M::get()
}
fn target() -> Perquintill {
Default::default()
}
fn variability() -> Multiplier {
Default::default()
}
}
impl<M> Convert<Multiplier, Multiplier> for ConstFeeMultiplier<M>
where
M: Get<Multiplier>,
{
fn convert(_previous: Multiplier) -> Multiplier {
Self::min()
}
}
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
enum Releases {
V1Ancient,
V2,
}
impl Default for Releases {
fn default() -> Self {
Releases::V1Ancient
}
}
const MULTIPLIER_DEFAULT_VALUE: Multiplier = Multiplier::from_u32(1);
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type OnChargeTransaction: OnChargeTransaction<Self>;
#[pallet::constant]
type OperationalFeeMultiplier: Get<u8>;
type WeightToFee: WeightToFee<Balance = BalanceOf<Self>>;
type LengthToFee: WeightToFee<Balance = BalanceOf<Self>>;
type FeeMultiplierUpdate: MultiplierUpdate;
}
#[pallet::type_value]
pub fn NextFeeMultiplierOnEmpty() -> Multiplier {
MULTIPLIER_DEFAULT_VALUE
}
#[pallet::storage]
#[pallet::getter(fn next_fee_multiplier)]
pub type NextFeeMultiplier<T: Config> =
StorageValue<_, Multiplier, ValueQuery, NextFeeMultiplierOnEmpty>;
#[pallet::storage]
pub(super) type StorageVersion<T: Config> = StorageValue<_, Releases, ValueQuery>;
#[pallet::genesis_config]
pub struct GenesisConfig {
pub multiplier: Multiplier,
}
#[cfg(feature = "std")]
impl Default for GenesisConfig {
fn default() -> Self {
Self { multiplier: MULTIPLIER_DEFAULT_VALUE }
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
StorageVersion::<T>::put(Releases::V2);
NextFeeMultiplier::<T>::put(self.multiplier);
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
TransactionFeePaid { who: T::AccountId, actual_fee: BalanceOf<T>, tip: BalanceOf<T> },
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_finalize(_: T::BlockNumber) {
<NextFeeMultiplier<T>>::mutate(|fm| {
*fm = T::FeeMultiplierUpdate::convert(*fm);
});
}
fn integrity_test() {
assert!(
<Multiplier as sp_runtime::traits::Bounded>::max_value() >=
Multiplier::checked_from_integer::<u128>(
T::BlockWeights::get().max_block.ref_time().try_into().unwrap()
)
.unwrap(),
);
let target = T::FeeMultiplierUpdate::target() *
T::BlockWeights::get().get(DispatchClass::Normal).max_total.expect(
"Setting `max_total` for `Normal` dispatch class is not compatible with \
`transaction-payment` pallet.",
);
let addition = target / 100;
if addition == Weight::zero() {
return
}
#[cfg(any(feature = "std", test))]
sp_io::TestExternalities::new_empty().execute_with(|| {
let min_value = T::FeeMultiplierUpdate::min();
let target = target + addition;
<frame_system::Pallet<T>>::set_block_consumed_resources(target, 0);
let next = T::FeeMultiplierUpdate::convert(min_value);
assert!(
next > min_value,
"The minimum bound of the multiplier is too low. When \
block saturation is more than target by 1% and multiplier is minimal then \
the multiplier doesn't increase."
);
});
}
}
}
impl<T: Config> Pallet<T>
where
BalanceOf<T>: FixedPointOperand,
{
pub fn query_info<Extrinsic: sp_runtime::traits::Extrinsic + GetDispatchInfo>(
unchecked_extrinsic: Extrinsic,
len: u32,
) -> RuntimeDispatchInfo<BalanceOf<T>>
where
T::RuntimeCall: Dispatchable<Info = DispatchInfo>,
{
let dispatch_info = <Extrinsic as GetDispatchInfo>::get_dispatch_info(&unchecked_extrinsic);
let partial_fee = if unchecked_extrinsic.is_signed().unwrap_or(false) {
Self::compute_fee(len, &dispatch_info, 0u32.into())
} else {
0u32.into()
};
let DispatchInfo { weight, class, .. } = dispatch_info;
RuntimeDispatchInfo { weight, class, partial_fee }
}
pub fn query_fee_details<Extrinsic: sp_runtime::traits::Extrinsic + GetDispatchInfo>(
unchecked_extrinsic: Extrinsic,
len: u32,
) -> FeeDetails<BalanceOf<T>>
where
T::RuntimeCall: Dispatchable<Info = DispatchInfo>,
{
let dispatch_info = <Extrinsic as GetDispatchInfo>::get_dispatch_info(&unchecked_extrinsic);
let tip = 0u32.into();
if unchecked_extrinsic.is_signed().unwrap_or(false) {
Self::compute_fee_details(len, &dispatch_info, tip)
} else {
FeeDetails { inclusion_fee: None, tip }
}
}
pub fn query_call_info(call: T::RuntimeCall, len: u32) -> RuntimeDispatchInfo<BalanceOf<T>>
where
T::RuntimeCall: Dispatchable<Info = DispatchInfo> + GetDispatchInfo,
{
let dispatch_info = <T::RuntimeCall as GetDispatchInfo>::get_dispatch_info(&call);
let DispatchInfo { weight, class, .. } = dispatch_info;
RuntimeDispatchInfo {
weight,
class,
partial_fee: Self::compute_fee(len, &dispatch_info, 0u32.into()),
}
}
pub fn query_call_fee_details(call: T::RuntimeCall, len: u32) -> FeeDetails<BalanceOf<T>>
where
T::RuntimeCall: Dispatchable<Info = DispatchInfo> + GetDispatchInfo,
{
let dispatch_info = <T::RuntimeCall as GetDispatchInfo>::get_dispatch_info(&call);
let tip = 0u32.into();
Self::compute_fee_details(len, &dispatch_info, tip)
}
pub fn compute_fee(
len: u32,
info: &DispatchInfoOf<T::RuntimeCall>,
tip: BalanceOf<T>,
) -> BalanceOf<T>
where
T::RuntimeCall: Dispatchable<Info = DispatchInfo>,
{
Self::compute_fee_details(len, info, tip).final_fee()
}
pub fn compute_fee_details(
len: u32,
info: &DispatchInfoOf<T::RuntimeCall>,
tip: BalanceOf<T>,
) -> FeeDetails<BalanceOf<T>>
where
T::RuntimeCall: Dispatchable<Info = DispatchInfo>,
{
Self::compute_fee_raw(len, info.weight, tip, info.pays_fee, info.class)
}
pub fn compute_actual_fee(
len: u32,
info: &DispatchInfoOf<T::RuntimeCall>,
post_info: &PostDispatchInfoOf<T::RuntimeCall>,
tip: BalanceOf<T>,
) -> BalanceOf<T>
where
T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
{
Self::compute_actual_fee_details(len, info, post_info, tip).final_fee()
}
pub fn compute_actual_fee_details(
len: u32,
info: &DispatchInfoOf<T::RuntimeCall>,
post_info: &PostDispatchInfoOf<T::RuntimeCall>,
tip: BalanceOf<T>,
) -> FeeDetails<BalanceOf<T>>
where
T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
{
Self::compute_fee_raw(
len,
post_info.calc_actual_weight(info),
tip,
post_info.pays_fee(info),
info.class,
)
}
fn compute_fee_raw(
len: u32,
weight: Weight,
tip: BalanceOf<T>,
pays_fee: Pays,
class: DispatchClass,
) -> FeeDetails<BalanceOf<T>> {
if pays_fee == Pays::Yes {
let unadjusted_weight_fee = Self::weight_to_fee(weight);
let multiplier = Self::next_fee_multiplier();
let adjusted_weight_fee = multiplier.saturating_mul_int(unadjusted_weight_fee);
let len_fee = Self::length_to_fee(len);
let base_fee = Self::weight_to_fee(T::BlockWeights::get().get(class).base_extrinsic);
FeeDetails {
inclusion_fee: Some(InclusionFee { base_fee, len_fee, adjusted_weight_fee }),
tip,
}
} else {
FeeDetails { inclusion_fee: None, tip }
}
}
pub fn length_to_fee(length: u32) -> BalanceOf<T> {
T::LengthToFee::weight_to_fee(&Weight::from_ref_time(length as u64))
}
pub fn weight_to_fee(weight: Weight) -> BalanceOf<T> {
let capped_weight = weight.min(T::BlockWeights::get().max_block);
T::WeightToFee::weight_to_fee(&capped_weight)
}
}
impl<T> Convert<Weight, BalanceOf<T>> for Pallet<T>
where
T: Config,
BalanceOf<T>: FixedPointOperand,
{
fn convert(weight: Weight) -> BalanceOf<T> {
<NextFeeMultiplier<T>>::get().saturating_mul_int(Self::weight_to_fee(weight))
}
}
#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct ChargeTransactionPayment<T: Config>(#[codec(compact)] BalanceOf<T>);
impl<T: Config> ChargeTransactionPayment<T>
where
T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
BalanceOf<T>: Send + Sync + FixedPointOperand,
{
pub fn from(fee: BalanceOf<T>) -> Self {
Self(fee)
}
pub fn tip(&self) -> BalanceOf<T> {
self.0
}
fn withdraw_fee(
&self,
who: &T::AccountId,
call: &T::RuntimeCall,
info: &DispatchInfoOf<T::RuntimeCall>,
len: usize,
) -> Result<
(
BalanceOf<T>,
<<T as Config>::OnChargeTransaction as OnChargeTransaction<T>>::LiquidityInfo,
),
TransactionValidityError,
> {
let tip = self.0;
let fee = Pallet::<T>::compute_fee(len as u32, info, tip);
<<T as Config>::OnChargeTransaction as OnChargeTransaction<T>>::withdraw_fee(
who, call, info, fee, tip,
)
.map(|i| (fee, i))
}
pub fn get_priority(
info: &DispatchInfoOf<T::RuntimeCall>,
len: usize,
tip: BalanceOf<T>,
final_fee: BalanceOf<T>,
) -> TransactionPriority {
let max_block_weight = T::BlockWeights::get().max_block;
let max_block_length = *T::BlockLength::get().max.get(info.class) as u64;
let max_block_weight = max_block_weight.ref_time();
let info_weight = info.weight.ref_time();
let bounded_weight = info_weight.clamp(1, max_block_weight);
let bounded_length = (len as u64).clamp(1, max_block_length);
let max_tx_per_block_weight = max_block_weight / bounded_weight;
let max_tx_per_block_length = max_block_length / bounded_length;
let max_tx_per_block = max_tx_per_block_length
.min(max_tx_per_block_weight)
.saturated_into::<BalanceOf<T>>();
let max_reward = |val: BalanceOf<T>| val.saturating_mul(max_tx_per_block);
let tip = tip.saturating_add(One::one());
let scaled_tip = max_reward(tip);
match info.class {
DispatchClass::Normal => {
scaled_tip
},
DispatchClass::Mandatory => {
scaled_tip
},
DispatchClass::Operational => {
let fee_multiplier = T::OperationalFeeMultiplier::get().saturated_into();
let virtual_tip = final_fee.saturating_mul(fee_multiplier);
let scaled_virtual_tip = max_reward(virtual_tip);
scaled_tip.saturating_add(scaled_virtual_tip)
},
}
.saturated_into::<TransactionPriority>()
}
}
impl<T: Config> sp_std::fmt::Debug for ChargeTransactionPayment<T> {
#[cfg(feature = "std")]
fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
write!(f, "ChargeTransactionPayment<{:?}>", self.0)
}
#[cfg(not(feature = "std"))]
fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
Ok(())
}
}
impl<T: Config> SignedExtension for ChargeTransactionPayment<T>
where
BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,
T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
{
const IDENTIFIER: &'static str = "ChargeTransactionPayment";
type AccountId = T::AccountId;
type Call = T::RuntimeCall;
type AdditionalSigned = ();
type Pre = (
BalanceOf<T>,
Self::AccountId,
<<T as Config>::OnChargeTransaction as OnChargeTransaction<T>>::LiquidityInfo,
);
fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {
Ok(())
}
fn validate(
&self,
who: &Self::AccountId,
call: &Self::Call,
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> TransactionValidity {
let (final_fee, _) = self.withdraw_fee(who, call, info, len)?;
let tip = self.0;
Ok(ValidTransaction {
priority: Self::get_priority(info, len, tip, final_fee),
..Default::default()
})
}
fn pre_dispatch(
self,
who: &Self::AccountId,
call: &Self::Call,
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
let (_fee, imbalance) = self.withdraw_fee(who, call, info, len)?;
Ok((self.0, who.clone(), imbalance))
}
fn post_dispatch(
maybe_pre: Option<Self::Pre>,
info: &DispatchInfoOf<Self::Call>,
post_info: &PostDispatchInfoOf<Self::Call>,
len: usize,
_result: &DispatchResult,
) -> Result<(), TransactionValidityError> {
if let Some((tip, who, imbalance)) = maybe_pre {
let actual_fee = Pallet::<T>::compute_actual_fee(len as u32, info, post_info, tip);
T::OnChargeTransaction::correct_and_deposit_fee(
&who, info, post_info, actual_fee, tip, imbalance,
)?;
Pallet::<T>::deposit_event(Event::<T>::TransactionFeePaid { who, actual_fee, tip });
}
Ok(())
}
}
impl<T: Config, AnyCall: GetDispatchInfo + Encode> EstimateCallFee<AnyCall, BalanceOf<T>>
for Pallet<T>
where
BalanceOf<T>: FixedPointOperand,
T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
{
fn estimate_call_fee(call: &AnyCall, post_info: PostDispatchInfo) -> BalanceOf<T> {
let len = call.encoded_size() as u32;
let info = call.get_dispatch_info();
Self::compute_actual_fee(len, &info, &post_info, Zero::zero())
}
}