impls.rs 7.15 KB
Newer Older
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.

//! Auxillary struct/enums for polkadot runtime.

19
20
use frame_support::traits::{OnUnbalanced, Imbalance, Currency};
use crate::NegativeImbalance;
21
22

/// Logic for the author to get a portion of fees.
23
pub struct ToAuthor<R>(sp_std::marker::PhantomData<R>);
24
25
impl<R> OnUnbalanced<NegativeImbalance<R>> for ToAuthor<R>
where
26
	R: pallet_balances::Trait + pallet_authorship::Trait,
27
28
	<R as frame_system::Trait>::AccountId: From<primitives::v1::AccountId>,
	<R as frame_system::Trait>::AccountId: Into<primitives::v1::AccountId>,
29
30
31
32
	<R as frame_system::Trait>::Event: From<pallet_balances::RawEvent<
		<R as frame_system::Trait>::AccountId,
		<R as pallet_balances::Trait>::Balance,
		pallet_balances::DefaultInstance>
33
34
35
	>,
{
	fn on_nonzero_unbalanced(amount: NegativeImbalance<R>) {
36
		let numeric_amount = amount.peek();
37
38
39
		let author = <pallet_authorship::Module<R>>::author();
		<pallet_balances::Module<R>>::resolve_creating(&<pallet_authorship::Module<R>>::author(), amount);
		<frame_system::Module<R>>::deposit_event(pallet_balances::RawEvent::Deposit(author, numeric_amount));
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

pub struct DealWithFees<R>(sp_std::marker::PhantomData<R>);
impl<R> OnUnbalanced<NegativeImbalance<R>> for DealWithFees<R>
where
	R: pallet_balances::Trait + pallet_treasury::Trait + pallet_authorship::Trait,
	pallet_treasury::Module<R>: OnUnbalanced<NegativeImbalance<R>>,
	<R as frame_system::Trait>::AccountId: From<primitives::v1::AccountId>,
	<R as frame_system::Trait>::AccountId: Into<primitives::v1::AccountId>,
	<R as frame_system::Trait>::Event: From<pallet_balances::RawEvent<
		<R as frame_system::Trait>::AccountId,
		<R as pallet_balances::Trait>::Balance,
		pallet_balances::DefaultInstance>
	>,
{
	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance<R>>) {
		if let Some(fees) = fees_then_tips.next() {
			// for fees, 80% to treasury, 20% to author
			let mut split = fees.ration(80, 20);
			if let Some(tips) = fees_then_tips.next() {
				// for tips, if any, 100% to author
				tips.merge_into(&mut split.1);
			}
			use pallet_treasury::Module as Treasury;
			<Treasury<R> as OnUnbalanced<_>>::on_unbalanced(split.0);
			<ToAuthor<R> as OnUnbalanced<_>>::on_unbalanced(split.1);
		}
	}
}


#[cfg(test)]
mod tests {
	use super::*;
	use frame_support::{impl_outer_origin, parameter_types, weights::Weight};
	use frame_support::traits::FindAuthor;
	use sp_core::H256;
	use sp_runtime::{
		testing::Header, ModuleId,
		traits::{BlakeTwo256, IdentityLookup},
		Perbill,
	};
	use primitives::v1::AccountId;

	#[derive(Clone, PartialEq, Eq, Debug)]
	pub struct Test;

	impl_outer_origin!{
		pub enum Origin for Test {}
	}

	parameter_types! {
		pub const BlockHashCount: u64 = 250;
		pub const ExtrinsicBaseWeight: u64 = 100;
		pub const MaximumBlockWeight: Weight = 1024;
		pub const MaximumBlockLength: u32 = 2 * 1024;
		pub const AvailableBlockRatio: Perbill = Perbill::one();
	}

	impl frame_system::Trait for Test {
		type BaseCallFilter = ();
		type Origin = Origin;
		type Index = u64;
		type BlockNumber = u64;
		type Call = ();
		type Hash = H256;
		type Hashing = BlakeTwo256;
		type AccountId = AccountId;
		type Lookup = IdentityLookup<Self::AccountId>;
		type Header = Header;
		type Event = ();
		type BlockHashCount = BlockHashCount;
		type MaximumBlockWeight = MaximumBlockWeight;
		type DbWeight = ();
		type BlockExecutionWeight = ();
		type ExtrinsicBaseWeight = ExtrinsicBaseWeight;
		type MaximumExtrinsicWeight = MaximumBlockWeight;
		type MaximumBlockLength = MaximumBlockLength;
		type AvailableBlockRatio = AvailableBlockRatio;
		type Version = ();
		type PalletInfo = ();
		type AccountData = pallet_balances::AccountData<u64>;
		type OnNewAccount = ();
		type OnKilledAccount = ();
		type SystemWeightInfo = ();
	}

	impl pallet_balances::Trait for Test {
		type Balance = u64;
		type Event = ();
		type DustRemoval = ();
		type ExistentialDeposit = ();
		type AccountStore = System;
		type MaxLocks = ();
		type WeightInfo = ();
	}

	pub struct Nobody;
	impl frame_support::traits::Contains<AccountId> for Nobody {
		fn contains(_: &AccountId) -> bool { false }
		fn sorted_members() -> Vec<AccountId> { vec![] }
		#[cfg(feature = "runtime-benchmarks")]
		fn add(_: &AccountId) { unimplemented!() }
	}
	impl frame_support::traits::ContainsLengthBound for Nobody {
		fn min_len() -> usize { 0 }
		fn max_len() -> usize { 0 }
	}

	parameter_types! {
		pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry");
	}

	impl pallet_treasury::Trait for Test {
		type Currency = pallet_balances::Module<Test>;
		type ApproveOrigin = frame_system::EnsureRoot<AccountId>;
		type RejectOrigin = frame_system::EnsureRoot<AccountId>;
		type Event = ();
		type OnSlash = ();
		type ProposalBond = ();
		type ProposalBondMinimum = ();
		type SpendPeriod = ();
		type Burn = ();
		type BurnDestination = ();
		type Tippers = Nobody;
		type TipCountdown = ();
		type TipFindersFee = ();
		type TipReportDepositBase = ();
		type DataDepositPerByte = ();
		type BountyDepositBase = ();
		type BountyDepositPayoutDelay = ();
		type BountyUpdatePeriod = ();
		type MaximumReasonLength = ();
		type BountyCuratorDeposit = ();
		type BountyValueMinimum = ();
		type ModuleId = TreasuryModuleId;
		type WeightInfo = ();
	}

	pub struct OneAuthor;
	impl FindAuthor<AccountId> for OneAuthor {
		fn find_author<'a, I>(_: I) -> Option<AccountId>
			where I: 'a,
		{
			Some(Default::default())
		}
	}
	impl pallet_authorship::Trait for Test {
		type FindAuthor = OneAuthor;
		type UncleGenerations = ();
		type FilterUncle = ();
		type EventHandler = ();
	}

	type Treasury = pallet_treasury::Module<Test>;
	type Balances = pallet_balances::Module<Test>;
	type System = frame_system::Module<Test>;

	pub fn new_test_ext() -> sp_io::TestExternalities {
		let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
		// We use default for brevity, but you can configure as desired if needed.
		pallet_balances::GenesisConfig::<Test>::default().assimilate_storage(&mut t).unwrap();
		t.into()
	}

	#[test]
	fn test_fees_and_tip_split() {
		new_test_ext().execute_with(|| {
			let fee = Balances::issue(10);
			let tip = Balances::issue(20);

			assert_eq!(Balances::free_balance(Treasury::account_id()), 0);
			assert_eq!(Balances::free_balance(AccountId::default()), 0);

			DealWithFees::on_unbalanceds(vec![fee, tip].into_iter());

			// Author gets 100% of tip and 20% of fee = 22
			assert_eq!(Balances::free_balance(AccountId::default()), 22);
			// Treasury gets 80% of fee
			assert_eq!(Balances::free_balance(Treasury::account_id()), 8);
		});
	}
}