-
Notifications
You must be signed in to change notification settings - Fork 735
Expand file tree
/
Copy pathlib.rs
More file actions
493 lines (431 loc) · 16.7 KB
/
lib.rs
File metadata and controls
493 lines (431 loc) · 16.7 KB
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
// This file is part of Acala.
// Copyright (C) 2020-2021 Acala Foundation.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program 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.
// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
//! Common runtime code for Acala, Karura and Mandala.
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::traits::Get;
use frame_support::{
parameter_types,
traits::Contains,
weights::{
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_MILLIS, WEIGHT_PER_NANOS},
DispatchClass, Weight,
},
RuntimeDebug,
};
use frame_system::{limits, EnsureOneOf, EnsureRoot};
pub use module_support::{ExchangeRate, PrecompileCallerFilter, Price, Rate, Ratio};
use primitives::{evm::is_system_contract, Balance, BlockNumber, CurrencyId};
use scale_info::TypeInfo;
use sp_core::{
u32_trait::{_1, _2, _3, _4},
H160,
};
use sp_runtime::{
traits::{BlockNumberProvider, Convert},
transaction_validity::TransactionPriority,
FixedPointNumber, Perbill,
};
use static_assertions::const_assert;
pub mod precompile;
use orml_traits::GetByKey;
pub use precompile::{
AllPrecompiles, DexPrecompile, MultiCurrencyPrecompile, NFTPrecompile, OraclePrecompile, ScheduleCallPrecompile,
StateRentPrecompile,
};
pub use primitives::{
currency::{TokenInfo, ACA, AUSD, BNC, DOT, KAR, KBTC, KINT, KSM, KUSD, LDOT, LKSM, PHA, RENBTC, VSKSM},
AccountId,
};
use sp_std::{marker::PhantomData, prelude::*};
pub use xcm::latest::prelude::*;
pub use xcm_builder::TakeRevenue;
pub use xcm_executor::{traits::DropAssets, Assets};
use cumulus_primitives_core::relay_chain::v1::Id;
use cumulus_primitives_core::{DmpMessageHandler, XcmpMessageHandler};
/// Block number type used by the relay chain.
pub use polkadot_core_primitives::BlockNumber as RelayChainBlockNumber;
pub type TimeStampedPrice = orml_oracle::TimestampedValue<Price, primitives::Moment>;
// Priority of unsigned transactions
parameter_types! {
// Operational = final_fee * OperationalFeeMultiplier / TipPerWeightStep * max_tx_per_block + (tip + 1) / TipPerWeightStep * max_tx_per_block
// final_fee_min = base_fee + len_fee + adjusted_weight_fee + tip
// priority_min = final_fee * OperationalFeeMultiplier / TipPerWeightStep * max_tx_per_block + (tip + 1) / TipPerWeightStep * max_tx_per_block
// = final_fee_min * OperationalFeeMultiplier / TipPerWeightStep
// Ensure Inherent -> Operational tx -> Unsigned tx -> Signed normal tx
// Ensure `max_normal_priority < MinOperationalPriority / 2`
pub TipPerWeightStep: Balance = cent(KAR); // 0.01 KAR/ACA
pub MaxTipsOfPriority: Balance = 10_000 * dollar(KAR); // 10_000 KAR/ACA
pub const OperationalFeeMultiplier: u64 = 100_000_000_000_000u64;
// MinOperationalPriority = final_fee_min * OperationalFeeMultiplier / TipPerWeightStep
// 1_500_000_000u128 from https://github.com/AcalaNetwork/Acala/blob/bda4d430cbecebf8720d700b976875d0d805ceca/runtime/integration-tests/src/runtime.rs#L275
MinOperationalPriority: TransactionPriority = (1_500_000_000u128 * OperationalFeeMultiplier::get() as u128 / TipPerWeightStep::get())
.try_into()
.expect("Check that there is no overflow here");
pub CdpEngineUnsignedPriority: TransactionPriority = MinOperationalPriority::get() - 1000;
pub AuctionManagerUnsignedPriority: TransactionPriority = MinOperationalPriority::get() - 2000;
pub RenvmBridgeUnsignedPriority: TransactionPriority = MinOperationalPriority::get() - 3000;
}
/// The call is allowed only if caller is a system contract.
pub struct SystemContractsFilter;
impl PrecompileCallerFilter for SystemContractsFilter {
fn is_allowed(caller: H160) -> bool {
is_system_contract(caller)
}
}
// TODO: estimate this from benchmarks
// total block weight is 500ms, normal tx have 70% of weight = 350ms
// 350ms / 25ns = 14M gas per block
pub const WEIGHT_PER_GAS: u64 = 25 * WEIGHT_PER_NANOS; // 25_000
/// Convert gas to weight
pub struct GasToWeight;
impl Convert<u64, Weight> for GasToWeight {
fn convert(gas: u64) -> Weight {
gas.saturating_mul(WEIGHT_PER_GAS)
}
}
// TODO: somehow estimate this value. Start from a conservative value.
pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);
/// The ratio that `Normal` extrinsics should occupy. Start from a conservative value.
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(70);
/// Parachain only have 0.5 second of computation time.
pub const MAXIMUM_BLOCK_WEIGHT: Weight = 500 * WEIGHT_PER_MILLIS;
const_assert!(NORMAL_DISPATCH_RATIO.deconstruct() >= AVERAGE_ON_INITIALIZE_RATIO.deconstruct());
parameter_types! {
/// Maximum length of block. Up to 5MB.
pub RuntimeBlockLength: limits::BlockLength =
limits::BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
/// Block weights base values and limits.
pub RuntimeBlockWeights: limits::BlockWeights = limits::BlockWeights::builder()
.base_block(BlockExecutionWeight::get())
.for_class(DispatchClass::all(), |weights| {
weights.base_extrinsic = ExtrinsicBaseWeight::get();
})
.for_class(DispatchClass::Normal, |weights| {
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
.for_class(DispatchClass::Operational, |weights| {
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
// Operational transactions have an extra reserved space, so that they
// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
weights.reserved = Some(
MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT,
);
})
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
.build_or_panic();
}
parameter_types! {
/// A limit for off-chain phragmen unsigned solution submission.
///
/// We want to keep it as high as possible, but can't risk having it reject,
/// so we always subtract the base block execution weight.
pub OffchainSolutionWeightLimit: Weight = RuntimeBlockWeights::get()
.get(DispatchClass::Normal)
.max_extrinsic
.expect("Normal extrinsics have weight limit configured by default; qed")
.saturating_sub(BlockExecutionWeight::get());
}
pub struct DummyNomineeFilter;
impl<AccountId> Contains<AccountId> for DummyNomineeFilter {
fn contains(_: &AccountId) -> bool {
true
}
}
// TODO: make those const fn
pub fn dollar(currency_id: CurrencyId) -> Balance {
10u128.saturating_pow(currency_id.decimals().expect("Not support Non-Token decimals").into())
}
pub fn cent(currency_id: CurrencyId) -> Balance {
dollar(currency_id) / 100
}
pub fn millicent(currency_id: CurrencyId) -> Balance {
cent(currency_id) / 1000
}
pub fn microcent(currency_id: CurrencyId) -> Balance {
millicent(currency_id) / 1000
}
pub fn calculate_asset_ratio(foreign_asset: (AssetId, u128), native_asset: (AssetId, u128)) -> Ratio {
Ratio::saturating_from_rational(foreign_asset.1, native_asset.1)
}
pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);
impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider for RelayChainBlockNumberProvider<T> {
type BlockNumber = BlockNumber;
fn current_block_number() -> Self::BlockNumber {
cumulus_pallet_parachain_system::Pallet::<T>::validation_data()
.map(|d| d.relay_parent_number)
.unwrap_or_default()
}
}
pub type GeneralCouncilInstance = pallet_collective::Instance1;
pub type FinancialCouncilInstance = pallet_collective::Instance2;
pub type HomaCouncilInstance = pallet_collective::Instance3;
pub type TechnicalCommitteeInstance = pallet_collective::Instance4;
pub type GeneralCouncilMembershipInstance = pallet_membership::Instance1;
pub type FinancialCouncilMembershipInstance = pallet_membership::Instance2;
pub type HomaCouncilMembershipInstance = pallet_membership::Instance3;
pub type TechnicalCommitteeMembershipInstance = pallet_membership::Instance4;
pub type OperatorMembershipInstanceAcala = pallet_membership::Instance5;
// General Council
pub type EnsureRootOrAllGeneralCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, GeneralCouncilInstance>,
>;
pub type EnsureRootOrHalfGeneralCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, GeneralCouncilInstance>,
>;
pub type EnsureRootOrOneThirdsGeneralCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _3, AccountId, GeneralCouncilInstance>,
>;
pub type EnsureRootOrTwoThirdsGeneralCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, GeneralCouncilInstance>,
>;
pub type EnsureRootOrThreeFourthsGeneralCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, GeneralCouncilInstance>,
>;
pub type EnsureRootOrOneGeneralCouncil =
EnsureOneOf<AccountId, EnsureRoot<AccountId>, pallet_collective::EnsureMember<AccountId, GeneralCouncilInstance>>;
// Financial Council
pub type EnsureRootOrAllFinancialCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, FinancialCouncilInstance>,
>;
pub type EnsureRootOrHalfFinancialCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, FinancialCouncilInstance>,
>;
pub type EnsureRootOrOneThirdsFinancialCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _3, AccountId, FinancialCouncilInstance>,
>;
pub type EnsureRootOrTwoThirdsFinancialCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, FinancialCouncilInstance>,
>;
pub type EnsureRootOrThreeFourthsFinancialCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, FinancialCouncilInstance>,
>;
// Homa Council
pub type EnsureRootOrAllHomaCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, HomaCouncilInstance>,
>;
pub type EnsureRootOrHalfHomaCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, HomaCouncilInstance>,
>;
pub type EnsureRootOrOneThirdsHomaCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _3, AccountId, HomaCouncilInstance>,
>;
pub type EnsureRootOrTwoThirdsHomaCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, HomaCouncilInstance>,
>;
pub type EnsureRootOrThreeFourthsHomaCouncil = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, HomaCouncilInstance>,
>;
// Technical Committee Council
pub type EnsureRootOrAllTechnicalCommittee = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCommitteeInstance>,
>;
pub type EnsureRootOrHalfTechnicalCommittee = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, TechnicalCommitteeInstance>,
>;
pub type EnsureRootOrOneThirdsTechnicalCommittee = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_1, _3, AccountId, TechnicalCommitteeInstance>,
>;
pub type EnsureRootOrTwoThirdsTechnicalCommittee = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCommitteeInstance>,
>;
pub type EnsureRootOrThreeFourthsTechnicalCommittee = EnsureOneOf<
AccountId,
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, TechnicalCommitteeInstance>,
>;
/// The type used to represent the kinds of proxying allowed.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo)]
pub enum ProxyType {
Any,
CancelProxy,
Governance,
Auction,
Swap,
Loan,
}
impl Default for ProxyType {
fn default() -> Self {
Self::Any
}
}
#[repr(u16)]
pub enum RelayChainSubAccountId {
HomaLite = 0,
}
/// `DropAssets` implementation support asset amount lower thant ED handled by `TakeRevenue`.
///
/// parameters type:
/// - `NC`: native currency_id type.
/// - `NB`: the ExistentialDeposit amount of native currency_id.
/// - `GK`: the ExistentialDeposit amount of tokens.
pub struct AcalaDropAssets<X, T, C, NC, NB, GK>(PhantomData<(X, T, C, NC, NB, GK)>);
impl<X, T, C, NC, NB, GK> DropAssets for AcalaDropAssets<X, T, C, NC, NB, GK>
where
X: DropAssets,
T: TakeRevenue,
C: Convert<MultiLocation, Option<CurrencyId>>,
NC: Get<CurrencyId>,
NB: Get<Balance>,
GK: GetByKey<CurrencyId, Balance>,
{
fn drop_assets(origin: &MultiLocation, assets: Assets) -> Weight {
let multi_assets: Vec<MultiAsset> = assets.into();
let mut asset_traps: Vec<MultiAsset> = vec![];
for asset in multi_assets {
if let MultiAsset {
id: Concrete(location),
fun: Fungible(amount),
} = asset.clone()
{
let currency_id = C::convert(location);
// burn asset(do nothing here) if convert result is None
if let Some(currency_id) = currency_id {
let ed = ExistentialDepositsForDropAssets::<NC, NB, GK>::get(¤cy_id);
if amount < ed {
T::take_revenue(asset);
} else {
asset_traps.push(asset);
}
}
}
}
if !asset_traps.is_empty() {
X::drop_assets(origin, asset_traps.into());
}
0
}
}
/// `ExistentialDeposit` for tokens, give priority to match native token, then handled by
/// `ExistentialDeposits`.
///
/// parameters type:
/// - `NC`: native currency_id type.
/// - `NB`: the ExistentialDeposit amount of native currency_id.
/// - `GK`: the ExistentialDeposit amount of tokens.
pub struct ExistentialDepositsForDropAssets<NC, NB, GK>(PhantomData<(NC, NB, GK)>);
impl<NC, NB, GK> ExistentialDepositsForDropAssets<NC, NB, GK>
where
NC: Get<CurrencyId>,
NB: Get<Balance>,
GK: GetByKey<CurrencyId, Balance>,
{
fn get(currency_id: &CurrencyId) -> Balance {
if currency_id == &NC::get() {
NB::get()
} else {
GK::get(currency_id)
}
}
}
/// XcmMessageHandler of `DmpMessageHandler` and `XcmpMessageHandler` implementations.
/// if xcm is paused, the `max_weight` of each handle method is set to `0`.
///
/// Parameters type:
/// - `A`: `DmpMessageHandler` or `XcmpMessageHandler`
pub struct XcmMessageHandler<Runtime, A>(PhantomData<(Runtime, A)>);
impl<Runtime, A> DmpMessageHandler for XcmMessageHandler<Runtime, A>
where
Runtime: module_transaction_pause::Config,
A: DmpMessageHandler,
{
fn handle_dmp_messages(iter: impl Iterator<Item = (RelayChainBlockNumber, Vec<u8>)>, max_weight: Weight) -> Weight {
let xcm_paused: bool = module_transaction_pause::Pallet::<Runtime>::xcm_paused();
if !xcm_paused {
A::handle_dmp_messages(iter, max_weight)
} else {
A::handle_dmp_messages(iter, 0)
}
}
}
impl<Runtime, A> XcmpMessageHandler for XcmMessageHandler<Runtime, A>
where
Runtime: module_transaction_pause::Config,
A: XcmpMessageHandler,
{
fn handle_xcmp_messages<'a, I: Iterator<Item = (Id, BlockNumber, &'a [u8])>>(
iter: I,
max_weight: Weight,
) -> Weight {
let xcm_paused: bool = module_transaction_pause::Pallet::<Runtime>::xcm_paused();
if !xcm_paused {
A::handle_xcmp_messages(iter, max_weight)
} else {
A::handle_xcmp_messages(iter, 0)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use primitives::evm::SYSTEM_CONTRACT_ADDRESS_PREFIX;
#[test]
fn system_contracts_filter_works() {
assert!(SystemContractsFilter::is_allowed(H160::from_low_u64_be(1)));
let mut max_allowed_addr = [0u8; 20];
max_allowed_addr[SYSTEM_CONTRACT_ADDRESS_PREFIX.len()] = 127u8;
assert!(SystemContractsFilter::is_allowed(max_allowed_addr.into()));
let mut min_blocked_addr = [0u8; 20];
min_blocked_addr[SYSTEM_CONTRACT_ADDRESS_PREFIX.len() - 1] = 1u8;
assert!(!SystemContractsFilter::is_allowed(min_blocked_addr.into()));
}
#[test]
fn check_max_normal_priority() {
let max_normal_priority: TransactionPriority = (MaxTipsOfPriority::get() / TipPerWeightStep::get()
* RuntimeBlockWeights::get()
.max_block
.min(*RuntimeBlockLength::get().max.get(DispatchClass::Normal) as u64) as u128)
.try_into()
.expect("Check that there is no overflow here");
assert!(max_normal_priority < MinOperationalPriority::get() / 2); // 50%
}
}