pallet-transaction-payment 21.1.0-dev.6

FRAME pallet to manage transaction payments
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
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::*;
use crate as pallet_transaction_payment;

use codec::Encode;

use sp_runtime::{
	testing::TestXt, traits::One, transaction_validity::InvalidTransaction, BuildStorage,
};

use frame_support::{
	assert_noop, assert_ok,
	dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, PostDispatchInfo},
	traits::Currency,
	weights::Weight,
};
use frame_system as system;
use mock::*;
use pallet_balances::Call as BalancesCall;

pub struct ExtBuilder {
	balance_factor: u64,
	base_weight: Weight,
	byte_fee: u64,
	weight_to_fee: u64,
	initial_multiplier: Option<Multiplier>,
}

impl Default for ExtBuilder {
	fn default() -> Self {
		Self {
			balance_factor: 1,
			base_weight: Weight::zero(),
			byte_fee: 1,
			weight_to_fee: 1,
			initial_multiplier: None,
		}
	}
}

impl ExtBuilder {
	pub fn base_weight(mut self, base_weight: Weight) -> Self {
		self.base_weight = base_weight;
		self
	}
	pub fn byte_fee(mut self, byte_fee: u64) -> Self {
		self.byte_fee = byte_fee;
		self
	}
	pub fn weight_fee(mut self, weight_to_fee: u64) -> Self {
		self.weight_to_fee = weight_to_fee;
		self
	}
	pub fn balance_factor(mut self, factor: u64) -> Self {
		self.balance_factor = factor;
		self
	}
	pub fn with_initial_multiplier(mut self, multiplier: Multiplier) -> Self {
		self.initial_multiplier = Some(multiplier);
		self
	}
	fn set_constants(&self) {
		ExtrinsicBaseWeight::mutate(|v| *v = self.base_weight);
		TRANSACTION_BYTE_FEE.with(|v| *v.borrow_mut() = self.byte_fee);
		WEIGHT_TO_FEE.with(|v| *v.borrow_mut() = self.weight_to_fee);
	}
	pub fn build(self) -> sp_io::TestExternalities {
		self.set_constants();
		let mut t = frame_system::GenesisConfig::<Runtime>::default().build_storage().unwrap();
		pallet_balances::GenesisConfig::<Runtime> {
			balances: if self.balance_factor > 0 {
				vec![
					(1, 10 * self.balance_factor),
					(2, 20 * self.balance_factor),
					(3, 30 * self.balance_factor),
					(4, 40 * self.balance_factor),
					(5, 50 * self.balance_factor),
					(6, 60 * self.balance_factor),
				]
			} else {
				vec![]
			},
		}
		.assimilate_storage(&mut t)
		.unwrap();

		if let Some(multiplier) = self.initial_multiplier {
			pallet::GenesisConfig::<Runtime> { multiplier, ..Default::default() }
				.assimilate_storage(&mut t)
				.unwrap();
		}

		t.into()
	}
}

/// create a transaction info struct from weight. Handy to avoid building the whole struct.
pub fn info_from_weight(w: Weight) -> DispatchInfo {
	// pays_fee: Pays::Yes -- class: DispatchClass::Normal
	DispatchInfo { weight: w, ..Default::default() }
}

fn post_info_from_weight(w: Weight) -> PostDispatchInfo {
	PostDispatchInfo { actual_weight: Some(w), pays_fee: Default::default() }
}

fn post_info_from_pays(p: Pays) -> PostDispatchInfo {
	PostDispatchInfo { actual_weight: None, pays_fee: p }
}

fn default_post_info() -> PostDispatchInfo {
	PostDispatchInfo { actual_weight: None, pays_fee: Default::default() }
}

#[test]
fn signed_extension_transaction_payment_work() {
	ExtBuilder::default()
		.balance_factor(10)
		.base_weight(Weight::from_parts(5, 0))
		.build()
		.execute_with(|| {
			let len = 10;
			let pre = ChargeTransactionPayment::<Runtime>::from(0)
				.pre_dispatch(&1, CALL, &info_from_weight(Weight::from_parts(5, 0)), len)
				.unwrap();
			assert_eq!(Balances::free_balance(1), 100 - 5 - 5 - 10);

			assert_ok!(ChargeTransactionPayment::<Runtime>::post_dispatch(
				Some(pre),
				&info_from_weight(Weight::from_parts(5, 0)),
				&default_post_info(),
				len,
				&Ok(())
			));
			assert_eq!(Balances::free_balance(1), 100 - 5 - 5 - 10);
			assert_eq!(FeeUnbalancedAmount::get(), 5 + 5 + 10);
			assert_eq!(TipUnbalancedAmount::get(), 0);

			FeeUnbalancedAmount::mutate(|a| *a = 0);

			let pre = ChargeTransactionPayment::<Runtime>::from(5 /* tipped */)
				.pre_dispatch(&2, CALL, &info_from_weight(Weight::from_parts(100, 0)), len)
				.unwrap();
			assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 100 - 5);

			assert_ok!(ChargeTransactionPayment::<Runtime>::post_dispatch(
				Some(pre),
				&info_from_weight(Weight::from_parts(100, 0)),
				&post_info_from_weight(Weight::from_parts(50, 0)),
				len,
				&Ok(())
			));
			assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 50 - 5);
			assert_eq!(FeeUnbalancedAmount::get(), 5 + 10 + 50);
			assert_eq!(TipUnbalancedAmount::get(), 5);
		});
}

#[test]
fn signed_extension_transaction_payment_multiplied_refund_works() {
	ExtBuilder::default()
		.balance_factor(10)
		.base_weight(Weight::from_parts(5, 0))
		.build()
		.execute_with(|| {
			let len = 10;
			<NextFeeMultiplier<Runtime>>::put(Multiplier::saturating_from_rational(3, 2));

			let pre = ChargeTransactionPayment::<Runtime>::from(5 /* tipped */)
				.pre_dispatch(&2, CALL, &info_from_weight(Weight::from_parts(100, 0)), len)
				.unwrap();
			// 5 base fee, 10 byte fee, 3/2 * 100 weight fee, 5 tip
			assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 150 - 5);

			assert_ok!(ChargeTransactionPayment::<Runtime>::post_dispatch(
				Some(pre),
				&info_from_weight(Weight::from_parts(100, 0)),
				&post_info_from_weight(Weight::from_parts(50, 0)),
				len,
				&Ok(())
			));
			// 75 (3/2 of the returned 50 units of weight) is refunded
			assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 75 - 5);
		});
}

#[test]
fn signed_extension_transaction_payment_is_bounded() {
	ExtBuilder::default().balance_factor(1000).byte_fee(0).build().execute_with(|| {
		// maximum weight possible
		assert_ok!(ChargeTransactionPayment::<Runtime>::from(0).pre_dispatch(
			&1,
			CALL,
			&info_from_weight(Weight::MAX),
			10
		));
		// fee will be proportional to what is the actual maximum weight in the runtime.
		assert_eq!(
			Balances::free_balance(&1),
			(10000 - <Runtime as frame_system::Config>::BlockWeights::get().max_block.ref_time())
				as u64
		);
	});
}

#[test]
fn signed_extension_allows_free_transactions() {
	ExtBuilder::default()
		.base_weight(Weight::from_parts(100, 0))
		.balance_factor(0)
		.build()
		.execute_with(|| {
			// 1 ain't have a penny.
			assert_eq!(Balances::free_balance(1), 0);

			let len = 100;

			// This is a completely free (and thus wholly insecure/DoS-ridden) transaction.
			let operational_transaction = DispatchInfo {
				weight: Weight::from_parts(0, 0),
				class: DispatchClass::Operational,
				pays_fee: Pays::No,
			};
			assert_ok!(ChargeTransactionPayment::<Runtime>::from(0).validate(
				&1,
				CALL,
				&operational_transaction,
				len
			));

			// like a InsecureFreeNormal
			let free_transaction = DispatchInfo {
				weight: Weight::from_parts(0, 0),
				class: DispatchClass::Normal,
				pays_fee: Pays::Yes,
			};
			assert_noop!(
				ChargeTransactionPayment::<Runtime>::from(0).validate(
					&1,
					CALL,
					&free_transaction,
					len
				),
				TransactionValidityError::Invalid(InvalidTransaction::Payment),
			);
		});
}

#[test]
fn signed_ext_length_fee_is_also_updated_per_congestion() {
	ExtBuilder::default()
		.base_weight(Weight::from_parts(5, 0))
		.balance_factor(10)
		.build()
		.execute_with(|| {
			// all fees should be x1.5
			<NextFeeMultiplier<Runtime>>::put(Multiplier::saturating_from_rational(3, 2));
			let len = 10;

			assert_ok!(ChargeTransactionPayment::<Runtime>::from(10) // tipped
				.pre_dispatch(&1, CALL, &info_from_weight(Weight::from_parts(3, 0)), len));
			assert_eq!(
				Balances::free_balance(1),
				100 // original
            - 10 // tip
            - 5 // base
            - 10 // len
            - (3 * 3 / 2) // adjusted weight
			);
		})
}

#[test]
fn query_info_and_fee_details_works() {
	let call = RuntimeCall::Balances(BalancesCall::transfer_allow_death { dest: 2, value: 69 });
	let origin = 111111;
	let extra = ();
	let xt = TestXt::new(call.clone(), Some((origin, extra)));
	let info = xt.get_dispatch_info();
	let ext = xt.encode();
	let len = ext.len() as u32;

	let unsigned_xt = TestXt::<_, ()>::new(call, None);
	let unsigned_xt_info = unsigned_xt.get_dispatch_info();

	ExtBuilder::default()
        .base_weight(Weight::from_parts(5, 0))
        .weight_fee(2)
        .build()
        .execute_with(|| {
            // all fees should be x1.5
            <NextFeeMultiplier<Runtime>>::put(Multiplier::saturating_from_rational(3, 2));

            assert_eq!(
                TransactionPayment::query_info(xt.clone(), len),
                RuntimeDispatchInfo {
                    weight: info.weight,
                    class: info.class,
                    partial_fee: 5 * 2 /* base * weight_fee */
                    + len as u64  /* len * 1 */
                    + info.weight.min(BlockWeights::get().max_block).ref_time() as u64 * 2 * 3 / 2 /* weight */
                },
            );

            assert_eq!(
                TransactionPayment::query_info(unsigned_xt.clone(), len),
                RuntimeDispatchInfo {
                    weight: unsigned_xt_info.weight,
                    class: unsigned_xt_info.class,
                    partial_fee: 0,
                },
            );

            assert_eq!(
                TransactionPayment::query_fee_details(xt, len),
                FeeDetails {
                    inclusion_fee: Some(InclusionFee {
                        base_fee: 5 * 2,
                        len_fee: len as u64,
                        adjusted_weight_fee: info
                            .weight
                            .min(BlockWeights::get().max_block)
                            .ref_time() as u64 * 2 * 3 / 2
                    }),
                    tip: 0,
                },
            );

            assert_eq!(
                TransactionPayment::query_fee_details(unsigned_xt, len),
                FeeDetails { inclusion_fee: None, tip: 0 },
            );
        });
}

#[test]
fn query_call_info_and_fee_details_works() {
	let call = RuntimeCall::Balances(BalancesCall::transfer_allow_death { dest: 2, value: 69 });
	let info = call.get_dispatch_info();
	let encoded_call = call.encode();
	let len = encoded_call.len() as u32;

	ExtBuilder::default()
        .base_weight(Weight::from_parts(5, 0))
        .weight_fee(2)
        .build()
        .execute_with(|| {
            // all fees should be x1.5
            <NextFeeMultiplier<Runtime>>::put(Multiplier::saturating_from_rational(3, 2));

            assert_eq!(
                TransactionPayment::query_call_info(call.clone(), len),
                RuntimeDispatchInfo {
                    weight: info.weight,
                    class: info.class,
                    partial_fee: 5 * 2 /* base * weight_fee */
                    + len as u64  /* len * 1 */
                    + info.weight.min(BlockWeights::get().max_block).ref_time() as u64 * 2 * 3 / 2 /* weight */
                },
            );

            assert_eq!(
                TransactionPayment::query_call_fee_details(call, len),
                FeeDetails {
                    inclusion_fee: Some(InclusionFee {
                        base_fee: 5 * 2,     /* base * weight_fee */
                        len_fee: len as u64, /* len * 1 */
                        adjusted_weight_fee: info
                            .weight
                            .min(BlockWeights::get().max_block)
                            .ref_time() as u64 * 2 * 3 / 2  /* weight * weight_fee * multipler */
                    }),
                    tip: 0,
                },
            );
        });
}

#[test]
fn compute_fee_works_without_multiplier() {
	ExtBuilder::default()
		.base_weight(Weight::from_parts(100, 0))
		.byte_fee(10)
		.balance_factor(0)
		.build()
		.execute_with(|| {
			// Next fee multiplier is zero
			assert_eq!(<NextFeeMultiplier<Runtime>>::get(), Multiplier::one());

			// Tip only, no fees works
			let dispatch_info = DispatchInfo {
				weight: Weight::from_parts(0, 0),
				class: DispatchClass::Operational,
				pays_fee: Pays::No,
			};
			assert_eq!(Pallet::<Runtime>::compute_fee(0, &dispatch_info, 10), 10);
			// No tip, only base fee works
			let dispatch_info = DispatchInfo {
				weight: Weight::from_parts(0, 0),
				class: DispatchClass::Operational,
				pays_fee: Pays::Yes,
			};
			assert_eq!(Pallet::<Runtime>::compute_fee(0, &dispatch_info, 0), 100);
			// Tip + base fee works
			assert_eq!(Pallet::<Runtime>::compute_fee(0, &dispatch_info, 69), 169);
			// Len (byte fee) + base fee works
			assert_eq!(Pallet::<Runtime>::compute_fee(42, &dispatch_info, 0), 520);
			// Weight fee + base fee works
			let dispatch_info = DispatchInfo {
				weight: Weight::from_parts(1000, 0),
				class: DispatchClass::Operational,
				pays_fee: Pays::Yes,
			};
			assert_eq!(Pallet::<Runtime>::compute_fee(0, &dispatch_info, 0), 1100);
		});
}

#[test]
fn compute_fee_works_with_multiplier() {
	ExtBuilder::default()
		.base_weight(Weight::from_parts(100, 0))
		.byte_fee(10)
		.balance_factor(0)
		.build()
		.execute_with(|| {
			// Add a next fee multiplier. Fees will be x3/2.
			<NextFeeMultiplier<Runtime>>::put(Multiplier::saturating_from_rational(3, 2));
			// Base fee is unaffected by multiplier
			let dispatch_info = DispatchInfo {
				weight: Weight::from_parts(0, 0),
				class: DispatchClass::Operational,
				pays_fee: Pays::Yes,
			};
			assert_eq!(Pallet::<Runtime>::compute_fee(0, &dispatch_info, 0), 100);

			// Everything works together :)
			let dispatch_info = DispatchInfo {
				weight: Weight::from_parts(123, 0),
				class: DispatchClass::Operational,
				pays_fee: Pays::Yes,
			};
			// 123 weight, 456 length, 100 base
			assert_eq!(
				Pallet::<Runtime>::compute_fee(456, &dispatch_info, 789),
				100 + (3 * 123 / 2) + 4560 + 789,
			);
		});
}

#[test]
fn compute_fee_works_with_negative_multiplier() {
	ExtBuilder::default()
		.base_weight(Weight::from_parts(100, 0))
		.byte_fee(10)
		.balance_factor(0)
		.build()
		.execute_with(|| {
			// Add a next fee multiplier. All fees will be x1/2.
			<NextFeeMultiplier<Runtime>>::put(Multiplier::saturating_from_rational(1, 2));

			// Base fee is unaffected by multiplier.
			let dispatch_info = DispatchInfo {
				weight: Weight::from_parts(0, 0),
				class: DispatchClass::Operational,
				pays_fee: Pays::Yes,
			};
			assert_eq!(Pallet::<Runtime>::compute_fee(0, &dispatch_info, 0), 100);

			// Everything works together.
			let dispatch_info = DispatchInfo {
				weight: Weight::from_parts(123, 0),
				class: DispatchClass::Operational,
				pays_fee: Pays::Yes,
			};
			// 123 weight, 456 length, 100 base
			assert_eq!(
				Pallet::<Runtime>::compute_fee(456, &dispatch_info, 789),
				100 + (123 / 2) + 4560 + 789,
			);
		});
}

#[test]
fn compute_fee_does_not_overflow() {
	ExtBuilder::default()
		.base_weight(Weight::from_parts(100, 0))
		.byte_fee(10)
		.balance_factor(0)
		.build()
		.execute_with(|| {
			// Overflow is handled
			let dispatch_info = DispatchInfo {
				weight: Weight::MAX,
				class: DispatchClass::Operational,
				pays_fee: Pays::Yes,
			};
			assert_eq!(
				Pallet::<Runtime>::compute_fee(u32::MAX, &dispatch_info, u64::MAX),
				u64::MAX
			);
		});
}

#[test]
fn refund_does_not_recreate_account() {
	ExtBuilder::default()
		.balance_factor(10)
		.base_weight(Weight::from_parts(5, 0))
		.build()
		.execute_with(|| {
			// So events are emitted
			System::set_block_number(10);
			let len = 10;
			let pre = ChargeTransactionPayment::<Runtime>::from(5 /* tipped */)
				.pre_dispatch(&2, CALL, &info_from_weight(Weight::from_parts(100, 0)), len)
				.unwrap();
			assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 100 - 5);

			// kill the account between pre and post dispatch
			assert_ok!(Balances::transfer_allow_death(
				Some(2).into(),
				3,
				Balances::free_balance(2)
			));
			assert_eq!(Balances::free_balance(2), 0);

			assert_ok!(ChargeTransactionPayment::<Runtime>::post_dispatch(
				Some(pre),
				&info_from_weight(Weight::from_parts(100, 0)),
				&post_info_from_weight(Weight::from_parts(50, 0)),
				len,
				&Ok(())
			));
			assert_eq!(Balances::free_balance(2), 0);
			// Transfer Event
			System::assert_has_event(RuntimeEvent::Balances(pallet_balances::Event::Transfer {
				from: 2,
				to: 3,
				amount: 80,
			}));
			// Killed Event
			System::assert_has_event(RuntimeEvent::System(system::Event::KilledAccount {
				account: 2,
			}));
		});
}

#[test]
fn actual_weight_higher_than_max_refunds_nothing() {
	ExtBuilder::default()
		.balance_factor(10)
		.base_weight(Weight::from_parts(5, 0))
		.build()
		.execute_with(|| {
			let len = 10;
			let pre = ChargeTransactionPayment::<Runtime>::from(5 /* tipped */)
				.pre_dispatch(&2, CALL, &info_from_weight(Weight::from_parts(100, 0)), len)
				.unwrap();
			assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 100 - 5);

			assert_ok!(ChargeTransactionPayment::<Runtime>::post_dispatch(
				Some(pre),
				&info_from_weight(Weight::from_parts(100, 0)),
				&post_info_from_weight(Weight::from_parts(101, 0)),
				len,
				&Ok(())
			));
			assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 100 - 5);
		});
}

#[test]
fn zero_transfer_on_free_transaction() {
	ExtBuilder::default()
		.balance_factor(10)
		.base_weight(Weight::from_parts(5, 0))
		.build()
		.execute_with(|| {
			// So events are emitted
			System::set_block_number(10);
			let len = 10;
			let dispatch_info = DispatchInfo {
				weight: Weight::from_parts(100, 0),
				pays_fee: Pays::No,
				class: DispatchClass::Normal,
			};
			let user = 69;
			let pre = ChargeTransactionPayment::<Runtime>::from(0)
				.pre_dispatch(&user, CALL, &dispatch_info, len)
				.unwrap();
			assert_eq!(Balances::total_balance(&user), 0);
			assert_ok!(ChargeTransactionPayment::<Runtime>::post_dispatch(
				Some(pre),
				&dispatch_info,
				&default_post_info(),
				len,
				&Ok(())
			));
			assert_eq!(Balances::total_balance(&user), 0);
			// TransactionFeePaid Event
			System::assert_has_event(RuntimeEvent::TransactionPayment(
				pallet_transaction_payment::Event::TransactionFeePaid {
					who: user,
					actual_fee: 0,
					tip: 0,
				},
			));
		});
}

#[test]
fn refund_consistent_with_actual_weight() {
	ExtBuilder::default()
		.balance_factor(10)
		.base_weight(Weight::from_parts(7, 0))
		.build()
		.execute_with(|| {
			let info = info_from_weight(Weight::from_parts(100, 0));
			let post_info = post_info_from_weight(Weight::from_parts(33, 0));
			let prev_balance = Balances::free_balance(2);
			let len = 10;
			let tip = 5;

			<NextFeeMultiplier<Runtime>>::put(Multiplier::saturating_from_rational(5, 4));

			let pre = ChargeTransactionPayment::<Runtime>::from(tip)
				.pre_dispatch(&2, CALL, &info, len)
				.unwrap();

			ChargeTransactionPayment::<Runtime>::post_dispatch(
				Some(pre),
				&info,
				&post_info,
				len,
				&Ok(()),
			)
			.unwrap();

			let refund_based_fee = prev_balance - Balances::free_balance(2);
			let actual_fee =
				Pallet::<Runtime>::compute_actual_fee(len as u32, &info, &post_info, tip);

			// 33 weight, 10 length, 7 base, 5 tip
			assert_eq!(actual_fee, 7 + 10 + (33 * 5 / 4) + 5);
			assert_eq!(refund_based_fee, actual_fee);
		});
}

#[test]
fn should_alter_operational_priority() {
	let tip = 5;
	let len = 10;

	ExtBuilder::default().balance_factor(100).build().execute_with(|| {
		let normal = DispatchInfo {
			weight: Weight::from_parts(100, 0),
			class: DispatchClass::Normal,
			pays_fee: Pays::Yes,
		};
		let priority = ChargeTransactionPayment::<Runtime>(tip)
			.validate(&2, CALL, &normal, len)
			.unwrap()
			.priority;

		assert_eq!(priority, 60);

		let priority = ChargeTransactionPayment::<Runtime>(2 * tip)
			.validate(&2, CALL, &normal, len)
			.unwrap()
			.priority;

		assert_eq!(priority, 110);
	});

	ExtBuilder::default().balance_factor(100).build().execute_with(|| {
		let op = DispatchInfo {
			weight: Weight::from_parts(100, 0),
			class: DispatchClass::Operational,
			pays_fee: Pays::Yes,
		};
		let priority = ChargeTransactionPayment::<Runtime>(tip)
			.validate(&2, CALL, &op, len)
			.unwrap()
			.priority;
		assert_eq!(priority, 5810);

		let priority = ChargeTransactionPayment::<Runtime>(2 * tip)
			.validate(&2, CALL, &op, len)
			.unwrap()
			.priority;
		assert_eq!(priority, 6110);
	});
}

#[test]
fn no_tip_has_some_priority() {
	let tip = 0;
	let len = 10;

	ExtBuilder::default().balance_factor(100).build().execute_with(|| {
		let normal = DispatchInfo {
			weight: Weight::from_parts(100, 0),
			class: DispatchClass::Normal,
			pays_fee: Pays::Yes,
		};
		let priority = ChargeTransactionPayment::<Runtime>(tip)
			.validate(&2, CALL, &normal, len)
			.unwrap()
			.priority;

		assert_eq!(priority, 10);
	});

	ExtBuilder::default().balance_factor(100).build().execute_with(|| {
		let op = DispatchInfo {
			weight: Weight::from_parts(100, 0),
			class: DispatchClass::Operational,
			pays_fee: Pays::Yes,
		};
		let priority = ChargeTransactionPayment::<Runtime>(tip)
			.validate(&2, CALL, &op, len)
			.unwrap()
			.priority;
		assert_eq!(priority, 5510);
	});
}

#[test]
fn higher_tip_have_higher_priority() {
	let get_priorities = |tip: u64| {
		let mut priority1 = 0;
		let mut priority2 = 0;
		let len = 10;
		ExtBuilder::default().balance_factor(100).build().execute_with(|| {
			let normal = DispatchInfo {
				weight: Weight::from_parts(100, 0),
				class: DispatchClass::Normal,
				pays_fee: Pays::Yes,
			};
			priority1 = ChargeTransactionPayment::<Runtime>(tip)
				.validate(&2, CALL, &normal, len)
				.unwrap()
				.priority;
		});

		ExtBuilder::default().balance_factor(100).build().execute_with(|| {
			let op = DispatchInfo {
				weight: Weight::from_parts(100, 0),
				class: DispatchClass::Operational,
				pays_fee: Pays::Yes,
			};
			priority2 = ChargeTransactionPayment::<Runtime>(tip)
				.validate(&2, CALL, &op, len)
				.unwrap()
				.priority;
		});

		(priority1, priority2)
	};

	let mut prev_priorities = get_priorities(0);

	for tip in 1..3 {
		let priorities = get_priorities(tip);
		assert!(prev_priorities.0 < priorities.0);
		assert!(prev_priorities.1 < priorities.1);
		prev_priorities = priorities;
	}
}

#[test]
fn post_info_can_change_pays_fee() {
	ExtBuilder::default()
		.balance_factor(10)
		.base_weight(Weight::from_parts(7, 0))
		.build()
		.execute_with(|| {
			let info = info_from_weight(Weight::from_parts(100, 0));
			let post_info = post_info_from_pays(Pays::No);
			let prev_balance = Balances::free_balance(2);
			let len = 10;
			let tip = 5;

			<NextFeeMultiplier<Runtime>>::put(Multiplier::saturating_from_rational(5, 4));

			let pre = ChargeTransactionPayment::<Runtime>::from(tip)
				.pre_dispatch(&2, CALL, &info, len)
				.unwrap();

			ChargeTransactionPayment::<Runtime>::post_dispatch(
				Some(pre),
				&info,
				&post_info,
				len,
				&Ok(()),
			)
			.unwrap();

			let refund_based_fee = prev_balance - Balances::free_balance(2);
			let actual_fee =
				Pallet::<Runtime>::compute_actual_fee(len as u32, &info, &post_info, tip);

			// Only 5 tip is paid
			assert_eq!(actual_fee, 5);
			assert_eq!(refund_based_fee, actual_fee);
		});
}

#[test]
fn genesis_config_works() {
	ExtBuilder::default()
		.with_initial_multiplier(Multiplier::from_u32(100))
		.build()
		.execute_with(|| {
			assert_eq!(
				<NextFeeMultiplier<Runtime>>::get(),
				Multiplier::saturating_from_integer(100)
			);
		});
}

#[test]
fn genesis_default_works() {
	ExtBuilder::default().build().execute_with(|| {
		assert_eq!(<NextFeeMultiplier<Runtime>>::get(), Multiplier::saturating_from_integer(1));
	});
}