-
Notifications
You must be signed in to change notification settings - Fork 358
/
Copy pathlib.rs
1895 lines (1739 loc) · 69.9 KB
/
lib.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
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
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019-2022 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam 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.
// Moonbeam 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 Moonbeam. If not, see <http://www.gnu.org/licenses/>.
//! The Moonbase Runtime.
//!
//! Primary features of this runtime include:
//! * Ethereum compatibility
//! * Moonbase tokenomics
#![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
#![recursion_limit = "512"]
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
pub mod asset_config;
pub mod governance;
pub mod timestamp;
pub mod xcm_config;
mod precompiles;
// Re-export required by get! macro.
#[cfg(feature = "std")]
pub use fp_evm::GenesisAccount;
pub use frame_support::traits::Get;
pub use moonbeam_core_primitives::{
AccountId, AccountIndex, Address, AssetId, Balance, BlockNumber, DigestItem, Hash, Header,
Index, Signature,
};
pub use pallet_author_slot_filter::EligibilityValue;
pub use pallet_parachain_staking::{weights::WeightInfo, InflationInfo, Range};
pub use precompiles::{
MoonbasePrecompiles, PrecompileName, FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
};
use account::AccountId20;
use cumulus_pallet_parachain_system::{
RelayChainStateProof, RelayNumberMonotonicallyIncreases, RelaychainDataProvider,
};
use cumulus_primitives_core::relay_chain;
use fp_rpc::TransactionStatus;
use frame_support::{
construct_runtime,
dispatch::{DispatchClass, GetDispatchInfo, PostDispatchInfo},
ensure,
pallet_prelude::DispatchResult,
parameter_types,
traits::{
fungible::{Balanced, Credit, HoldConsideration, Inspect},
tokens::imbalance::ResolveTo,
tokens::{PayFromAccount, UnityAssetBalanceConversion},
ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Contains, EitherOfDiverse,
EqualPrivilegeOnly, FindAuthor, Imbalance, InstanceFilter, LinearStoragePrice,
OffchainWorker, OnFinalize, OnIdle, OnInitialize, OnRuntimeUpgrade, OnUnbalanced,
},
weights::{
constants::{RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND},
ConstantMultiplier, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients,
WeightToFeePolynomial,
},
PalletId,
};
use frame_system::{EnsureRoot, EnsureSigned};
use governance::councils::*;
use moonbeam_rpc_primitives_txpool::TxPoolResponse;
use moonbeam_runtime_common::weights as moonbeam_weights;
use nimbus_primitives::CanAuthor;
use pallet_ethereum::Call::transact;
use pallet_ethereum::{PostLogContent, Transaction as EthereumTransaction};
use pallet_evm::{
Account as EVMAccount, EVMFungibleAdapter, EnsureAddressNever, EnsureAddressRoot,
FeeCalculator, GasWeightMapping, IdentityAddressMapping,
OnChargeEVMTransaction as OnChargeEVMTransactionT, Runner,
};
use pallet_transaction_payment::{FungibleAdapter, Multiplier, TargetedFeeAdjustment};
use pallet_treasury::TreasuryAccountId;
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
use sp_api::impl_runtime_apis;
use sp_consensus_slots::Slot;
use sp_core::{OpaqueMetadata, H160, H256, U256};
#[cfg(feature = "try-runtime")]
use sp_runtime::TryRuntimeError;
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
traits::{
BlakeTwo256, Block as BlockT, DispatchInfoOf, Dispatchable, Header as HeaderT,
IdentityLookup, PostDispatchInfoOf, UniqueSaturatedInto, Zero,
},
transaction_validity::{
InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
},
ApplyExtrinsicResult, DispatchErrorWithPostInfo, FixedPointNumber, Perbill, Permill,
Perquintill,
};
use sp_std::{
convert::{From, Into},
prelude::*,
};
#[cfg(feature = "std")]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
use smallvec::smallvec;
use sp_runtime::serde::{Deserialize, Serialize};
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
pub type Precompiles = MoonbasePrecompiles<Runtime>;
/// UNIT, the native token, uses 18 decimals of precision.
pub mod currency {
use super::Balance;
// Provide a common factor between runtimes based on a supply of 10_000_000 tokens.
pub const SUPPLY_FACTOR: Balance = 1;
pub const WEI: Balance = 1;
pub const KILOWEI: Balance = 1_000;
pub const MEGAWEI: Balance = 1_000_000;
pub const GIGAWEI: Balance = 1_000_000_000;
pub const MICROUNIT: Balance = 1_000_000_000_000;
pub const MILLIUNIT: Balance = 1_000_000_000_000_000;
pub const UNIT: Balance = 1_000_000_000_000_000_000;
pub const KILOUNIT: Balance = 1_000_000_000_000_000_000_000;
pub const TRANSACTION_BYTE_FEE: Balance = 1 * GIGAWEI * SUPPLY_FACTOR;
pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT * SUPPLY_FACTOR;
pub const WEIGHT_FEE: Balance = 50 * KILOWEI * SUPPLY_FACTOR;
pub const fn deposit(items: u32, bytes: u32) -> Balance {
items as Balance * 1 * UNIT * SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
}
}
/// Maximum weight per block
// TODO: multiply MAXIMUM_BLOCK_WEIGHT times 4 when async backing will be definitly enabled
pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND, u64::MAX)
.saturating_div(2)
.set_proof_size(cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64);
pub const MILLISECS_PER_BLOCK: u64 = 6_000;
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
pub const HOURS: BlockNumber = MINUTES * 60;
pub const DAYS: BlockNumber = HOURS * 24;
pub const WEEKS: BlockNumber = DAYS * 7;
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
/// to even the core data structures.
pub mod opaque {
use super::*;
pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
impl_opaque_keys! {
pub struct SessionKeys {
pub nimbus: AuthorInherent,
pub vrf: session_keys_primitives::VrfSessionKey,
}
}
}
/// This runtime version.
/// The spec_version is composed of 2x2 digits. The first 2 digits represent major changes
/// that can't be skipped, such as data migration upgrades. The last 2 digits represent minor
/// changes which can be skipped.
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("moonbase"),
impl_name: create_runtime_str!("moonbase"),
authoring_version: 4,
spec_version: 2900,
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
transaction_version: 2,
state_version: 0,
};
/// The version information used to identify this runtime when compiled natively.
#[cfg(feature = "std")]
pub fn native_version() -> NativeVersion {
NativeVersion {
runtime_version: VERSION,
can_author_with: Default::default(),
}
}
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
pub const NORMAL_WEIGHT: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_mul(3).saturating_div(4);
// Here we assume Ethereum's base fee of 21000 gas and convert to weight, but we
// subtract roughly the cost of a balance transfer from it (about 1/3 the cost)
// and some cost to account for per-byte-fee.
// TODO: we should use benchmarking's overhead feature to measure this
pub const EXTRINSIC_BASE_WEIGHT: Weight = Weight::from_parts(10000 * WEIGHT_PER_GAS, 0);
pub struct RuntimeBlockWeights;
impl Get<frame_system::limits::BlockWeights> for RuntimeBlockWeights {
fn get() -> frame_system::limits::BlockWeights {
frame_system::limits::BlockWeights::builder()
.for_class(DispatchClass::Normal, |weights| {
weights.base_extrinsic = EXTRINSIC_BASE_WEIGHT;
weights.max_total = NORMAL_WEIGHT.into();
})
.for_class(DispatchClass::Operational, |weights| {
weights.max_total = MAXIMUM_BLOCK_WEIGHT.into();
weights.reserved = (MAXIMUM_BLOCK_WEIGHT - NORMAL_WEIGHT).into();
})
.avg_block_initialization(Perbill::from_percent(10))
.build()
.expect("Provided BlockWeight definitions are valid, qed")
}
}
parameter_types! {
pub const Version: RuntimeVersion = VERSION;
/// TODO: this is left here so that `impl_runtime_apis_plus_common` will find the same type for
/// `BlockWeights` in all runtimes. It can probably be removed once the custom
/// `RuntimeBlockWeights` has been pushed to each runtime.
pub BlockWeights: frame_system::limits::BlockWeights = RuntimeBlockWeights::get();
/// We allow for 5 MB blocks.
pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength
::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
}
impl frame_system::Config for Runtime {
/// The identifier used to distinguish between accounts.
type AccountId = AccountId;
/// The aggregated dispatch type that is available for extrinsics.
type RuntimeCall = RuntimeCall;
/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
type Lookup = IdentityLookup<AccountId>;
/// The index type for storing how many extrinsics an account has signed.
type Nonce = Index;
/// The index type for blocks.
type Block = Block;
/// The type for hashing blocks and tries.
type Hash = Hash;
/// The hashing algorithm used.
type Hashing = BlakeTwo256;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
/// The ubiquitous origin type.
type RuntimeOrigin = RuntimeOrigin;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = ConstU32<256>;
/// Maximum weight of each block. With a default weight system of 1byte == 1weight, 4mb is ok.
type BlockWeights = RuntimeBlockWeights;
/// Maximum size of all encoded transactions (in bytes) that are allowed in one block.
type BlockLength = BlockLength;
/// Runtime version.
type Version = Version;
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
type DbWeight = RocksDbWeight;
type BaseCallFilter = MaintenanceMode;
type SystemWeightInfo = ();
/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
type SS58Prefix = ConstU16<1287>;
type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
type MaxConsumers = frame_support::traits::ConstU32<16>;
}
impl pallet_utility::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type PalletsOrigin = OriginCaller;
type WeightInfo = moonbeam_weights::pallet_utility::WeightInfo<Runtime>;
}
impl pallet_timestamp::Config for Runtime {
/// A timestamp: milliseconds since the unix epoch.
type Moment = u64;
type OnTimestampSet = ();
type MinimumPeriod = ConstU64<3000>;
type WeightInfo = moonbeam_weights::pallet_timestamp::WeightInfo<Runtime>;
}
impl pallet_balances::Config for Runtime {
type MaxReserves = ConstU32<50>;
type ReserveIdentifier = [u8; 4];
type MaxLocks = ConstU32<50>;
/// The type for recording an account's balance.
type Balance = Balance;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
type DustRemoval = ();
type ExistentialDeposit = ConstU128<0>;
type AccountStore = System;
type FreezeIdentifier = ();
type MaxFreezes = ConstU32<0>;
type RuntimeHoldReason = RuntimeHoldReason;
type RuntimeFreezeReason = RuntimeFreezeReason;
type MaxHolds = ConstU32<1>;
type WeightInfo = moonbeam_weights::pallet_balances::WeightInfo<Runtime>;
}
pub struct DealWithFees<R>(sp_std::marker::PhantomData<R>);
impl<R> OnUnbalanced<Credit<R::AccountId, pallet_balances::Pallet<R>>> for DealWithFees<R>
where
R: pallet_balances::Config + pallet_treasury::Config,
{
// this seems to be called for substrate-based transactions
fn on_unbalanceds<B>(
mut fees_then_tips: impl Iterator<Item = Credit<R::AccountId, pallet_balances::Pallet<R>>>,
) {
if let Some(fees) = fees_then_tips.next() {
// for fees, 80% are burned, 20% to the treasury
let (_, to_treasury) = fees.ration(80, 20);
// Balances pallet automatically burns dropped Credits by decreasing
// total_supply accordingly
ResolveTo::<TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(
to_treasury,
);
// handle tip if there is one
if let Some(tip) = fees_then_tips.next() {
// for now we use the same burn/treasury strategy used for regular fees
let (_, to_treasury) = tip.ration(80, 20);
ResolveTo::<TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(
to_treasury,
);
}
}
}
// this is called from pallet_evm for Ethereum-based transactions
// (technically, it calls on_unbalanced, which calls this when non-zero)
fn on_nonzero_unbalanced(amount: Credit<R::AccountId, pallet_balances::Pallet<R>>) {
// Balances pallet automatically burns dropped Credits by decreasing
// total_supply accordingly
let (_, to_treasury) = amount.ration(80, 20);
ResolveTo::<TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(to_treasury);
}
}
pub struct LengthToFee;
impl WeightToFeePolynomial for LengthToFee {
type Balance = Balance;
fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
smallvec![
WeightToFeeCoefficient {
degree: 1,
coeff_frac: Perbill::zero(),
coeff_integer: currency::TRANSACTION_BYTE_FEE,
negative: false,
},
WeightToFeeCoefficient {
degree: 3,
coeff_frac: Perbill::zero(),
coeff_integer: 1 * currency::SUPPLY_FACTOR,
negative: false,
},
]
}
}
impl pallet_transaction_payment::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type OnChargeTransaction = FungibleAdapter<Balances, DealWithFees<Runtime>>;
type OperationalFeeMultiplier = ConstU8<5>;
type WeightToFee = ConstantMultiplier<Balance, ConstU128<{ currency::WEIGHT_FEE }>>;
type LengthToFee = LengthToFee;
type FeeMultiplierUpdate = FastAdjustingFeeUpdate<Runtime>;
}
impl pallet_sudo::Config for Runtime {
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = moonbeam_weights::pallet_sudo::WeightInfo<Runtime>;
}
impl pallet_evm_chain_id::Config for Runtime {}
/// Current approximation of the gas/s consumption considering
/// EVM execution over compiled WASM (on 4.4Ghz CPU).
/// Given the 500ms Weight, from which 75% only are used for transactions,
/// the total EVM execution gas limit is: GAS_PER_SECOND * 0.500 * 0.75 ~= 15_000_000.
pub const GAS_PER_SECOND: u64 = 40_000_000;
/// Approximate ratio of the amount of Weight per Gas.
/// u64 works for approximations because Weight is a very small unit compared to gas.
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
/// The highest amount of new storage that can be created in a block (40KB).
pub const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
parameter_types! {
pub BlockGasLimit: U256
= U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS);
/// The portion of the `NORMAL_DISPATCH_RATIO` that we adjust the fees with. Blocks filled less
/// than this will decrease the weight and more will increase.
pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25);
/// The adjustment variable of the runtime. Higher values will cause `TargetBlockFullness` to
/// change the fees more rapidly. This fast multiplier responds by doubling/halving in
/// approximately one hour at extreme block congestion levels.
pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(4, 1_000);
/// Minimum amount of the multiplier. This value cannot be too low. A test case should ensure
/// that combined with `AdjustmentVariable`, we can recover from the minimum.
/// See `multiplier_can_grow_from_zero` in integration_tests.rs.
pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 10);
/// Maximum multiplier. We pick a value that is expensive but not impossibly so; it should act
/// as a safety net.
pub MaximumMultiplier: Multiplier = Multiplier::from(100_000u128);
pub PrecompilesValue: MoonbasePrecompiles<Runtime> = MoonbasePrecompiles::<_>::new();
pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0);
/// The amount of gas per pov. A ratio of 4 if we convert ref_time to gas and we compare
/// it with the pov_size for a block. E.g.
/// ceil(
/// (max_extrinsic.ref_time() / max_extrinsic.proof_size()) / WEIGHT_PER_GAS
/// )
pub const GasLimitPovSizeRatio: u64 = 4;
/// The amount of gas per storage (in bytes): BLOCK_GAS_LIMIT / BLOCK_STORAGE_LIMIT
/// (15_000_000 / 40kb)
pub GasLimitStorageGrowthRatio: u64 = 366;
}
pub struct TransactionPaymentAsGasPrice;
impl FeeCalculator for TransactionPaymentAsGasPrice {
fn min_gas_price() -> (U256, Weight) {
// TODO: transaction-payment differs from EIP-1559 in that its tip and length fees are not
// scaled by the multiplier, which means its multiplier will be overstated when
// applied to an ethereum transaction
// note: transaction-payment uses both a congestion modifier (next_fee_multiplier, which is
// updated once per block in on_finalize) and a 'WeightToFee' implementation. Our
// runtime implements this as a 'ConstantModifier', so we can get away with a simple
// multiplication here.
// It is imperative that `saturating_mul_int` be performed as late as possible in the
// expression since it involves fixed point multiplication with a division by a fixed
// divisor. This leads to truncation and subsequent precision loss if performed too early.
// This can lead to min_gas_price being same across blocks even if the multiplier changes.
// There's still some precision loss when the final `gas_price` (used_gas * min_gas_price)
// is computed in frontier, but that's currently unavoidable.
let min_gas_price = TransactionPayment::next_fee_multiplier()
.saturating_mul_int(currency::WEIGHT_FEE.saturating_mul(WEIGHT_PER_GAS as u128));
(
min_gas_price.into(),
<Runtime as frame_system::Config>::DbWeight::get().reads(1),
)
}
}
/// A "Fast" TargetedFeeAdjustment. Parameters chosen based on model described here:
/// https://research.web3.foundation/en/latest/polkadot/overview/2-token-economics.html#-1.-fast-adjusting-mechanism // editorconfig-checker-disable-line
///
/// The adjustment algorithm boils down to:
///
/// diff = (previous_block_weight - target) / maximum_block_weight
/// next_multiplier = prev_multiplier * (1 + (v * diff) + ((v * diff)^2 / 2))
/// assert(next_multiplier > min)
/// where: v is AdjustmentVariable
/// target is TargetBlockFullness
/// min is MinimumMultiplier
pub type FastAdjustingFeeUpdate<R> = TargetedFeeAdjustment<
R,
TargetBlockFullness,
AdjustmentVariable,
MinimumMultiplier,
MaximumMultiplier,
>;
/// The author inherent provides an AccountId, but pallet evm needs an H160.
/// This simple adapter makes the conversion for any types T, U such that T: Into<U>
pub struct FindAuthorAdapter<T, U, Inner>(sp_std::marker::PhantomData<(T, U, Inner)>);
impl<T, U, Inner> FindAuthor<U> for FindAuthorAdapter<T, U, Inner>
where
T: Into<U>,
Inner: FindAuthor<T>,
{
fn find_author<'a, I>(digests: I) -> Option<U>
where
I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
{
Inner::find_author(digests).map(Into::into)
}
}
moonbeam_runtime_common::impl_on_charge_evm_transaction!();
impl pallet_evm::Config for Runtime {
type FeeCalculator = TransactionPaymentAsGasPrice;
type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
type WeightPerGas = WeightPerGas;
type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
type CallOrigin = EnsureAddressRoot<AccountId>;
type WithdrawOrigin = EnsureAddressNever<AccountId>;
type AddressMapping = IdentityAddressMapping;
type Currency = Balances;
type RuntimeEvent = RuntimeEvent;
type Runner = pallet_evm::runner::stack::Runner<Self>;
type PrecompilesType = MoonbasePrecompiles<Self>;
type PrecompilesValue = PrecompilesValue;
type ChainId = EthereumChainId;
type OnChargeTransaction = OnChargeEVMTransaction<DealWithFees<Runtime>>;
type BlockGasLimit = BlockGasLimit;
type FindAuthor = FindAuthorAdapter<AccountId20, H160, AuthorInherent>;
type OnCreate = ();
type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
type SuicideQuickClearLimit = ConstU32<0>;
type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
type Timestamp = crate::timestamp::RelayTimestamp;
type WeightInfo = moonbeam_weights::pallet_evm::WeightInfo<Runtime>;
}
parameter_types! {
pub MaximumSchedulerWeight: Weight = NORMAL_DISPATCH_RATIO * RuntimeBlockWeights::get().max_block;
pub const NoPreimagePostponement: Option<u32> = Some(10);
}
impl pallet_scheduler::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
type PalletsOrigin = OriginCaller;
type RuntimeCall = RuntimeCall;
type MaximumWeight = MaximumSchedulerWeight;
type ScheduleOrigin = EnsureRoot<AccountId>;
type MaxScheduledPerBlock = ConstU32<50>;
type WeightInfo = moonbeam_weights::pallet_scheduler::WeightInfo<Runtime>;
type OriginPrivilegeCmp = EqualPrivilegeOnly;
type Preimages = Preimage;
}
parameter_types! {
pub const PreimageBaseDeposit: Balance = 5 * currency::UNIT * currency::SUPPLY_FACTOR ;
pub const PreimageByteDeposit: Balance = currency::STORAGE_BYTE_FEE;
pub const PreimageHoldReason: RuntimeHoldReason =
RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
}
impl pallet_preimage::Config for Runtime {
type WeightInfo = moonbeam_weights::pallet_preimage::WeightInfo<Runtime>;
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type ManagerOrigin = EnsureRoot<AccountId>;
type Consideration = HoldConsideration<
AccountId,
Balances,
PreimageHoldReason,
LinearStoragePrice<PreimageBaseDeposit, PreimageByteDeposit, Balance>,
>;
}
parameter_types! {
pub const ProposalBond: Permill = Permill::from_percent(5);
pub const TreasuryId: PalletId = PalletId(*b"pc/trsry");
pub TreasuryAccount: AccountId = Treasury::account_id();
}
type TreasuryApproveOrigin = EitherOfDiverse<
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionAtLeast<AccountId, TreasuryCouncilInstance, 3, 5>,
>;
type TreasuryRejectOrigin = EitherOfDiverse<
EnsureRoot<AccountId>,
pallet_collective::EnsureProportionMoreThan<AccountId, TreasuryCouncilInstance, 1, 2>,
>;
impl pallet_treasury::Config for Runtime {
type PalletId = TreasuryId;
type Currency = Balances;
// At least three-fifths majority of the council is required (or root) to approve a proposal
type ApproveOrigin = TreasuryApproveOrigin;
// More than half of the council is required (or root) to reject a proposal
type RejectOrigin = TreasuryRejectOrigin;
type RuntimeEvent = RuntimeEvent;
// If spending proposal rejected, transfer proposer bond to treasury
type OnSlash = Treasury;
type ProposalBond = ProposalBond;
type ProposalBondMinimum = ConstU128<{ 1 * currency::UNIT * currency::SUPPLY_FACTOR }>;
type SpendPeriod = ConstU32<{ 6 * DAYS }>;
type Burn = ();
type BurnDestination = ();
type MaxApprovals = ConstU32<100>;
type WeightInfo = moonbeam_weights::pallet_treasury::WeightInfo<Runtime>;
type SpendFunds = ();
type ProposalBondMaximum = ();
type SpendOrigin = frame_support::traits::NeverEnsureOrigin<Balance>; // Same as Polkadot
type AssetKind = ();
type Beneficiary = AccountId;
type BeneficiaryLookup = IdentityLookup<AccountId>;
type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
type BalanceConverter = UnityAssetBalanceConversion;
type PayoutPeriod = ConstU32<0>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = BenchmarkHelper;
}
type IdentityForceOrigin =
EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
type IdentityRegistrarOrigin =
EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
impl pallet_identity::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
// Add one item in storage and take 258 bytes
type BasicDeposit = ConstU128<{ currency::deposit(1, 258) }>;
// Not add any item to the storage but takes 66 bytes
type FieldDeposit = ConstU128<{ currency::deposit(0, 66) }>;
// Add one item in storage and take 53 bytes
type SubAccountDeposit = ConstU128<{ currency::deposit(1, 53) }>;
type MaxSubAccounts = ConstU32<100>;
type MaxAdditionalFields = ConstU32<100>;
type IdentityInformation = pallet_identity::simple::IdentityInfo<Self::MaxAdditionalFields>;
type MaxRegistrars = ConstU32<20>;
type Slashed = Treasury;
type ForceOrigin = IdentityForceOrigin;
type RegistrarOrigin = IdentityRegistrarOrigin;
type WeightInfo = moonbeam_weights::pallet_identity::WeightInfo<Runtime>;
}
pub struct TransactionConverter;
impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {
fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {
UncheckedExtrinsic::new_unsigned(
pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
)
}
}
impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {
fn convert_transaction(
&self,
transaction: pallet_ethereum::Transaction,
) -> opaque::UncheckedExtrinsic {
let extrinsic = UncheckedExtrinsic::new_unsigned(
pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
);
let encoded = extrinsic.encode();
opaque::UncheckedExtrinsic::decode(&mut &encoded[..])
.expect("Encoded extrinsic is always valid")
}
}
parameter_types! {
pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
}
impl pallet_ethereum::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;
type PostLogContent = PostBlockAndTxnHashes;
type ExtraDataLength = ConstU32<30>;
}
pub struct EthereumXcmEnsureProxy;
impl xcm_primitives::EnsureProxy<AccountId> for EthereumXcmEnsureProxy {
fn ensure_ok(delegator: AccountId, delegatee: AccountId) -> Result<(), &'static str> {
// The EVM implicitely contains an Any proxy, so we only allow for "Any" proxies
let def: pallet_proxy::ProxyDefinition<AccountId, ProxyType, BlockNumber> =
pallet_proxy::Pallet::<Runtime>::find_proxy(
&delegator,
&delegatee,
Some(ProxyType::Any),
)
.map_err(|_| "proxy error: expected `ProxyType::Any`")?;
// We only allow to use it for delay zero proxies, as the call will immediatly be executed
ensure!(def.delay.is_zero(), "proxy delay is Non-zero`");
Ok(())
}
}
impl pallet_ethereum_xcm::Config for Runtime {
type InvalidEvmTransactionError = pallet_ethereum::InvalidTransactionWrapper;
type ValidatedTransaction = pallet_ethereum::ValidatedTransaction<Self>;
type XcmEthereumOrigin = pallet_ethereum_xcm::EnsureXcmEthereumTransaction;
type ReservedXcmpWeight = ReservedXcmpWeight;
type EnsureProxy = EthereumXcmEnsureProxy;
type ControllerOrigin = EnsureRoot<AccountId>;
}
parameter_types! {
pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
}
/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included
/// into the relay chain.
const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
/// How many parachain blocks are processed by the relay chain per parent. Limits the
/// number of blocks authored per slot.
const BLOCK_PROCESSING_VELOCITY: u32 = 2;
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
Runtime,
BLOCK_PROCESSING_VELOCITY,
UNINCLUDED_SEGMENT_CAPACITY,
>;
impl cumulus_pallet_parachain_system::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type OnSystemEvent = ();
type SelfParaId = ParachainInfo;
type DmpMessageHandler = MaintenanceMode;
type ReservedDmpWeight = ReservedDmpWeight;
type OutboundXcmpMessageSource = XcmpQueue;
type XcmpMessageHandler = XcmpQueue;
type ReservedXcmpWeight = ReservedXcmpWeight;
type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
type ConsensusHook = crate::timestamp::ConsensusHookWrapperForRelayTimestamp<ConsensusHook>;
}
impl parachain_info::Config for Runtime {}
pub struct OnNewRound;
impl pallet_parachain_staking::OnNewRound for OnNewRound {
fn on_new_round(round_index: pallet_parachain_staking::RoundIndex) -> Weight {
MoonbeamOrbiters::on_new_round(round_index)
}
}
pub struct PayoutCollatorOrOrbiterReward;
impl pallet_parachain_staking::PayoutCollatorReward<Runtime> for PayoutCollatorOrOrbiterReward {
fn payout_collator_reward(
for_round: pallet_parachain_staking::RoundIndex,
collator_id: AccountId,
amount: Balance,
) -> Weight {
let extra_weight = if MoonbeamOrbiters::is_orbiter(for_round, collator_id) {
MoonbeamOrbiters::distribute_rewards(for_round, collator_id, amount)
} else {
ParachainStaking::mint_collator_reward(for_round, collator_id, amount)
};
<Runtime as frame_system::Config>::DbWeight::get()
.reads(1)
.saturating_add(extra_weight)
}
}
pub struct OnInactiveCollator;
impl pallet_parachain_staking::OnInactiveCollator<Runtime> for OnInactiveCollator {
fn on_inactive_collator(
collator_id: AccountId,
round: pallet_parachain_staking::RoundIndex,
) -> Result<Weight, DispatchErrorWithPostInfo<PostDispatchInfo>> {
let extra_weight = if !MoonbeamOrbiters::is_orbiter(round, collator_id.clone()) {
ParachainStaking::go_offline_inner(collator_id)?;
<Runtime as pallet_parachain_staking::Config>::WeightInfo::go_offline(
pallet_parachain_staking::MAX_CANDIDATES,
)
} else {
Weight::zero()
};
Ok(<Runtime as frame_system::Config>::DbWeight::get()
.reads(1)
.saturating_add(extra_weight))
}
}
type MonetaryGovernanceOrigin =
EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
pub struct RelayChainSlotProvider;
impl Get<Slot> for RelayChainSlotProvider {
fn get() -> Slot {
let slot_info = pallet_async_backing::pallet::Pallet::<Runtime>::slot_info();
slot_info.unwrap_or_default().0
}
}
impl pallet_parachain_staking::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type MonetaryGovernanceOrigin = MonetaryGovernanceOrigin;
/// Minimum round length is 2 minutes (10 * 12 second block times)
type MinBlocksPerRound = ConstU32<10>;
/// If a collator doesn't produce any block on this number of rounds, it is notified as inactive
type MaxOfflineRounds = ConstU32<2>;
/// Rounds before the collator leaving the candidates request can be executed
type LeaveCandidatesDelay = ConstU32<2>;
/// Rounds before the candidate bond increase/decrease can be executed
type CandidateBondLessDelay = ConstU32<2>;
/// Rounds before the delegator exit can be executed
type LeaveDelegatorsDelay = ConstU32<2>;
/// Rounds before the delegator revocation can be executed
type RevokeDelegationDelay = ConstU32<2>;
/// Rounds before the delegator bond increase/decrease can be executed
type DelegationBondLessDelay = ConstU32<2>;
/// Rounds before the reward is paid
type RewardPaymentDelay = ConstU32<2>;
/// Minimum collators selected per round, default at genesis and minimum forever after
type MinSelectedCandidates = ConstU32<8>;
/// Maximum top delegations per candidate
type MaxTopDelegationsPerCandidate = ConstU32<300>;
/// Maximum bottom delegations per candidate
type MaxBottomDelegationsPerCandidate = ConstU32<50>;
/// Maximum delegations per delegator
type MaxDelegationsPerDelegator = ConstU32<100>;
/// Minimum stake required to be reserved to be a candidate
type MinCandidateStk = ConstU128<{ 500 * currency::UNIT * currency::SUPPLY_FACTOR }>;
/// Minimum stake required to be reserved to be a delegator
type MinDelegation = ConstU128<{ 1 * currency::UNIT * currency::SUPPLY_FACTOR }>;
type BlockAuthor = AuthorInherent;
type OnCollatorPayout = ();
type PayoutCollatorReward = PayoutCollatorOrOrbiterReward;
type OnInactiveCollator = OnInactiveCollator;
type OnNewRound = OnNewRound;
type SlotProvider = RelayChainSlotProvider;
type WeightInfo = moonbeam_weights::pallet_parachain_staking::WeightInfo<Runtime>;
type MaxCandidates = ConstU32<200>;
type SlotsPerYear = ConstU32<{ 31_557_600 / 6 }>;
}
impl pallet_author_inherent::Config for Runtime {
type SlotBeacon = RelaychainDataProvider<Self>;
type AccountLookup = MoonbeamOrbiters;
type CanAuthor = AuthorFilter;
type AuthorId = AccountId;
type WeightInfo = moonbeam_weights::pallet_author_inherent::WeightInfo<Runtime>;
}
#[cfg(test)]
mod mock {
use super::*;
pub struct MockRandomness;
impl frame_support::traits::Randomness<H256, BlockNumber> for MockRandomness {
fn random(subject: &[u8]) -> (H256, BlockNumber) {
(H256(sp_io::hashing::blake2_256(subject)), 0)
}
}
}
impl pallet_author_slot_filter::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
#[cfg(not(test))]
type RandomnessSource = Randomness;
#[cfg(test)]
type RandomnessSource = mock::MockRandomness;
type PotentialAuthors = ParachainStaking;
type WeightInfo = moonbeam_weights::pallet_author_slot_filter::WeightInfo<Runtime>;
}
impl pallet_async_backing::Config for Runtime {
type AllowMultipleBlocksPerSlot = ConstBool<true>;
type GetAndVerifySlot = pallet_async_backing::RelaySlot;
}
parameter_types! {
pub const InitializationPayment: Perbill = Perbill::from_percent(30);
pub const RelaySignaturesThreshold: Perbill = Perbill::from_percent(100);
pub const SignatureNetworkIdentifier: &'static [u8] = b"moonbase-";
}
impl pallet_crowdloan_rewards::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Initialized = ConstBool<false>;
type InitializationPayment = InitializationPayment;
type MaxInitContributors = ConstU32<500>;
// TODO to be revisited
type MinimumReward = ConstU128<0>;
type RewardCurrency = Balances;
type RelayChainAccountId = [u8; 32];
type RewardAddressAssociateOrigin = EnsureSigned<Self::AccountId>;
type RewardAddressChangeOrigin = EnsureSigned<Self::AccountId>;
type RewardAddressRelayVoteThreshold = RelaySignaturesThreshold;
type SignatureNetworkIdentifier = SignatureNetworkIdentifier;
type VestingBlockNumber = cumulus_primitives_core::relay_chain::BlockNumber;
type VestingBlockProvider = RelaychainDataProvider<Self>;
type WeightInfo = moonbeam_weights::pallet_crowdloan_rewards::WeightInfo<Runtime>;
}
// This is a simple session key manager. It should probably either work with, or be replaced
// entirely by pallet sessions
impl pallet_author_mapping::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type DepositCurrency = Balances;
type DepositAmount = ConstU128<{ 100 * currency::UNIT * currency::SUPPLY_FACTOR }>;
type Keys = session_keys_primitives::VrfId;
type WeightInfo = moonbeam_weights::pallet_author_mapping::WeightInfo<Runtime>;
}
/// The type used to represent the kinds of proxying allowed.
#[derive(
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Encode,
Decode,
Debug,
MaxEncodedLen,
TypeInfo,
Serialize,
Deserialize,
)]
pub enum ProxyType {
/// All calls can be proxied. This is the trivial/most permissive filter.
Any = 0,
/// Only extrinsics that do not transfer funds.
NonTransfer = 1,
/// Only extrinsics related to governance (democracy and collectives).
Governance = 2,
/// Only extrinsics related to staking.
Staking = 3,
/// Allow to veto an announced proxy call.
CancelProxy = 4,
/// Allow extrinsic related to Balances.
Balances = 5,
/// Allow extrinsic related to AuthorMapping.
AuthorMapping = 6,
/// Allow extrinsic related to IdentityJudgement.
IdentityJudgement = 7,
}
impl Default for ProxyType {
fn default() -> Self {
Self::Any
}
}
fn is_governance_precompile(precompile_name: &precompiles::PrecompileName) -> bool {
matches!(
precompile_name,
PrecompileName::DemocracyPrecompile
| PrecompileName::TreasuryCouncilInstance
| PrecompileName::ReferendaPrecompile
| PrecompileName::ConvictionVotingPrecompile
| PrecompileName::PreimagePrecompile
| PrecompileName::OpenTechCommitteeInstance,
)
}
// Be careful: Each time this filter is modified, the substrate filter must also be modified
// consistently.
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {
fn is_evm_proxy_call_allowed(
&self,
call: &pallet_evm_precompile_proxy::EvmSubCall,
recipient_has_code: bool,
gas: u64,
) -> precompile_utils::EvmResult<bool> {
Ok(match self {
ProxyType::Any => true,
ProxyType::NonTransfer => {
call.value == U256::zero()
&& match PrecompileName::from_address(call.to.0) {
Some(
PrecompileName::AuthorMappingPrecompile
| PrecompileName::IdentityPrecompile
| PrecompileName::ParachainStakingPrecompile,
) => true,
Some(ref precompile) if is_governance_precompile(precompile) => true,
_ => false,
}
}
ProxyType::Governance => {
call.value == U256::zero()
&& matches!(
PrecompileName::from_address(call.to.0),
Some(ref precompile) if is_governance_precompile(precompile)
)
}
ProxyType::Staking => {
call.value == U256::zero()
&& matches!(
PrecompileName::from_address(call.to.0),
Some(
PrecompileName::AuthorMappingPrecompile
| PrecompileName::ParachainStakingPrecompile
)
)
}
// The proxy precompile does not contain method cancel_proxy
ProxyType::CancelProxy => false,
ProxyType::Balances => {
// Allow only "simple" accounts as recipient (no code nor precompile).
// Note: Checking the presence of the code is not enough because some precompiles
// have no code.
!recipient_has_code
&& !precompile_utils::precompile_set::is_precompile_or_fail::<Runtime>(
call.to.0, gas,
)?
}