-
Notifications
You must be signed in to change notification settings - Fork 416
/
Copy pathlib.rs
2094 lines (1862 loc) · 78.4 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
// This file is part of Astar.
// Copyright (C) Stake Technologies Pte.Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later
// Astar 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.
// Astar 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 Astar. If not, see <http://www.gnu.org/licenses/>.
#![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 = "256"]
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
use frame_support::{
construct_runtime, genesis_builder_helper, parameter_types,
traits::{
fungible::{Balanced, Credit, HoldConsideration},
AsEnsureOriginWithArg, ConstU128, ConstU32, ConstU64, Contains, EqualPrivilegeOnly,
FindAuthor, Get, InsideBoth, InstanceFilter, LinearStoragePrice, Nothing, OnFinalize,
WithdrawReasons,
},
weights::{
constants::{ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND},
ConstantMultiplier, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients,
WeightToFeePolynomial,
},
ConsensusEngineId, PalletId,
};
use frame_system::{
limits::{BlockLength, BlockWeights},
EnsureRoot, EnsureSigned, EnsureWithSuccess,
};
use pallet_ethereum::PostLogContent;
use pallet_evm::{FeeCalculator, GasWeightMapping, Runner};
use pallet_evm_precompile_assets_erc20::AddressToAssetId;
use pallet_grandpa::{fg_primitives, AuthorityList as GrandpaAuthorityList};
use pallet_transaction_payment::{FungibleAdapter, Multiplier, TargetedFeeAdjustment};
use parity_scale_codec::{Compact, Decode, Encode, MaxEncodedLen};
use sp_api::impl_runtime_apis;
use sp_core::{crypto::KeyTypeId, sr25519, ConstBool, OpaqueMetadata, H160, H256, U256};
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
traits::{
AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto,
DispatchInfoOf, Dispatchable, NumberFor, PostDispatchInfoOf, UniqueSaturatedInto,
},
transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError},
ApplyExtrinsicResult, FixedPointNumber, FixedU128, Perbill, Permill, Perquintill, RuntimeDebug,
};
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
use astar_primitives::{
dapp_staking::{
CycleConfiguration, DAppId, EraNumber, PeriodNumber, RankedTier, SmartContract,
StandardTierSlots,
},
evm::{EvmRevertCodeHandler, HashedDefaultMappings},
governance::{
CommunityCouncilCollectiveInst, CommunityCouncilMembershipInst, CommunityTreasuryInst,
EnsureRootOrAllMainCouncil, EnsureRootOrAllTechnicalCommittee,
EnsureRootOrHalfTechnicalCommittee, EnsureRootOrTwoThirdsCommunityCouncil,
EnsureRootOrTwoThirdsMainCouncil, EnsureRootOrTwoThirdsTechnicalCommittee,
MainCouncilCollectiveInst, MainCouncilMembershipInst, MainTreasuryInst,
TechnicalCommitteeCollectiveInst, TechnicalCommitteeMembershipInst,
},
Address, AssetId, Balance, BlockNumber, Hash, Header, Nonce,
};
pub use astar_primitives::{AccountId, Signature};
pub use pallet_dapp_staking::TierThreshold;
pub use crate::precompiles::WhitelistedCalls;
#[cfg(feature = "std")]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
pub use frame_system::Call as SystemCall;
pub use pallet_balances::Call as BalancesCall;
pub use pallet_grandpa::AuthorityId as GrandpaId;
pub use pallet_inflation::InflationParameters;
pub use pallet_timestamp::Call as TimestampCall;
pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
#[cfg(feature = "std")]
/// Wasm binary unwrapped. If built with `BUILD_DUMMY_WASM_BINARY`, the function panics.
pub fn wasm_binary_unwrap() -> &'static [u8] {
WASM_BINARY.expect(
"Development wasm binary is not available. This means the client is \
built with `BUILD_DUMMY_WASM_BINARY` flag and it is only usable for \
production chains. Please rebuild with the flag disabled.",
)
}
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("local"),
impl_name: create_runtime_str!("local"),
authoring_version: 1,
spec_version: 1,
impl_version: 1,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
state_version: 1,
};
impl_opaque_keys! {
pub struct SessionKeys {
pub aura: Aura,
pub grandpa: Grandpa,
}
}
mod precompiles;
pub use precompiles::{LocalPrecompiles, ASSET_PRECOMPILE_ADDRESS_PREFIX};
pub type Precompiles = LocalPrecompiles<Runtime>;
mod chain_extensions;
pub use chain_extensions::LocalChainExtensions;
pub mod genesis_config;
mod weights;
/// Constant values used within the runtime.
pub const MICROAST: Balance = 1_000_000_000_000;
pub const MILLIAST: Balance = 1_000 * MICROAST;
pub const AST: Balance = 1_000 * MILLIAST;
pub const STORAGE_BYTE_FEE: Balance = 100 * MICROAST;
/// Charge fee for stored bytes and items.
pub const fn deposit(items: u32, bytes: u32) -> Balance {
items as Balance * 1 * AST + (bytes as Balance) * STORAGE_BYTE_FEE
}
/// This determines the average expected block time that we are targeting.
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
/// up by `pallet_aura` to implement `fn slot_duration()`.
///
/// Change this to adjust the block time.
pub const MILLISECS_PER_BLOCK: u64 = 2000;
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
// Time is measured by number of blocks.
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
pub const HOURS: BlockNumber = MINUTES * 60;
pub const DAYS: BlockNumber = HOURS * 24;
impl AddressToAssetId<AssetId> for Runtime {
fn address_to_asset_id(address: H160) -> Option<AssetId> {
let mut data = [0u8; 16];
let address_bytes: [u8; 20] = address.into();
if ASSET_PRECOMPILE_ADDRESS_PREFIX.eq(&address_bytes[0..4]) {
data.copy_from_slice(&address_bytes[4..20]);
Some(u128::from_be_bytes(data))
} else {
None
}
}
fn asset_id_to_address(asset_id: AssetId) -> H160 {
let mut data = [0u8; 20];
data[0..4].copy_from_slice(ASSET_PRECOMPILE_ADDRESS_PREFIX);
data[4..20].copy_from_slice(&asset_id.to_be_bytes());
H160::from(data)
}
}
/// 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(),
}
}
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used
/// by Operational extrinsics.
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
parameter_types! {
pub const Version: RuntimeVersion = VERSION;
pub const BlockHashCount: BlockNumber = 2400;
/// We allow for 1 seconds of compute with a 2 second average block time.
pub RuntimeBlockWeights: BlockWeights = BlockWeights
::with_sensible_defaults(Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND, u64::MAX), NORMAL_DISPATCH_RATIO);
pub RuntimeBlockLength: BlockLength = BlockLength
::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
pub const SS58Prefix: u8 = 5;
}
// Configure FRAME pallets to include in runtime.
impl frame_system::Config for Runtime {
/// The basic call filter to use in dispatchable.
type BaseCallFilter = InsideBoth<SafeMode, TxPause>;
/// Block & extrinsics weights: base values and limits.
type BlockWeights = RuntimeBlockWeights;
/// The maximum length of a block (in bytes).
type BlockLength = RuntimeBlockLength;
/// 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 = (AccountIdLookup<AccountId, ()>, UnifiedAccounts);
/// The nonce type for storing how many extrinsics an account has signed.
type Nonce = Nonce;
/// The 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;
/// The aggregated RuntimeTask type.
type RuntimeTask = RuntimeTask;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = BlockHashCount;
/// The weight of database operations that the runtime can invoke.
type DbWeight = RocksDbWeight;
/// Version of the runtime.
type Version = Version;
/// Converts a module to the index of the module in `construct_runtime!`.
///
/// This type is being generated by `construct_runtime!`.
type PalletInfo = PalletInfo;
/// What to do if a new account is created.
type OnNewAccount = ();
/// What to do if an account is fully reaped from the system.
type OnKilledAccount = pallet_unified_accounts::KillAccountMapping<Self>;
/// The data to be stored in an account.
type AccountData = pallet_balances::AccountData<Balance>;
/// Weight information for the extrinsics of this pallet.
type SystemWeightInfo = frame_system::weights::SubstrateWeight<Runtime>;
/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
type SS58Prefix = SS58Prefix;
/// The set code logic, just the default since we're not a parachain.
type OnSetCode = ();
type MaxConsumers = frame_support::traits::ConstU32<16>;
type SingleBlockMigrations = ();
type MultiBlockMigrator = ();
type PreInherents = ();
type PostInherents = ();
type PostTransactions = ();
}
impl pallet_aura::Config for Runtime {
type AuthorityId = AuraId;
type DisabledValidators = ();
type MaxAuthorities = ConstU32<50>;
type SlotDuration = pallet_aura::MinimumPeriodTimesTwo<Runtime>;
type AllowMultipleBlocksPerSlot = ConstBool<false>;
}
impl pallet_grandpa::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type KeyOwnerProof = sp_core::Void;
type EquivocationReportSystem = ();
type WeightInfo = ();
type MaxAuthorities = ConstU32<50>;
type MaxSetIdSessionEntries = ConstU64<0>;
type MaxNominators = ConstU32<0>;
}
parameter_types! {
pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
}
impl pallet_timestamp::Config for Runtime {
/// A timestamp: milliseconds since the unix epoch.
type Moment = u64;
type OnTimestampSet = Aura;
type MinimumPeriod = MinimumPeriod;
type WeightInfo = pallet_timestamp::weights::SubstrateWeight<Runtime>;
}
impl pallet_insecure_randomness_collective_flip::Config for Runtime {}
parameter_types! {
pub const ExistentialDeposit: u128 = 500;
pub const MaxLocks: u32 = 50;
}
impl pallet_balances::Config for Runtime {
type MaxLocks = MaxLocks;
type MaxReserves = ();
type ReserveIdentifier = [u8; 8];
/// The type for recording an account's balance.
type Balance = Balance;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
type RuntimeHoldReason = RuntimeHoldReason;
type RuntimeFreezeReason = RuntimeFreezeReason;
type FreezeIdentifier = RuntimeFreezeReason;
type MaxFreezes = ConstU32<1>;
}
parameter_types! {
pub const AssetDeposit: Balance = 1 * AST;
pub const AssetsStringLimit: u32 = 50;
/// Key = 32 bytes, Value = 36 bytes (32+1+1+1+1)
// https://github.com/paritytech/substrate/blob/069917b/frame/assets/src/lib.rs#L257L271
pub const MetadataDepositBase: Balance = deposit(1, 68);
pub const MetadataDepositPerByte: Balance = deposit(0, 1);
pub const AssetAccountDeposit: Balance = deposit(1, 18);
}
impl pallet_assets::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Balance = Balance;
type AssetId = AssetId;
type Currency = Balances;
type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
type ForceOrigin = EnsureRoot<AccountId>;
type AssetDeposit = AssetDeposit;
type MetadataDepositBase = MetadataDepositBase;
type MetadataDepositPerByte = MetadataDepositPerByte;
type AssetAccountDeposit = AssetAccountDeposit;
type ApprovalDeposit = ExistentialDeposit;
type StringLimit = AssetsStringLimit;
type Freezer = ();
type Extra = ();
type WeightInfo = weights::pallet_assets::SubstrateWeight<Runtime>;
type RemoveItemsLimit = ConstU32<1000>;
type AssetIdParameter = Compact<AssetId>;
type CallbackHandle = EvmRevertCodeHandler<Self, Self>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = astar_primitives::benchmarks::AssetsBenchmarkHelper;
}
// These values are based on the Astar 2.0 Tokenomics Modeling report.
parameter_types! {
pub const TransactionLengthFeeFactor: Balance = 23_500_000_000_000; // 0.000_023_500_000_000_000 AST per byte
pub const WeightFeeFactor: Balance = 30_855_000_000_000_000; // Around 0.03 AST per unit of ref time.
pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25);
pub const OperationalFeeMultiplier: u8 = 5;
pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(000_015, 1_000_000); // 0.000_015
pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 10); // 0.1
pub MaximumMultiplier: Multiplier = Multiplier::saturating_from_integer(10); // 10
}
/// Handles converting a weight scalar to a fee value, based on the scale and granularity of the
/// node's balance type.
///
/// This should typically create a mapping between the following ranges:
/// - [0, MAXIMUM_BLOCK_WEIGHT]
/// - [Balance::min, Balance::max]
///
/// Yet, it can be used for any other sort of change to weight-fee. Some examples being:
/// - Setting it to `0` will essentially disable the weight fee.
/// - Setting it to `1` will cause the literal `#[weight = x]` values to be charged.
pub struct WeightToFee;
impl WeightToFeePolynomial for WeightToFee {
type Balance = Balance;
fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
let p = WeightFeeFactor::get();
let q = Balance::from(ExtrinsicBaseWeight::get().ref_time());
smallvec::smallvec![WeightToFeeCoefficient {
degree: 1,
negative: false,
coeff_frac: Perbill::from_rational(p % q, q),
coeff_integer: p / q,
}]
}
}
impl pallet_transaction_payment::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type OnChargeTransaction = FungibleAdapter<Balances, ()>;
type WeightToFee = WeightToFee;
type OperationalFeeMultiplier = OperationalFeeMultiplier;
type FeeMultiplierUpdate = TargetedFeeAdjustment<
Self,
TargetBlockFullness,
AdjustmentVariable,
MinimumMultiplier,
MaximumMultiplier,
>;
type LengthToFee = ConstantMultiplier<Balance, TransactionLengthFeeFactor>;
}
parameter_types! {
pub DefaultBaseFeePerGas: U256 = U256::from(1_470_000_000_000_u128);
pub MinBaseFeePerGas: U256 = U256::from(800_000_000_000_u128);
pub MaxBaseFeePerGas: U256 = U256::from(80_000_000_000_000_u128);
pub StepLimitRatio: Perquintill = Perquintill::from_rational(5_u128, 100_000);
}
/// Simple wrapper for fetching current native transaction fee weight fee multiplier.
pub struct AdjustmentFactorGetter;
impl Get<Multiplier> for AdjustmentFactorGetter {
fn get() -> Multiplier {
pallet_transaction_payment::NextFeeMultiplier::<Runtime>::get()
}
}
impl pallet_dynamic_evm_base_fee::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type DefaultBaseFeePerGas = DefaultBaseFeePerGas;
type MinBaseFeePerGas = MinBaseFeePerGas;
type MaxBaseFeePerGas = MaxBaseFeePerGas;
type AdjustmentFactor = AdjustmentFactorGetter;
type WeightFactor = WeightFeeFactor;
type StepLimitRatio = StepLimitRatio;
type WeightInfo = pallet_dynamic_evm_base_fee::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
pub const DappsStakingPalletId: PalletId = PalletId(*b"py/dpsst");
}
impl pallet_static_price_provider::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
}
#[cfg(feature = "runtime-benchmarks")]
pub struct BenchmarkHelper<SC, ACC>(sp_std::marker::PhantomData<(SC, ACC)>);
#[cfg(feature = "runtime-benchmarks")]
impl pallet_dapp_staking::BenchmarkHelper<SmartContract<AccountId>, AccountId>
for BenchmarkHelper<SmartContract<AccountId>, AccountId>
{
fn get_smart_contract(id: u32) -> SmartContract<AccountId> {
SmartContract::Wasm(AccountId::from([id as u8; 32]))
}
fn set_balance(account: &AccountId, amount: Balance) {
use frame_support::traits::fungible::Unbalanced as FunUnbalanced;
Balances::write_balance(account, amount)
.expect("Must succeed in test/benchmark environment.");
}
}
parameter_types! {
pub const BaseNativeCurrencyPrice: FixedU128 = FixedU128::from_rational(5, 100);
}
impl pallet_dapp_staking::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeFreezeReason = RuntimeFreezeReason;
type Currency = Balances;
type SmartContract = SmartContract<AccountId>;
type ContractRegisterOrigin = EnsureRootOrTwoThirdsCommunityCouncil;
type ContractUnregisterOrigin = EnsureRoot<AccountId>;
type ManagerOrigin = EnsureRootOrTwoThirdsTechnicalCommittee;
type NativePriceProvider = StaticPriceProvider;
type StakingRewardHandler = Inflation;
type CycleConfiguration = InflationCycleConfig;
type Observers = Inflation;
type AccountCheck = ();
type TierSlots = StandardTierSlots;
type BaseNativeCurrencyPrice = BaseNativeCurrencyPrice;
type EraRewardSpanLength = ConstU32<8>;
type RewardRetentionInPeriods = ConstU32<2>;
type MaxNumberOfContracts = ConstU32<100>;
type MaxUnlockingChunks = ConstU32<5>;
type MinimumLockedAmount = ConstU128<AST>;
type UnlockingPeriod = ConstU32<2>;
type MaxNumberOfStakedContracts = ConstU32<3>;
type MinimumStakeAmount = ConstU128<AST>;
type NumberOfTiers = ConstU32<4>;
type RankingEnabled = ConstBool<true>;
type WeightInfo = pallet_dapp_staking::weights::SubstrateWeight<Runtime>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = BenchmarkHelper<SmartContract<AccountId>, AccountId>;
}
pub struct InflationPayoutPerBlock;
impl pallet_inflation::PayoutPerBlock<Credit<AccountId, Balances>> for InflationPayoutPerBlock {
fn treasury(reward: Credit<AccountId, Balances>) {
let _ = Balances::resolve(&TreasuryPalletId::get().into_account_truncating(), reward);
}
fn collators(_reward: Credit<AccountId, Balances>) {
// no collators for local dev node
}
}
pub struct InflationCycleConfig;
impl CycleConfiguration for InflationCycleConfig {
fn periods_per_cycle() -> PeriodNumber {
4
}
fn eras_per_voting_subperiod() -> EraNumber {
2
}
fn eras_per_build_and_earn_subperiod() -> EraNumber {
22
}
fn blocks_per_era() -> BlockNumber {
30
}
}
impl pallet_inflation::Config for Runtime {
type Currency = Balances;
type PayoutPerBlock = InflationPayoutPerBlock;
type CycleConfiguration = InflationCycleConfig;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_inflation::weights::SubstrateWeight<Runtime>;
}
impl pallet_utility::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type PalletsOrigin = OriginCaller;
type WeightInfo = pallet_utility::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
// 2 storage items with value size 20 and 32
pub const AccountMappingStorageFee: u128 = deposit(2, 32 + 20);
}
impl pallet_unified_accounts::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type DefaultMappings = HashedDefaultMappings<BlakeTwo256>;
type ChainId = ChainId;
type AccountMappingStorageFee = AccountMappingStorageFee;
type WeightInfo = pallet_unified_accounts::weights::SubstrateWeight<Self>;
}
parameter_types! {
pub ReservedXcmpWeight: Weight = Weight::zero();
}
impl pallet_ethereum_checked::Config for Runtime {
type ReservedXcmpWeight = ReservedXcmpWeight;
type InvalidEvmTransactionError = pallet_ethereum::InvalidTransactionWrapper;
type ValidatedTransaction = pallet_ethereum::ValidatedTransaction<Self>;
type AddressMapper = UnifiedAccounts;
type XcmTransactOrigin = pallet_ethereum_checked::EnsureXcmEthereumTx<AccountId>;
type WeightInfo = pallet_ethereum_checked::weights::SubstrateWeight<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.saturating_div(GAS_PER_SECOND);
pub struct FindAuthorTruncated<F>(sp_std::marker::PhantomData<F>);
impl<F: FindAuthor<u32>> FindAuthor<H160> for FindAuthorTruncated<F> {
fn find_author<'a, I>(digests: I) -> Option<H160>
where
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
{
if let Some(author_index) = F::find_author(digests) {
let authority_id =
pallet_aura::Authorities::<Runtime>::get()[author_index as usize].clone();
return Some(H160::from_slice(&authority_id.encode()[4..24]));
}
None
}
}
parameter_types! {
/// Ethereum-compatible chain_id:
/// * Dusty: 80
/// * Shibuya: 81
/// * Shiden: 336
/// * Local: 4369
pub ChainId: u64 = 0x1111;
/// EVM gas limit
pub BlockGasLimit: U256 = U256::from(
NORMAL_DISPATCH_RATIO * WEIGHT_REF_TIME_PER_SECOND / WEIGHT_PER_GAS
);
pub PrecompilesValue: Precompiles = LocalPrecompiles::<_>::new();
pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0);
/// The amount of gas per PoV size. Value is calculated as:
///
/// max_gas_limit = max_tx_ref_time / WEIGHT_PER_GAS = max_pov_size * gas_limit_pov_size_ratio
/// gas_limit_pov_size_ratio = ceil((max_tx_ref_time / WEIGHT_PER_GAS) / max_pov_size)
///
/// Local runtime has no strict bounds as parachain, but we keep the value set to 4 for consistency.
pub const GasLimitPovSizeRatio: u64 = 4;
}
impl pallet_evm::Config for Runtime {
type FeeCalculator = DynamicEvmBaseFee;
type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
type WeightPerGas = WeightPerGas;
type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Runtime>;
type CallOrigin = pallet_evm::EnsureAddressRoot<AccountId>;
type WithdrawOrigin = pallet_evm::EnsureAddressTruncated;
type AddressMapping = UnifiedAccounts;
type Currency = Balances;
type RuntimeEvent = RuntimeEvent;
type Runner = pallet_evm::runner::stack::Runner<Self>;
type PrecompilesType = Precompiles;
type PrecompilesValue = PrecompilesValue;
type ChainId = ChainId;
type OnChargeTransaction = pallet_evm::EVMFungibleAdapter<Balances, ()>;
type BlockGasLimit = BlockGasLimit;
type Timestamp = Timestamp;
type OnCreate = ();
type FindAuthor = FindAuthorTruncated<Aura>;
type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
type SuicideQuickClearLimit = ConstU32<0>;
type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
}
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;
// Maximum length (in bytes) of revert message to include in Executed event
type ExtraDataLength = ConstU32<30>;
}
parameter_types! {
pub MaximumSchedulerWeight: Weight = NORMAL_DISPATCH_RATIO * RuntimeBlockWeights::get().max_block;
}
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 = pallet_scheduler::weights::SubstrateWeight<Runtime>;
type OriginPrivilegeCmp = EqualPrivilegeOnly;
type Preimages = Preimage;
}
parameter_types! {
pub const PreimageBaseDeposit: Balance = deposit(1, 0);
pub const PreimageByteDeposit: Balance = deposit(0, 1);
pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
}
impl pallet_preimage::Config for Runtime {
type WeightInfo = pallet_preimage::weights::SubstrateWeight<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 MinVestedTransfer: Balance = 1 * AST;
pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons =
WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE);
}
impl pallet_vesting::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type BlockNumberToBalance = ConvertInto;
type MinVestedTransfer = MinVestedTransfer;
type WeightInfo = pallet_vesting::weights::SubstrateWeight<Runtime>;
type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons;
type BlockNumberProvider = System;
// `VestingInfo` encode length is 36bytes. 28 schedules gets encoded as 1009 bytes, which is the
// highest number of schedules that encodes less than 2^10.
const MAX_VESTING_SCHEDULES: u32 = 28;
}
parameter_types! {
pub const DepositPerItem: Balance = deposit(1, 0);
pub const DepositPerByte: Balance = deposit(0, 1);
// Fallback value if storage deposit limit not set by the user
pub const DefaultDepositLimit: Balance = deposit(16, 16 * 1024);
pub const MaxDelegateDependencies: u32 = 32;
pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(10);
pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();
}
impl pallet_contracts::Config for Runtime {
type Time = Timestamp;
type Randomness = RandomnessCollectiveFlip;
type Currency = Balances;
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
/// The safest default is to allow no calls at all.
///
/// Runtimes should whitelist dispatchables that are allowed to be called from contracts
/// and make sure they are stable. Dispatchables exposed to contracts are not allowed to
/// change because that would break already deployed contracts. The `Call` structure itself
/// is not allowed to change the indices of existing pallets, too.
type CallFilter = Nothing;
type DepositPerItem = DepositPerItem;
type DepositPerByte = DepositPerByte;
type DefaultDepositLimit = DefaultDepositLimit;
type CallStack = [pallet_contracts::Frame<Self>; 5];
type WeightPrice = pallet_transaction_payment::Pallet<Self>;
type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
type ChainExtension = LocalChainExtensions<Self, UnifiedAccounts>;
type Schedule = Schedule;
type AddressGenerator = pallet_contracts::DefaultAddressGenerator;
type MaxCodeLen = ConstU32<{ 123 * 1024 }>;
type MaxStorageKeyLen = ConstU32<128>;
type UnsafeUnstableInterface = ConstBool<true>;
type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>;
type MaxDelegateDependencies = MaxDelegateDependencies;
type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
type RuntimeHoldReason = RuntimeHoldReason;
type Debug = ();
type Environment = ();
type Migrations = ();
type Xcm = ();
type UploadOrigin = EnsureSigned<<Self as frame_system::Config>::AccountId>;
type InstantiateOrigin = EnsureSigned<<Self as frame_system::Config>::AccountId>;
type ApiVersion = ();
type MaxTransientStorageSize = ConstU32<{ 1 * 1024 * 1024 }>;
}
impl pallet_sudo::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
}
/// The type used to represent the kinds of proxying allowed.
#[derive(
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Encode,
Decode,
RuntimeDebug,
MaxEncodedLen,
scale_info::TypeInfo,
)]
pub enum ProxyType {
/// Allows all runtime calls for proxy account
Any,
/// Allows only NonTransfer runtime calls for proxy account
/// To know exact calls check InstanceFilter implementation for ProxyTypes
NonTransfer,
/// All Runtime calls from Pallet Balances allowed for proxy account
Balances,
/// All Runtime calls from Pallet Assets allowed for proxy account
Assets,
/// Only reject_announcement call from pallet proxy allowed for proxy account
CancelProxy,
/// All runtime calls from pallet DappStaking allowed for proxy account
DappStaking,
/// Only claim_staker call from pallet DappStaking allowed for proxy account
StakerRewardClaim,
/// All governance related calls allowed for proxy account
Governance,
}
impl Default for ProxyType {
fn default() -> Self {
Self::Any
}
}
impl InstanceFilter<RuntimeCall> for ProxyType {
fn filter(&self, c: &RuntimeCall) -> bool {
match self {
// Always allowed RuntimeCall::Utility no matter type.
// Only transactions allowed by Proxy.filter can be executed
_ if matches!(c, RuntimeCall::Utility(..)) => true,
// Allows all runtime calls for proxy account
ProxyType::Any => true,
// Allows only NonTransfer runtime calls for proxy account
ProxyType::NonTransfer => {
matches!(
c,
RuntimeCall::System(..)
| RuntimeCall::Proxy(..)
| RuntimeCall::Vesting(
pallet_vesting::Call::vest { .. }
| pallet_vesting::Call::vest_other { .. }
)
| RuntimeCall::DappStaking(..)
)
}
// All Runtime calls from Pallet Balances allowed for proxy account
ProxyType::Balances => {
matches!(c, RuntimeCall::Balances(..))
}
// All Runtime calls from Pallet Assets allowed for proxy account
ProxyType::Assets => {
matches!(c, RuntimeCall::Assets(..))
}
// Only reject_announcement call from pallet proxy allowed for proxy account
ProxyType::CancelProxy => {
matches!(
c,
RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
)
}
// All runtime calls from pallet DappStaking allowed for proxy account
ProxyType::DappStaking => {
matches!(c, RuntimeCall::DappStaking(..))
}
ProxyType::StakerRewardClaim => {
matches!(
c,
RuntimeCall::DappStaking(
pallet_dapp_staking::Call::claim_staker_rewards { .. }
)
)
}
ProxyType::Governance => {
matches!(
c,
RuntimeCall::Democracy(..)
| RuntimeCall::Council(..)
| RuntimeCall::TechnicalCommittee(..)
| RuntimeCall::CommunityCouncil(..)
)
}
}
}
fn is_superset(&self, o: &Self) -> bool {
match (self, o) {
(x, y) if x == y => true,
(ProxyType::Any, _) => true,
(_, ProxyType::Any) => false,
(ProxyType::NonTransfer, _) => true,
(ProxyType::DappStaking, ProxyType::StakerRewardClaim) => true,
_ => false,
}
}
}
impl pallet_proxy::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type Currency = Balances;
type ProxyType = ProxyType;
// One storage item; key size 32, value size 8; .
type ProxyDepositBase = ConstU128<{ AST * 10 }>;
// Additional storage item size of 33 bytes.
type ProxyDepositFactor = ConstU128<{ MILLIAST * 330 }>;
type MaxProxies = ConstU32<32>;
type WeightInfo = pallet_proxy::weights::SubstrateWeight<Runtime>;
type MaxPending = ConstU32<32>;
type CallHasher = BlakeTwo256;
// Key size 32 + 1 item
type AnnouncementDepositBase = ConstU128<{ AST * 10 }>;
// Acc Id + Hash + block number
type AnnouncementDepositFactor = ConstU128<{ MILLIAST * 660 }>;
}
parameter_types! {
pub const CouncilMaxMembers: u32 = 5;
pub const TechnicalCommitteeMaxMembers: u32 = 3;
pub const CommunityCouncilMaxMembers: u32 = 10;
}
impl pallet_membership::Config<MainCouncilMembershipInst> for Runtime {
type RuntimeEvent = RuntimeEvent;
type AddOrigin = EnsureRootOrTwoThirdsMainCouncil;
type RemoveOrigin = EnsureRootOrTwoThirdsMainCouncil;
type SwapOrigin = EnsureRootOrTwoThirdsMainCouncil;
type ResetOrigin = EnsureRootOrTwoThirdsMainCouncil;
type PrimeOrigin = EnsureRootOrTwoThirdsMainCouncil;
type MembershipInitialized = Council;
type MembershipChanged = Council;
type MaxMembers = CouncilMaxMembers;
type WeightInfo = pallet_membership::weights::SubstrateWeight<Runtime>;
}
impl pallet_membership::Config<TechnicalCommitteeMembershipInst> for Runtime {
type RuntimeEvent = RuntimeEvent;
type AddOrigin = EnsureRootOrTwoThirdsMainCouncil;
type RemoveOrigin = EnsureRootOrTwoThirdsMainCouncil;
type SwapOrigin = EnsureRootOrTwoThirdsMainCouncil;
type ResetOrigin = EnsureRootOrTwoThirdsMainCouncil;
type PrimeOrigin = EnsureRootOrTwoThirdsMainCouncil;
type MembershipInitialized = TechnicalCommittee;
type MembershipChanged = TechnicalCommittee;
type MaxMembers = TechnicalCommitteeMaxMembers;
type WeightInfo = pallet_membership::weights::SubstrateWeight<Runtime>;
}
impl pallet_membership::Config<CommunityCouncilMembershipInst> for Runtime {
type RuntimeEvent = RuntimeEvent;
type AddOrigin = EnsureRootOrTwoThirdsMainCouncil;
type RemoveOrigin = EnsureRootOrTwoThirdsMainCouncil;
type SwapOrigin = EnsureRootOrTwoThirdsMainCouncil;
type ResetOrigin = EnsureRootOrTwoThirdsMainCouncil;
type PrimeOrigin = EnsureRootOrTwoThirdsMainCouncil;
type MembershipInitialized = CommunityCouncil;
type MembershipChanged = CommunityCouncil;
type MaxMembers = CommunityCouncilMaxMembers;
type WeightInfo = pallet_membership::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub MaxProposalWeight: Weight = Perbill::from_percent(50) * RuntimeBlockWeights::get().max_block;
}
impl pallet_collective::Config<MainCouncilCollectiveInst> for Runtime {
type RuntimeOrigin = RuntimeOrigin;
type Proposal = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type MotionDuration = ConstU32<{ 5 * MINUTES }>;
type MaxProposals = ConstU32<16>;
type MaxMembers = CouncilMaxMembers;
type DefaultVote = pallet_collective::PrimeDefaultVote;
type SetMembersOrigin = EnsureRoot<AccountId>;
type MaxProposalWeight = MaxProposalWeight;
type WeightInfo = pallet_collective::weights::SubstrateWeight<Runtime>;
}
impl pallet_collective::Config<TechnicalCommitteeCollectiveInst> for Runtime {
type RuntimeOrigin = RuntimeOrigin;
type Proposal = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type MotionDuration = ConstU32<{ 5 * MINUTES }>;
type MaxProposals = ConstU32<16>;
type MaxMembers = TechnicalCommitteeMaxMembers;
type DefaultVote = pallet_collective::PrimeDefaultVote;
type SetMembersOrigin = EnsureRoot<AccountId>;
type MaxProposalWeight = MaxProposalWeight;
type WeightInfo = pallet_collective::weights::SubstrateWeight<Runtime>;
}
impl pallet_collective::Config<CommunityCouncilCollectiveInst> for Runtime {
type RuntimeOrigin = RuntimeOrigin;
type Proposal = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type MotionDuration = ConstU32<{ 5 * MINUTES }>;
type MaxProposals = ConstU32<16>;
type MaxMembers = CommunityCouncilMaxMembers;
type DefaultVote = pallet_collective::PrimeDefaultVote;
type SetMembersOrigin = EnsureRoot<AccountId>;
type MaxProposalWeight = MaxProposalWeight;
type WeightInfo = pallet_collective::weights::SubstrateWeight<Runtime>;
}
impl pallet_democracy::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type EnactmentPeriod = ConstU32<{ 5 * MINUTES }>;
type LaunchPeriod = ConstU32<{ 5 * MINUTES }>;
type VotingPeriod = ConstU32<{ 5 * MINUTES }>;
type VoteLockingPeriod = ConstU32<{ 2 * MINUTES }>;
type MinimumDeposit = ConstU128<{ 10 * AST }>;
type FastTrackVotingPeriod = ConstU32<{ MINUTES / 2 }>;
type CooloffPeriod = ConstU32<{ 2 * MINUTES }>;
type MaxVotes = ConstU32<128>;
type MaxProposals = ConstU32<128>;
type MaxDeposits = ConstU32<128>;
type MaxBlacklisted = ConstU32<128>;
/// A two third majority of the Council can choose the next external "super majority approve" proposal.
type ExternalOrigin = EnsureRootOrTwoThirdsMainCouncil;
/// A two third majority of the Council can choose the next external "majority approve" proposal. Also bypasses blacklist filter.
type ExternalMajorityOrigin = EnsureRootOrTwoThirdsMainCouncil;
/// Unanimous approval of the Council can choose the next external "super majority against" proposal.
type ExternalDefaultOrigin = EnsureRootOrAllMainCouncil;
/// A two third majority of the Technical Committee can have an external proposal tabled immediately