This repository has been archived by the owner on May 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathimpls.rs
273 lines (245 loc) · 8.92 KB
/
impls.rs
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
// This file is part of Trappist.
// 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.
//! Auxiliary struct/enums for parachain runtimes.
//! Taken from polkadot/runtime/common (at a21cd64) and adapted for parachains.
use frame_support::traits::{Currency, Imbalance, OnUnbalanced};
pub use log;
use sp_std::marker::PhantomData;
/// Type alias to conveniently refer to the `Currency::NegativeImbalance` associated type.
pub type NegativeImbalance<T> = <pallet_balances::Pallet<T> as Currency<
<T as frame_system::Config>::AccountId,
>>::NegativeImbalance;
/// Type alias to conveniently refer to `frame_system`'s `Config::AccountId`.
pub type AccountIdOf<R> = <R as frame_system::Config>::AccountId;
/// Logic for the author to get a portion of fees.
pub struct ToAuthor<R>(PhantomData<R>);
impl<R> OnUnbalanced<NegativeImbalance<R>> for ToAuthor<R>
where
R: pallet_balances::Config + pallet_collator_selection::Config,
AccountIdOf<R>:
From<polkadot_core_primitives::AccountId> + Into<polkadot_core_primitives::AccountId>,
<R as frame_system::Config>::RuntimeEvent: From<pallet_balances::Event<R>>,
{
fn on_nonzero_unbalanced(amount: NegativeImbalance<R>) {
let author = <pallet_collator_selection::Pallet<R>>::account_id();
<pallet_balances::Pallet<R>>::resolve_creating(&author, amount);
}
}
pub struct DealWithFees<R>(PhantomData<R>);
impl<R> OnUnbalanced<NegativeImbalance<R>> for DealWithFees<R>
where
R: pallet_balances::Config + pallet_collator_selection::Config + pallet_treasury::Config,
pallet_treasury::Pallet<R>: OnUnbalanced<NegativeImbalance<R>>,
AccountIdOf<R>:
From<polkadot_core_primitives::AccountId> + Into<polkadot_core_primitives::AccountId>,
<R as frame_system::Config>::RuntimeEvent: From<pallet_balances::Event<R>>,
{
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::Pallet as Treasury;
<Treasury<R> as OnUnbalanced<_>>::on_unbalanced(split.0);
<ToAuthor<R> as OnUnbalanced<_>>::on_unbalanced(split.1);
}
}
}
#[cfg(test)]
mod tests {
use frame_support::traits::tokens::{PayFromAccount, UnityAssetBalanceConversion};
use frame_support::{
construct_runtime, parameter_types,
traits::{FindAuthor, ValidatorRegistration},
PalletId,
};
use frame_system::{limits, EnsureRoot};
use pallet_collator_selection::IdentityCollator;
use polkadot_core_primitives::AccountId;
use sp_core::H256;
use sp_runtime::{
traits::{BlakeTwo256, ConstU32, ConstU64, IdentityLookup},
BuildStorage, Perbill, Permill,
};
use super::*;
type Block = frame_system::mocking::MockBlock<Test>;
const TEST_ACCOUNT: AccountId = AccountId::new([1; 32]);
construct_runtime!(
pub struct Test {
System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
CollatorSelection: pallet_collator_selection::{Pallet, Call, Storage, Event<T>},
Treasury: pallet_treasury::{Pallet, Call, Storage, Event<T>},
}
);
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub BlockLength: limits::BlockLength = limits::BlockLength::max(2 * 1024);
pub const AvailableBlockRatio: Perbill = Perbill::one();
pub const MaxReserves: u32 = 50;
}
impl frame_system::Config for Test {
type BaseCallFilter = frame_support::traits::Everything;
type BlockWeights = ();
type BlockLength = BlockLength;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type RuntimeEvent = RuntimeEvent;
type BlockHashCount = BlockHashCount;
type DbWeight = ();
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = ConstU32<16>;
type Nonce = u64;
type Block = Block;
}
impl pallet_balances::Config for Test {
type RuntimeEvent = RuntimeEvent;
type WeightInfo = ();
type Balance = u64;
type DustRemoval = ();
type ExistentialDeposit = ConstU64<1>;
type AccountStore = System;
type ReserveIdentifier = [u8; 8];
type RuntimeHoldReason = ();
type FreezeIdentifier = ();
type MaxLocks = ();
type MaxReserves = MaxReserves;
type MaxHolds = ConstU32<3>;
type MaxFreezes = ConstU32<0>;
type RuntimeFreezeReason = ();
}
pub struct OneAuthor;
impl FindAuthor<AccountId> for OneAuthor {
fn find_author<'a, I>(_: I) -> Option<AccountId>
where
I: 'a,
{
Some(TEST_ACCOUNT)
}
}
pub struct IsRegistered;
impl ValidatorRegistration<AccountId> for IsRegistered {
fn is_registered(_id: &AccountId) -> bool {
true
}
}
parameter_types! {
pub const PotId: PalletId = PalletId(*b"PotStake");
pub const MaxCandidates: u32 = 20;
pub const MaxInvulnerables: u32 = 20;
pub const MinEligibleCollators: u32 = 1;
}
impl pallet_collator_selection::Config for Test {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type UpdateOrigin = EnsureRoot<AccountId>;
type PotId = PotId;
type MaxCandidates = MaxCandidates;
type MinEligibleCollators = MinEligibleCollators;
type MaxInvulnerables = MaxInvulnerables;
type KickThreshold = ();
type ValidatorId = <Self as frame_system::Config>::AccountId;
type ValidatorIdOf = IdentityCollator;
type ValidatorRegistration = IsRegistered;
type WeightInfo = ();
}
impl pallet_authorship::Config for Test {
type FindAuthor = OneAuthor;
type EventHandler = ();
}
parameter_types! {
pub const ProposalBond: Permill = Permill::from_percent(5);
pub const Burn: Permill = Permill::from_percent(50);
pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
}
pub struct TestSpendOrigin;
impl frame_support::traits::EnsureOrigin<RuntimeOrigin> for TestSpendOrigin {
type Success = u64;
fn try_origin(o: RuntimeOrigin) -> Result<Self::Success, RuntimeOrigin> {
Result::<frame_system::RawOrigin<_>, RuntimeOrigin>::from(o).and_then(|o| match o {
frame_system::RawOrigin::Root => Ok(u64::max_value()),
r => Err(RuntimeOrigin::from(r)),
})
}
#[cfg(feature = "runtime-benchmarks")]
fn try_successful_origin() -> Result<RuntimeOrigin, ()> {
Ok(RuntimeOrigin::root())
}
}
parameter_types! {
pub TreasuryAccount: AccountId = Treasury::account_id();
}
impl pallet_treasury::Config for Test {
type Currency = pallet_balances::Pallet<Test>;
type ApproveOrigin = EnsureRoot<AccountId>;
type RejectOrigin = EnsureRoot<AccountId>;
type RuntimeEvent = RuntimeEvent;
type OnSlash = ();
type ProposalBond = ProposalBond;
type ProposalBondMinimum = ConstU64<1>;
type ProposalBondMaximum = ();
type SpendPeriod = ConstU64<2>;
type Burn = Burn;
type PalletId = TreasuryPalletId;
type BurnDestination = (); // Just gets burned.
type WeightInfo = ();
type SpendFunds = ();
type MaxApprovals = ConstU32<100>;
type SpendOrigin = TestSpendOrigin;
type AssetKind = ();
type Beneficiary = Self::AccountId;
type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
type BalanceConverter = UnityAssetBalanceConversion;
type PayoutPeriod = ConstU64<10>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
}
pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().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(100);
let tip = Balances::issue(30);
assert_eq!(Balances::free_balance(Treasury::account_id()), 0);
DealWithFees::on_unbalanceds(vec![fee, tip].into_iter());
// Author should get 20% of the fee + the 100% of the tip. (50)
assert_eq!(Balances::free_balance(CollatorSelection::account_id()), 50);
// Treasury should get 80% of the fee. (80)
assert_eq!(Balances::free_balance(Treasury::account_id()), 80);
});
}
}