1
// Copyright (C) Parity Technologies (UK) Ltd.
2
// This file is part of Polkadot.
3

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

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

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

            
17
//! Auxiliary `struct`/`enum`s for polkadot runtime.
18

            
19
use codec::{Decode, Encode, MaxEncodedLen};
20
use frame_support::traits::{
21
	fungible::{Balanced, Credit},
22
	tokens::imbalance::ResolveTo,
23
	Contains, ContainsPair, Imbalance, OnUnbalanced,
24
};
25
use pallet_treasury::TreasuryAccountId;
26
use polkadot_primitives::Balance;
27
use sp_runtime::{traits::TryConvert, Perquintill, RuntimeDebug};
28
use xcm::VersionedLocation;
29

            
30
/// Logic for the author to get a portion of fees.
31
pub struct ToAuthor<R>(core::marker::PhantomData<R>);
32
impl<R> OnUnbalanced<Credit<R::AccountId, pallet_balances::Pallet<R>>> for ToAuthor<R>
33
where
34
	R: pallet_balances::Config + pallet_authorship::Config,
35
	<R as frame_system::Config>::AccountId: From<polkadot_primitives::AccountId>,
36
	<R as frame_system::Config>::AccountId: Into<polkadot_primitives::AccountId>,
37
{
38
	fn on_nonzero_unbalanced(
39
		amount: Credit<<R as frame_system::Config>::AccountId, pallet_balances::Pallet<R>>,
40
	) {
41
		if let Some(author) = <pallet_authorship::Pallet<R>>::author() {
42
			let _ = <pallet_balances::Pallet<R>>::resolve(&author, amount);
43
		}
44
	}
45
}
46

            
47
pub struct DealWithFees<R>(core::marker::PhantomData<R>);
48
impl<R> OnUnbalanced<Credit<R::AccountId, pallet_balances::Pallet<R>>> for DealWithFees<R>
49
where
50
	R: pallet_balances::Config + pallet_authorship::Config + pallet_treasury::Config,
51
	<R as frame_system::Config>::AccountId: From<polkadot_primitives::AccountId>,
52
	<R as frame_system::Config>::AccountId: Into<polkadot_primitives::AccountId>,
53
{
54
	fn on_unbalanceds<B>(
55
		mut fees_then_tips: impl Iterator<Item = Credit<R::AccountId, pallet_balances::Pallet<R>>>,
56
	) {
57
		if let Some(fees) = fees_then_tips.next() {
58
			// for fees, 80% to treasury, 20% to author
59
			let mut split = fees.ration(80, 20);
60
			if let Some(tips) = fees_then_tips.next() {
61
				// for tips, if any, 100% to author
62
				tips.merge_into(&mut split.1);
63
			}
64
			ResolveTo::<TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(split.0);
65
			<ToAuthor<R> as OnUnbalanced<_>>::on_unbalanced(split.1);
66
		}
67
	}
68
}
69

            
70
pub fn era_payout(
71
	total_staked: Balance,
72
	total_stakable: Balance,
73
	max_annual_inflation: Perquintill,
74
	period_fraction: Perquintill,
75
	auctioned_slots: u64,
76
) -> (Balance, Balance) {
77
	use pallet_staking_reward_fn::compute_inflation;
78
	use sp_runtime::traits::Saturating;
79

            
80
	let min_annual_inflation = Perquintill::from_rational(25u64, 1000u64);
81
	let delta_annual_inflation = max_annual_inflation.saturating_sub(min_annual_inflation);
82

            
83
	// 30% reserved for up to 60 slots.
84
	let auction_proportion = Perquintill::from_rational(auctioned_slots.min(60), 200u64);
85

            
86
	// Therefore the ideal amount at stake (as a percentage of total issuance) is 75% less the
87
	// amount that we expect to be taken up with auctions.
88
	let ideal_stake = Perquintill::from_percent(75).saturating_sub(auction_proportion);
89

            
90
	let stake = Perquintill::from_rational(total_staked, total_stakable);
91
	let falloff = Perquintill::from_percent(5);
92
	let adjustment = compute_inflation(stake, ideal_stake, falloff);
93
	let staking_inflation =
94
		min_annual_inflation.saturating_add(delta_annual_inflation * adjustment);
95

            
96
	let max_payout = period_fraction * max_annual_inflation * total_stakable;
97
	let staking_payout = (period_fraction * staking_inflation) * total_stakable;
98
	let rest = max_payout.saturating_sub(staking_payout);
99

            
100
	let other_issuance = total_stakable.saturating_sub(total_staked);
101
	if total_staked > other_issuance {
102
		let _cap_rest = Perquintill::from_rational(other_issuance, total_staked) * staking_payout;
103
		// We don't do anything with this, but if we wanted to, we could introduce a cap on the
104
		// treasury amount with: `rest = rest.min(cap_rest);`
105
	}
106
	(staking_payout, rest)
107
}
108

            
109
/// Versioned locatable asset type which contains both an XCM `location` and `asset_id` to identify
110
/// an asset which exists on some chain.
111
#[derive(
112
	Encode, Decode, Eq, PartialEq, Clone, RuntimeDebug, scale_info::TypeInfo, MaxEncodedLen,
113
)]
114
pub enum VersionedLocatableAsset {
115
	#[codec(index = 3)]
116
	V3 { location: xcm::v3::Location, asset_id: xcm::v3::AssetId },
117
	#[codec(index = 4)]
118
	V4 { location: xcm::v4::Location, asset_id: xcm::v4::AssetId },
119
}
120

            
121
/// Converts the [`VersionedLocatableAsset`] to the [`xcm_builder::LocatableAssetId`].
122
pub struct LocatableAssetConverter;
123
impl TryConvert<VersionedLocatableAsset, xcm_builder::LocatableAssetId>
124
	for LocatableAssetConverter
125
{
126
	fn try_convert(
127
		asset: VersionedLocatableAsset,
128
	) -> Result<xcm_builder::LocatableAssetId, VersionedLocatableAsset> {
129
		match asset {
130
			VersionedLocatableAsset::V3 { location, asset_id } =>
131
				Ok(xcm_builder::LocatableAssetId {
132
					location: location.try_into().map_err(|_| asset.clone())?,
133
					asset_id: asset_id.try_into().map_err(|_| asset.clone())?,
134
				}),
135
			VersionedLocatableAsset::V4 { location, asset_id } =>
136
				Ok(xcm_builder::LocatableAssetId { location, asset_id }),
137
		}
138
	}
139
}
140

            
141
/// Converts the [`VersionedLocation`] to the [`xcm::latest::Location`].
142
pub struct VersionedLocationConverter;
143
impl TryConvert<&VersionedLocation, xcm::latest::Location> for VersionedLocationConverter {
144
	fn try_convert(
145
		location: &VersionedLocation,
146
	) -> Result<xcm::latest::Location, &VersionedLocation> {
147
		let latest = match location.clone() {
148
			VersionedLocation::V2(l) => {
149
				let v3: xcm::v3::Location = l.try_into().map_err(|_| location)?;
150
				v3.try_into().map_err(|_| location)?
151
			},
152
			VersionedLocation::V3(l) => l.try_into().map_err(|_| location)?,
153
			VersionedLocation::V4(l) => l,
154
		};
155
		Ok(latest)
156
	}
157
}
158

            
159
/// Adapter for [`Contains`] trait to match [`VersionedLocatableAsset`] type converted to the latest
160
/// version of itself where it's location matched by `L` and it's asset id by `A` parameter types.
161
pub struct ContainsParts<C>(core::marker::PhantomData<C>);
162
impl<C> Contains<VersionedLocatableAsset> for ContainsParts<C>
163
where
164
	C: ContainsPair<xcm::latest::Location, xcm::latest::Location>,
165
{
166
	fn contains(asset: &VersionedLocatableAsset) -> bool {
167
		use VersionedLocatableAsset::*;
168
		let (location, asset_id) = match asset.clone() {
169
			V3 { location, asset_id } => match (location.try_into(), asset_id.try_into()) {
170
				(Ok(l), Ok(a)) => (l, a),
171
				_ => return false,
172
			},
173
			V4 { location, asset_id } => (location, asset_id),
174
		};
175
		C::contains(&location, &asset_id.0)
176
	}
177
}
178

            
179
#[cfg(feature = "runtime-benchmarks")]
180
pub mod benchmarks {
181
	use super::VersionedLocatableAsset;
182
	use core::marker::PhantomData;
183
	use frame_support::traits::Get;
184
	use pallet_asset_rate::AssetKindFactory;
185
	use pallet_treasury::ArgumentsFactory as TreasuryArgumentsFactory;
186
	use sp_core::{ConstU32, ConstU8};
187
	use xcm::prelude::*;
188

            
189
	/// Provides a factory method for the [`VersionedLocatableAsset`].
190
	/// The location of the asset is determined as a Parachain with an ID equal to the passed seed.
191
	pub struct AssetRateArguments;
192
	impl AssetKindFactory<VersionedLocatableAsset> for AssetRateArguments {
193
		fn create_asset_kind(seed: u32) -> VersionedLocatableAsset {
194
			VersionedLocatableAsset::V4 {
195
				location: xcm::v4::Location::new(0, [xcm::v4::Junction::Parachain(seed)]),
196
				asset_id: xcm::v4::Location::new(
197
					0,
198
					[
199
						xcm::v4::Junction::PalletInstance(seed.try_into().unwrap()),
200
						xcm::v4::Junction::GeneralIndex(seed.into()),
201
					],
202
				)
203
				.into(),
204
			}
205
		}
206
	}
207

            
208
	/// Provide factory methods for the [`VersionedLocatableAsset`] and the `Beneficiary` of the
209
	/// [`VersionedLocation`]. The location of the asset is determined as a Parachain with an
210
	/// ID equal to the passed seed.
211
	pub struct TreasuryArguments<Parents = ConstU8<0>, ParaId = ConstU32<0>>(
212
		PhantomData<(Parents, ParaId)>,
213
	);
214
	impl<Parents: Get<u8>, ParaId: Get<u32>>
215
		TreasuryArgumentsFactory<VersionedLocatableAsset, VersionedLocation>
216
		for TreasuryArguments<Parents, ParaId>
217
	{
218
		fn create_asset_kind(seed: u32) -> VersionedLocatableAsset {
219
			VersionedLocatableAsset::V3 {
220
				location: xcm::v3::Location::new(
221
					Parents::get(),
222
					[xcm::v3::Junction::Parachain(ParaId::get())],
223
				),
224
				asset_id: xcm::v3::Location::new(
225
					0,
226
					[
227
						xcm::v3::Junction::PalletInstance(seed.try_into().unwrap()),
228
						xcm::v3::Junction::GeneralIndex(seed.into()),
229
					],
230
				)
231
				.into(),
232
			}
233
		}
234
		fn create_beneficiary(seed: [u8; 32]) -> VersionedLocation {
235
			VersionedLocation::V4(xcm::v4::Location::new(
236
				0,
237
				[xcm::v4::Junction::AccountId32 { network: None, id: seed }],
238
			))
239
		}
240
	}
241
}
242

            
243
#[cfg(test)]
244
mod tests {
245
	use super::*;
246
	use frame_support::{
247
		derive_impl,
248
		dispatch::DispatchClass,
249
		parameter_types,
250
		traits::{
251
			tokens::{PayFromAccount, UnityAssetBalanceConversion},
252
			FindAuthor,
253
		},
254
		weights::Weight,
255
		PalletId,
256
	};
257
	use frame_system::limits;
258
	use polkadot_primitives::AccountId;
259
	use sp_core::{ConstU64, H256};
260
	use sp_runtime::{
261
		traits::{BlakeTwo256, IdentityLookup},
262
		BuildStorage, Perbill,
263
	};
264

            
265
	type Block = frame_system::mocking::MockBlock<Test>;
266
	const TEST_ACCOUNT: AccountId = AccountId::new([1; 32]);
267

            
268
	frame_support::construct_runtime!(
269
		pub enum Test
270
		{
271
			System: frame_system,
272
			Authorship: pallet_authorship,
273
			Balances: pallet_balances,
274
			Treasury: pallet_treasury,
275
		}
276
	);
277

            
278
	parameter_types! {
279
		pub BlockWeights: limits::BlockWeights = limits::BlockWeights::builder()
280
			.base_block(Weight::from_parts(10, 0))
281
			.for_class(DispatchClass::all(), |weight| {
282
				weight.base_extrinsic = Weight::from_parts(100, 0);
283
			})
284
			.for_class(DispatchClass::non_mandatory(), |weight| {
285
				weight.max_total = Some(Weight::from_parts(1024, u64::MAX));
286
			})
287
			.build_or_panic();
288
		pub BlockLength: limits::BlockLength = limits::BlockLength::max(2 * 1024);
289
		pub const AvailableBlockRatio: Perbill = Perbill::one();
290
	}
291

            
292
	#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
293
	impl frame_system::Config for Test {
294
		type BaseCallFilter = frame_support::traits::Everything;
295
		type RuntimeOrigin = RuntimeOrigin;
296
		type Nonce = u64;
297
		type RuntimeCall = RuntimeCall;
298
		type Hash = H256;
299
		type Hashing = BlakeTwo256;
300
		type AccountId = AccountId;
301
		type Lookup = IdentityLookup<Self::AccountId>;
302
		type Block = Block;
303
		type RuntimeEvent = RuntimeEvent;
304
		type BlockLength = BlockLength;
305
		type BlockWeights = BlockWeights;
306
		type DbWeight = ();
307
		type Version = ();
308
		type PalletInfo = PalletInfo;
309
		type AccountData = pallet_balances::AccountData<u64>;
310
		type OnNewAccount = ();
311
		type OnKilledAccount = ();
312
		type SystemWeightInfo = ();
313
		type SS58Prefix = ();
314
		type OnSetCode = ();
315
		type MaxConsumers = frame_support::traits::ConstU32<16>;
316
	}
317

            
318
	#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
319
	impl pallet_balances::Config for Test {
320
		type AccountStore = System;
321
	}
322

            
323
	parameter_types! {
324
		pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
325
		pub const MaxApprovals: u32 = 100;
326
		pub TreasuryAccount: AccountId = Treasury::account_id();
327
	}
328

            
329
	impl pallet_treasury::Config for Test {
330
		type Currency = pallet_balances::Pallet<Test>;
331
		type RejectOrigin = frame_system::EnsureRoot<AccountId>;
332
		type RuntimeEvent = RuntimeEvent;
333
		type SpendPeriod = ();
334
		type Burn = ();
335
		type BurnDestination = ();
336
		type PalletId = TreasuryPalletId;
337
		type SpendFunds = ();
338
		type MaxApprovals = MaxApprovals;
339
		type WeightInfo = ();
340
		type SpendOrigin = frame_support::traits::NeverEnsureOrigin<u64>;
341
		type AssetKind = ();
342
		type Beneficiary = Self::AccountId;
343
		type BeneficiaryLookup = IdentityLookup<Self::AccountId>;
344
		type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
345
		type BalanceConverter = UnityAssetBalanceConversion;
346
		type PayoutPeriod = ConstU64<0>;
347
		#[cfg(feature = "runtime-benchmarks")]
348
		type BenchmarkHelper = ();
349
	}
350

            
351
	pub struct OneAuthor;
352
	impl FindAuthor<AccountId> for OneAuthor {
353
		fn find_author<'a, I>(_: I) -> Option<AccountId>
354
		where
355
			I: 'a,
356
		{
357
			Some(TEST_ACCOUNT)
358
		}
359
	}
360
	impl pallet_authorship::Config for Test {
361
		type FindAuthor = OneAuthor;
362
		type EventHandler = ();
363
	}
364

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

            
374
	#[test]
375
	fn test_fees_and_tip_split() {
376
		new_test_ext().execute_with(|| {
377
			let fee =
378
				<pallet_balances::Pallet<Test> as frame_support::traits::fungible::Balanced<
379
					AccountId,
380
				>>::issue(10);
381
			let tip =
382
				<pallet_balances::Pallet<Test> as frame_support::traits::fungible::Balanced<
383
					AccountId,
384
				>>::issue(20);
385

            
386
			assert_eq!(Balances::free_balance(Treasury::account_id()), 0);
387
			assert_eq!(Balances::free_balance(TEST_ACCOUNT), 0);
388

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

            
391
			// Author gets 100% of tip and 20% of fee = 22
392
			assert_eq!(Balances::free_balance(TEST_ACCOUNT), 22);
393
			// Treasury gets 80% of fee
394
			assert_eq!(Balances::free_balance(Treasury::account_id()), 8);
395
		});
396
	}
397

            
398
	#[test]
399
	fn compute_inflation_should_give_sensible_results() {
400
		assert_eq!(
401
			pallet_staking_reward_fn::compute_inflation(
402
				Perquintill::from_percent(75),
403
				Perquintill::from_percent(75),
404
				Perquintill::from_percent(5),
405
			),
406
			Perquintill::one()
407
		);
408
		assert_eq!(
409
			pallet_staking_reward_fn::compute_inflation(
410
				Perquintill::from_percent(50),
411
				Perquintill::from_percent(75),
412
				Perquintill::from_percent(5),
413
			),
414
			Perquintill::from_rational(2u64, 3u64)
415
		);
416
		assert_eq!(
417
			pallet_staking_reward_fn::compute_inflation(
418
				Perquintill::from_percent(80),
419
				Perquintill::from_percent(75),
420
				Perquintill::from_percent(5),
421
			),
422
			Perquintill::from_rational(1u64, 2u64)
423
		);
424
	}
425

            
426
	#[test]
427
	fn era_payout_should_give_sensible_results() {
428
		assert_eq!(
429
			era_payout(75, 100, Perquintill::from_percent(10), Perquintill::one(), 0,),
430
			(10, 0)
431
		);
432
		assert_eq!(
433
			era_payout(80, 100, Perquintill::from_percent(10), Perquintill::one(), 0,),
434
			(6, 4)
435
		);
436
	}
437
}