-
Notifications
You must be signed in to change notification settings - Fork 374
/
lib.rs
1781 lines (1589 loc) · 64.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
// This file is part of Astar.
// Copyright (C) 2019-2023 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/>.
//! The Astar Network runtime. This can be compiled with ``#[no_std]`, ready for Wasm.
#![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"]
pub use crate::precompiles::WhitelistedCalls;
pub use astar_primitives::{
evm::EvmRevertCodeHandler, xcm::AssetLocationIdConverter, AccountId, Address, AssetId, Balance,
BlockNumber, Hash, Header, Index, Signature,
};
use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use frame_support::{
construct_runtime,
dispatch::DispatchClass,
parameter_types,
traits::{
AsEnsureOriginWithArg, ConstBool, ConstU32, Contains, Currency, FindAuthor, Get, Imbalance,
InstanceFilter, Nothing, OnFinalize, OnUnbalanced, Randomness, WithdrawReasons,
},
weights::{
constants::{
BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND,
},
ConstantMultiplier, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients,
WeightToFeePolynomial,
},
ConsensusEngineId, PalletId,
};
use frame_system::{
limits::{BlockLength, BlockWeights},
EnsureRoot, EnsureSigned,
};
use pallet_ethereum::PostLogContent;
use pallet_evm::{FeeCalculator, GasWeightMapping, Runner};
use pallet_transaction_payment::{
FeeDetails, Multiplier, RuntimeDispatchInfo, TargetedFeeAdjustment,
};
use parity_scale_codec::{Compact, Decode, Encode, MaxEncodedLen};
use polkadot_runtime_common::BlockHashCount;
use sp_api::impl_runtime_apis;
use sp_core::{OpaqueMetadata, H160, H256, U256};
use sp_inherents::{CheckInherentsResult, InherentData};
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
traits::{
AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Bounded, ConvertInto,
DispatchInfoOf, Dispatchable, OpaqueKeys, PostDispatchInfoOf, UniqueSaturatedInto, Zero,
},
transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError},
ApplyExtrinsicResult, FixedPointNumber, Perbill, Permill, Perquintill, RuntimeDebug,
};
use sp_std::prelude::*;
use pallet_evm_precompile_assets_erc20::AddressToAssetId;
#[cfg(any(feature = "std", test))]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
pub use frame_system::Call as SystemCall;
pub use pallet_balances::Call as BalancesCall;
pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
mod precompiles;
mod weights;
mod xcm_config;
pub type AstarAssetLocationIdConverter = AssetLocationIdConverter<AssetId, XcAssetConfig>;
pub use precompiles::{AstarNetworkPrecompiles, ASSET_PRECOMPILE_ADDRESS_PREFIX};
pub type Precompiles = AstarNetworkPrecompiles<Runtime, AstarAssetLocationIdConverter>;
/// Constant values used within the runtime.
pub const MICROASTR: Balance = 1_000_000_000_000;
pub const MILLIASTR: Balance = 1_000 * MICROASTR;
pub const ASTR: Balance = 1_000 * MILLIASTR;
pub const INIT_SUPPLY_FACTOR: Balance = 100;
pub const STORAGE_BYTE_FEE: Balance = 20 * MICROASTR * INIT_SUPPLY_FACTOR;
/// Charge fee for stored bytes and items.
pub const fn deposit(items: u32, bytes: u32) -> Balance {
items as Balance * 100 * MILLIASTR * INIT_SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
}
/// Charge fee for stored bytes and items as part of `pallet-contracts`.
///
/// The slight difference to general `deposit` function is because there is fixed bound on how large the DB
/// key can grow so it doesn't make sense to have as high deposit per item as in the general approach.
pub const fn contracts_deposit(items: u32, bytes: u32) -> Balance {
items as Balance * 4 * MILLIASTR * INIT_SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
}
/// Change this to adjust the block time.
pub const MILLISECS_PER_BLOCK: u64 = 12000;
// 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;
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
#[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.",
)
}
/// Runtime version.
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("astar"),
impl_name: create_runtime_str!("astar"),
authoring_version: 1,
spec_version: 67,
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
transaction_version: 2,
state_version: 1,
};
/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
NativeVersion {
runtime_version: VERSION,
can_author_with: Default::default(),
}
}
impl_opaque_keys! {
pub struct SessionKeys {
pub aura: Aura,
}
}
/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.
/// This is used to limit the maximal weight of a single extrinsic.
const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);
/// 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);
/// We allow for 0.5 seconds of compute with a 6 second average block time.
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
WEIGHT_REF_TIME_PER_SECOND.saturating_div(2),
polkadot_primitives::MAX_POV_SIZE as u64,
);
parameter_types! {
pub const Version: RuntimeVersion = VERSION;
pub RuntimeBlockLength: BlockLength =
BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
pub RuntimeBlockWeights: BlockWeights = 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 some 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();
pub SS58Prefix: u8 = 5;
}
pub struct BaseFilter;
impl Contains<RuntimeCall> for BaseFilter {
fn contains(call: &RuntimeCall) -> bool {
match call {
// Filter permission-less assets creation/destroying.
// Custom asset's `id` should fit in `u32` as not to mix with service assets.
RuntimeCall::Assets(method) => match method {
pallet_assets::Call::create { id, .. } => *id < (u32::MAX as AssetId).into(),
_ => true,
},
// These modules are not allowed to be called by transactions:
// To leave collator just shutdown it, next session funds will be released
// Other modules should works:
_ => true,
}
}
}
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 = AccountIdLookup<AccountId, ()>;
/// The index type for storing how many extrinsics an account has signed.
type Index = Index;
/// The index type for blocks.
type BlockNumber = BlockNumber;
/// The type for hashing blocks and tries.
type Hash = Hash;
/// The hashing algorithm used.
type Hashing = BlakeTwo256;
/// The header type.
type Header = generic::Header<BlockNumber, 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 = BlockHashCount;
/// Runtime version.
type Version = Version;
/// Converts a module to an index of this module in the runtime.
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
type DbWeight = RocksDbWeight;
type BaseCallFilter = BaseFilter;
type SystemWeightInfo = frame_system::weights::SubstrateWeight<Runtime>;
type BlockWeights = RuntimeBlockWeights;
type BlockLength = RuntimeBlockLength;
type SS58Prefix = SS58Prefix;
type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
type MaxConsumers = frame_support::traits::ConstU32<16>;
}
parameter_types! {
pub const MinimumPeriod: u64 = MILLISECS_PER_BLOCK / 2;
}
impl pallet_timestamp::Config for Runtime {
/// A timestamp: milliseconds since the unix epoch.
type Moment = u64;
type OnTimestampSet = BlockReward;
type MinimumPeriod = MinimumPeriod;
type WeightInfo = pallet_timestamp::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const BasicDeposit: Balance = deposit(1, 258); // 258 bytes on-chain
pub const FieldDeposit: Balance = deposit(0, 66); // 66 bytes on-chain
pub const SubAccountDeposit: Balance = deposit(1, 53); // 53 bytes on-chain
pub const MaxSubAccounts: u32 = 100;
pub const MaxAdditionalFields: u32 = 100;
pub const MaxRegistrars: u32 = 20;
}
impl pallet_identity::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type BasicDeposit = BasicDeposit;
type FieldDeposit = FieldDeposit;
type SubAccountDeposit = SubAccountDeposit;
type MaxSubAccounts = MaxSubAccounts;
type MaxAdditionalFields = MaxAdditionalFields;
type MaxRegistrars = MaxRegistrars;
type Slashed = ();
type ForceOrigin = EnsureRoot<<Self as frame_system::Config>::AccountId>;
type RegistrarOrigin = EnsureRoot<<Self as frame_system::Config>::AccountId>;
type WeightInfo = pallet_identity::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
// One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
pub const DepositBase: Balance = deposit(1, 88);
// Additional storage item size of 32 bytes.
pub const DepositFactor: Balance = deposit(0, 32);
}
impl pallet_multisig::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type Currency = Balances;
type DepositBase = DepositBase;
type DepositFactor = DepositFactor;
type MaxSignatories = ConstU32<100>;
type WeightInfo = pallet_multisig::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const BlockPerEra: BlockNumber = DAYS;
pub const RegisterDeposit: Balance = 1000 * ASTR;
pub const MaxNumberOfStakersPerContract: u32 = 16384;
pub const MinimumStakingAmount: Balance = 500 * ASTR;
pub const MinimumRemainingAmount: Balance = ASTR;
pub const MaxEraStakeValues: u32 = 5;
pub const MaxUnlockingChunks: u32 = 4;
pub const UnbondingPeriod: u32 = 10;
}
impl pallet_dapps_staking::Config for Runtime {
type Currency = Balances;
type BlockPerEra = BlockPerEra;
type SmartContract = SmartContract<AccountId>;
type RegisterDeposit = RegisterDeposit;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_dapps_staking::weights::SubstrateWeight<Runtime>;
type MaxNumberOfStakersPerContract = MaxNumberOfStakersPerContract;
type MinimumStakingAmount = MinimumStakingAmount;
type PalletId = DappsStakingPalletId;
type MaxUnlockingChunks = MaxUnlockingChunks;
type UnbondingPeriod = UnbondingPeriod;
type MinimumRemainingAmount = MinimumRemainingAmount;
type MaxEraStakeValues = MaxEraStakeValues;
// Not allowed on Astar yet
type UnregisteredDappRewardRetention = ConstU32<{ u32::MAX }>;
}
/// Multi-VM pointer to smart contract instance.
#[derive(
PartialEq, Eq, Copy, Clone, Encode, Decode, RuntimeDebug, MaxEncodedLen, scale_info::TypeInfo,
)]
pub enum SmartContract<AccountId> {
/// EVM smart contract instance.
Evm(sp_core::H160),
/// Wasm smart contract instance.
Wasm(AccountId),
}
impl<AccountId> Default for SmartContract<AccountId> {
fn default() -> Self {
SmartContract::Evm(H160::repeat_byte(0x00))
}
}
impl pallet_utility::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type PalletsOrigin = OriginCaller;
type WeightInfo = pallet_utility::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
}
impl cumulus_pallet_parachain_system::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type OnSystemEvent = ();
type SelfParaId = parachain_info::Pallet<Runtime>;
type OutboundXcmpMessageSource = XcmpQueue;
type DmpMessageHandler = DmpQueue;
type ReservedDmpWeight = ReservedDmpWeight;
type XcmpMessageHandler = XcmpQueue;
type ReservedXcmpWeight = ReservedXcmpWeight;
type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
}
impl parachain_info::Config for Runtime {}
parameter_types! {
pub const MaxAuthorities: u32 = 250;
}
impl pallet_aura::Config for Runtime {
type AuthorityId = AuraId;
type DisabledValidators = ();
type MaxAuthorities = MaxAuthorities;
}
impl cumulus_pallet_aura_ext::Config for Runtime {}
impl pallet_authorship::Config for Runtime {
type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
type EventHandler = (CollatorSelection,);
}
parameter_types! {
pub const SessionPeriod: BlockNumber = HOURS;
pub const SessionOffset: BlockNumber = 0;
}
impl pallet_session::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type ValidatorId = <Self as frame_system::Config>::AccountId;
type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
type ShouldEndSession = pallet_session::PeriodicSessions<SessionPeriod, SessionOffset>;
type NextSessionRotation = pallet_session::PeriodicSessions<SessionPeriod, SessionOffset>;
type SessionManager = CollatorSelection;
type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type Keys = SessionKeys;
type WeightInfo = pallet_session::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const PotId: PalletId = PalletId(*b"PotStake");
pub const MaxCandidates: u32 = 148;
pub const MinCandidates: u32 = 5;
pub const MaxInvulnerables: u32 = 48;
pub const SlashRatio: Perbill = Perbill::from_percent(1);
pub const KickThreshold: BlockNumber = 2 * HOURS; // 2 SessionPeriod
}
impl pallet_collator_selection::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type UpdateOrigin = EnsureRoot<AccountId>;
type PotId = PotId;
type MaxCandidates = MaxCandidates;
type MinCandidates = MinCandidates;
type MaxInvulnerables = MaxInvulnerables;
// should be a multiple of session or things will get inconsistent
type KickThreshold = KickThreshold;
type ValidatorId = <Self as frame_system::Config>::AccountId;
type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
type ValidatorRegistration = Session;
type SlashRatio = SlashRatio;
type WeightInfo = pallet_collator_selection::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
pub const DappsStakingPalletId: PalletId = PalletId(*b"py/dpsst");
pub TreasuryAccountId: AccountId = TreasuryPalletId::get().into_account_truncating();
}
type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;
pub struct ToStakingPot;
impl OnUnbalanced<NegativeImbalance> for ToStakingPot {
fn on_nonzero_unbalanced(amount: NegativeImbalance) {
let staking_pot = PotId::get().into_account_truncating();
Balances::resolve_creating(&staking_pot, amount);
}
}
pub struct DappsStakingTvlProvider();
impl Get<Balance> for DappsStakingTvlProvider {
fn get() -> Balance {
DappsStaking::tvl()
}
}
pub struct BeneficiaryPayout();
impl pallet_block_reward::BeneficiaryPayout<NegativeImbalance> for BeneficiaryPayout {
fn treasury(reward: NegativeImbalance) {
Balances::resolve_creating(&TreasuryPalletId::get().into_account_truncating(), reward);
}
fn collators(reward: NegativeImbalance) {
ToStakingPot::on_unbalanced(reward);
}
fn dapps_staking(stakers: NegativeImbalance, dapps: NegativeImbalance) {
DappsStaking::rewards(stakers, dapps)
}
}
parameter_types! {
pub const RewardAmount: Balance = 253_080 * MILLIASTR;
}
impl pallet_block_reward::Config for Runtime {
type Currency = Balances;
type DappsStakingTvlProvider = DappsStakingTvlProvider;
type BeneficiaryPayout = BeneficiaryPayout;
type RewardAmount = RewardAmount;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_block_reward::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const ExistentialDeposit: Balance = 1_000_000;
pub const MaxLocks: u32 = 50;
pub const MaxReserves: u32 = 50;
}
impl pallet_balances::Config for Runtime {
type Balance = Balance;
type DustRemoval = ();
type RuntimeEvent = RuntimeEvent;
type MaxLocks = MaxLocks;
type MaxReserves = MaxReserves;
type ReserveIdentifier = [u8; 8];
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = frame_system::Pallet<Runtime>;
type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
type HoldIdentifier = ();
type FreezeIdentifier = ();
type MaxHolds = ConstU32<0>;
type MaxFreezes = ConstU32<0>;
}
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)
}
}
parameter_types! {
pub const AssetDeposit: Balance = 10 * INIT_SUPPLY_FACTOR * ASTR;
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;
}
parameter_types! {
pub const MinVestedTransfer: Balance = 100 * ASTR;
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;
// `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 = contracts_deposit(1, 0);
pub const DepositPerByte: Balance = contracts_deposit(0, 1);
// Fallback value if storage deposit limit not set by the user
pub const DefaultDepositLimit: Balance = contracts_deposit(16, 16 * 1024);
pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();
}
/// Codes using the randomness functionality cannot be uploaded. Neither can contracts
/// be instantiated from existing codes that use this deprecated functionality.
///
/// But since some `Randomness` config type is still required for `pallet-contracts`, we provide this dummy type.
pub struct DummyDeprecatedRandomness;
impl Randomness<Hash, BlockNumber> for DummyDeprecatedRandomness {
fn random(_: &[u8]) -> (Hash, BlockNumber) {
(Default::default(), Zero::zero())
}
}
impl pallet_contracts::Config for Runtime {
type Time = Timestamp;
type Randomness = DummyDeprecatedRandomness;
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 = ();
type Schedule = Schedule;
type AddressGenerator = pallet_contracts::DefaultAddressGenerator;
type MaxCodeLen = ConstU32<{ 123 * 1024 }>;
type MaxStorageKeyLen = ConstU32<128>;
type UnsafeUnstableInterface = ConstBool<false>;
type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>;
}
parameter_types! {
pub const TransactionByteFee: Balance = MILLIASTR / 100;
pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25);
pub const OperationalFeeMultiplier: u8 = 5;
pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(1, 100_000);
pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 1_000_000_000u128);
pub MaximumMultiplier: Multiplier = Bounded::max_value();
}
/// 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> {
// in Astar, extrinsic base weight (smallest non-zero weight) is mapped to 1/10 mASTR:
let p = MILLIASTR;
let q = 10 * 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,
}]
}
}
pub struct DealWithFees;
impl OnUnbalanced<NegativeImbalance> for DealWithFees {
fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {
if let Some(mut fees) = fees_then_tips.next() {
if let Some(tips) = fees_then_tips.next() {
tips.merge_into(&mut fees);
}
let (to_burn, collators) = fees.ration(20, 80);
// burn part of fees
drop(to_burn);
// pay fees to collators
<ToStakingPot as OnUnbalanced<_>>::on_unbalanced(collators);
}
}
}
impl pallet_transaction_payment::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;
type WeightToFee = WeightToFee;
type OperationalFeeMultiplier = OperationalFeeMultiplier;
type FeeMultiplierUpdate = TargetedFeeAdjustment<
Self,
TargetBlockFullness,
AdjustmentVariable,
MinimumMultiplier,
MaximumMultiplier,
>;
type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
}
parameter_types! {
pub DefaultBaseFeePerGas: U256 = (MILLIASTR / 1_000_000).into();
// At the moment, we don't use dynamic fee calculation for Astar by default
pub DefaultElasticity: Permill = Permill::zero();
}
pub struct BaseFeeThreshold;
impl pallet_base_fee::BaseFeeThreshold for BaseFeeThreshold {
fn lower() -> Permill {
Permill::zero()
}
fn ideal() -> Permill {
Permill::from_parts(500_000)
}
fn upper() -> Permill {
Permill::from_parts(1_000_000)
}
}
impl pallet_base_fee::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Threshold = BaseFeeThreshold;
type DefaultBaseFeePerGas = DefaultBaseFeePerGas;
type DefaultElasticity = DefaultElasticity;
}
/// 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 = Aura::authorities()[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
/// * Astar: 592
pub ChainId: u64 = 0x250;
/// EVM gas limit
pub BlockGasLimit: U256 = U256::from(
NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS
);
pub PrecompilesValue: Precompiles = AstarNetworkPrecompiles::<_, _>::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)
///
/// Equals 4 for values used by Astar runtime.
pub const GasLimitPovSizeRatio: u64 = 4;
}
impl pallet_evm::Config for Runtime {
type FeeCalculator = BaseFee;
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 = pallet_evm::HashedAddressMapping<BlakeTwo256>;
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::EVMCurrencyAdapter<Balances, ToStakingPot>;
type BlockGasLimit = BlockGasLimit;
type Timestamp = Timestamp;
type OnCreate = ();
type FindAuthor = FindAuthorTruncated<Aura>;
type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
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>;
}
impl pallet_sudo::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
}
impl pallet_xc_asset_config::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type AssetId = AssetId;
type ManagerOrigin = EnsureRoot<AccountId>;
type WeightInfo = pallet_xc_asset_config::weights::SubstrateWeight<Self>;
}
/// 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 inmplementation 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 provide_judgement call from pallet identity allowed for proxy account
IdentityJudgement,
/// Only reject_announcement call from pallet proxy allowed for proxy account
CancelProxy,
/// All runtime calls from pallet DappStaking allowed for proxy account
DappsStaking,
/// Only claim_staker call from pallet DappStaking allowed for proxy account
StakerRewardClaim,
}
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,
ProxyType::Any => true,
ProxyType::NonTransfer => {
matches!(
c,
RuntimeCall::System(..)
| RuntimeCall::Identity(..)
| RuntimeCall::Timestamp(..)
| RuntimeCall::Multisig(..)
| RuntimeCall::Proxy(..)
| RuntimeCall::ParachainSystem(..)
| RuntimeCall::ParachainInfo(..)
// Skip entire Balances pallet
| RuntimeCall::Vesting(pallet_vesting::Call::vest{..})
| RuntimeCall::Vesting(pallet_vesting::Call::vest_other{..})
// Specifically omitting Vesting `vested_transfer`, and `force_vested_transfer`
| RuntimeCall::DappsStaking(..)
// Skip entire Assets pallet
| RuntimeCall::CollatorSelection(..)
| RuntimeCall::Session(..)
| RuntimeCall::XcmpQueue(..)
| RuntimeCall::PolkadotXcm(..)
| RuntimeCall::CumulusXcm(..)
| RuntimeCall::DmpQueue(..)
| RuntimeCall::XcAssetConfig(..)
// Skip entire EVM pallet
// Skip entire Ethereum pallet
| RuntimeCall::BaseFee(..) // Skip entire Contracts pallet
)
}
ProxyType::Balances => {
matches!(c, RuntimeCall::Balances(..))
}
ProxyType::Assets => {
matches!(c, RuntimeCall::Assets(..))
}
ProxyType::IdentityJudgement => {
matches!(
c,
RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. })
)
}
ProxyType::CancelProxy => {
matches!(
c,
RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
)
}
ProxyType::DappsStaking => {
matches!(c, RuntimeCall::DappsStaking(..))
}
ProxyType::StakerRewardClaim => {
matches!(
c,
RuntimeCall::DappsStaking(pallet_dapps_staking::Call::claim_staker { .. })
)
}
}
}
fn is_superset(&self, o: &Self) -> bool {
match (self, o) {
(x, y) if x == y => true,
(ProxyType::Any, _) => true,
(_, ProxyType::Any) => false,
(ProxyType::DappsStaking, ProxyType::StakerRewardClaim) => true,
_ => false,
}
}
}
parameter_types! {
// One storage item; key size 32, value size 8; .
pub const ProxyDepositBase: Balance = deposit(1, 8);
// Additional storage item size of 33 bytes.
pub const ProxyDepositFactor: Balance = deposit(0, 33);
pub const MaxProxies: u16 = 32;
pub const MaxPending: u16 = 32;
pub const AnnouncementDepositBase: Balance = deposit(1, 8);
pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
}
impl pallet_proxy::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type Currency = Balances;
type ProxyType = ProxyType;
type ProxyDepositBase = ProxyDepositBase;
type ProxyDepositFactor = ProxyDepositFactor;
type MaxProxies = MaxProxies;
type WeightInfo = pallet_proxy::weights::SubstrateWeight<Runtime>;
type MaxPending = MaxPending;
type CallHasher = BlakeTwo256;
type AnnouncementDepositBase = AnnouncementDepositBase;
type AnnouncementDepositFactor = AnnouncementDepositFactor;
}
construct_runtime!(
pub struct Runtime where
Block = Block,
NodeBlock = generic::Block<Header, sp_runtime::OpaqueExtrinsic>,
UncheckedExtrinsic = UncheckedExtrinsic
{
System: frame_system = 10,
Utility: pallet_utility = 11,
Identity: pallet_identity = 12,
Timestamp: pallet_timestamp = 13,
Multisig: pallet_multisig = 14,
Proxy: pallet_proxy = 15,
ParachainSystem: cumulus_pallet_parachain_system = 20,
ParachainInfo: parachain_info = 21,
TransactionPayment: pallet_transaction_payment = 30,
Balances: pallet_balances = 31,
Vesting: pallet_vesting = 32,
DappsStaking: pallet_dapps_staking = 34,
BlockReward: pallet_block_reward = 35,
Assets: pallet_assets = 36,
Authorship: pallet_authorship = 40,
CollatorSelection: pallet_collator_selection = 41,
Session: pallet_session = 42,
Aura: pallet_aura = 43,
AuraExt: cumulus_pallet_aura_ext = 44,
XcmpQueue: cumulus_pallet_xcmp_queue = 50,
PolkadotXcm: pallet_xcm = 51,
CumulusXcm: cumulus_pallet_xcm = 52,