-
Notifications
You must be signed in to change notification settings - Fork 374
/
lib.rs
1277 lines (1127 loc) · 44.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
//! 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"]
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{
construct_runtime,
dispatch::DispatchClass,
parameter_types,
traits::{Contains, Currency, FindAuthor, Get, Imbalance, OnUnbalanced},
weights::{
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
ConstantMultiplier, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients,
WeightToFeePolynomial,
},
ConsensusEngineId, PalletId,
};
use frame_system::limits::{BlockLength, BlockWeights};
use pallet_evm::{FeeCalculator, Runner};
use pallet_transaction_payment::{
FeeDetails, Multiplier, RuntimeDispatchInfo, TargetedFeeAdjustment,
};
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, ConvertInto,
DispatchInfoOf, Dispatchable, OpaqueKeys, PostDispatchInfoOf, UniqueSaturatedInto, Verify,
},
transaction_validity::{
TransactionPriority, TransactionSource, TransactionValidity, TransactionValidityError,
},
ApplyExtrinsicResult, FixedPointNumber, Perbill, Permill, Perquintill, RuntimeDebug,
};
use sp_std::prelude::*;
use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use pallet_evm_precompile_assets_erc20::AddressToAssetId;
use xcm_primitives::AssetLocationIdConverter;
#[cfg(any(feature = "std", test))]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
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 MILLIASTR: Balance = 1_000_000_000_000_000;
pub const ASTR: Balance = 1_000 * MILLIASTR;
/// Charge fee for stored bytes and items.
pub const fn deposit(items: u32, bytes: u32) -> Balance {
(items as Balance + bytes as Balance) * MILLIASTR / 1_000_000
}
/// 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: 44,
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_PER_SECOND.saturating_div(2);
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
RuntimeCall::Assets(method) => match method {
pallet_assets::Call::create { id, .. } => *id < u32::MAX.into(),
pallet_assets::Call::destroy { id, .. } => *id < u32::MAX.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 = ();
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 = ();
}
parameter_types! {
pub const BasicDeposit: Balance = 10 * ASTR; // 258 bytes on-chain
pub const FieldDeposit: Balance = 25 * MILLIASTR; // 66 bytes on-chain
pub const SubAccountDeposit: Balance = 2 * ASTR; // 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 = frame_system::EnsureRoot<<Self as frame_system::Config>::AccountId>;
type RegistrarOrigin = frame_system::EnsureRoot<<Self as frame_system::Config>::AccountId>;
type WeightInfo = ();
}
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);
pub const MaxSignatories: u16 = 100;
}
impl pallet_multisig::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type Currency = Balances;
type DepositBase = DepositBase;
type DepositFactor = DepositFactor;
type MaxSignatories = MaxSignatories;
type WeightInfo = ();
}
parameter_types! {
pub const EcdsaUnsignedPriority: TransactionPriority = TransactionPriority::MAX / 2;
pub const CallFee: Balance = ASTR / 10;
pub const CallMagicNumber: u16 = 0x0250;
}
impl pallet_custom_signatures::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type Signature = pallet_custom_signatures::ethereum::EthereumSignature;
type Signer = <Signature as Verify>::Signer;
type CallMagicNumber = CallMagicNumber;
type Currency = Balances;
type CallFee = CallFee;
type OnChargeTransaction = ToStakingPot;
type UnsignedPriority = EcdsaUnsignedPriority;
}
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 = weights::pallet_dapps_staking::WeightInfo<Runtime>;
type MaxNumberOfStakersPerContract = MaxNumberOfStakersPerContract;
type MinimumStakingAmount = MinimumStakingAmount;
type PalletId = DappsStakingPalletId;
type MaxUnlockingChunks = MaxUnlockingChunks;
type UnbondingPeriod = UnbondingPeriod;
type MinimumRemainingAmount = MinimumRemainingAmount;
type MaxEraStakeValues = MaxEraStakeValues;
}
/// 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 = ();
}
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 {}
parameter_types! {
pub const UncleGenerations: BlockNumber = 5;
}
impl pallet_authorship::Config for Runtime {
type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
type UncleGenerations = UncleGenerations;
type FilterUncle = ();
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 = frame_system::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 = ();
}
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 = 266_400 * 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 = ();
}
/// Id used for identifying assets.
///
/// AssetId allocation:
/// [1; 2^32-1] Custom user assets (permissionless)
/// [2^32; 2^64-1] Statemine assets (simple map)
/// [2^64; 2^128-1] Ecosystem assets
/// 2^128-1 Relay chain token (KSM)
pub type AssetId = u128;
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 = 1_000_000;
pub const ApprovalDeposit: Balance = 1_000_000;
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 ForceOrigin = frame_system::EnsureRoot<AccountId>;
type AssetDeposit = AssetDeposit;
type MetadataDepositBase = MetadataDepositBase;
type MetadataDepositPerByte = MetadataDepositPerByte;
type AssetAccountDeposit = AssetAccountDeposit;
type ApprovalDeposit = ApprovalDeposit;
type StringLimit = AssetsStringLimit;
type Freezer = ();
type Extra = ();
type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const MinVestedTransfer: Balance = ASTR;
}
impl pallet_vesting::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type BlockNumberToBalance = ConvertInto;
type MinVestedTransfer = MinVestedTransfer;
type WeightInfo = ();
// `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 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);
}
/// 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
let _ = Balances::burn(to_burn.peek());
// 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>;
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_PER_SECOND.saturating_div(GAS_PER_SECOND).ref_time();
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: u64 = WEIGHT_PER_GAS;
}
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 FindAuthor = FindAuthorTruncated<Aura>;
}
impl pallet_ethereum::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;
}
impl pallet_sudo::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
}
pub struct EvmRevertCodeHandler;
impl pallet_xc_asset_config::XcAssetChanged<Runtime> for EvmRevertCodeHandler {
fn xc_asset_registered(asset_id: AssetId) {
let address = Runtime::asset_id_to_address(asset_id);
pallet_evm::AccountCodes::<Runtime>::insert(address, vec![0x60, 0x00, 0x60, 0x00, 0xfd]);
}
fn xc_asset_unregistered(asset_id: AssetId) {
let address = Runtime::asset_id_to_address(asset_id);
pallet_evm::AccountCodes::<Runtime>::remove(address);
}
}
impl pallet_xc_asset_config::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type AssetId = AssetId;
type XcAssetChanged = EvmRevertCodeHandler;
type ManagerOrigin = frame_system::EnsureRoot<AccountId>;
type WeightInfo = weights::pallet_xc_asset_config::WeightInfo<Self>;
}
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,
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,
DmpQueue: cumulus_pallet_dmp_queue = 53,
XcAssetConfig: pallet_xc_asset_config = 54,
EVM: pallet_evm = 60,
Ethereum: pallet_ethereum = 61,
EthCall: pallet_custom_signatures = 62,
BaseFee: pallet_base_fee = 63,
Sudo: pallet_sudo = 99,
}
);
/// Balance of an account.
pub type Balance = u128;
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
pub type Signature = sp_runtime::MultiSignature;
/// Some way of identifying an account on the chain. We intentionally make it equivalent
/// to the public key of our transaction signing scheme.
pub type AccountId = <<Signature as sp_runtime::traits::Verify>::Signer as sp_runtime::traits::IdentifyAccount>::AccountId;
/// Index of a transaction in the chain.
pub type Index = u32;
/// A hash of some data used by the chain.
pub type Hash = sp_core::H256;
/// An index to a block.
pub type BlockNumber = u32;
/// The address format for describing accounts.
pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
/// Block header type as expected by this runtime.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// A Block signed with a Justification
pub type SignedBlock = generic::SignedBlock<Block>;
/// BlockId type as expected by this runtime.
pub type BlockId = generic::BlockId<Block>;
/// The SignedExtension to the basic transaction logic.
pub type SignedExtra = (
frame_system::CheckSpecVersion<Runtime>,
frame_system::CheckTxVersion<Runtime>,
frame_system::CheckGenesis<Runtime>,
frame_system::CheckEra<Runtime>,
frame_system::CheckNonce<Runtime>,
frame_system::CheckWeight<Runtime>,
pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
/// The payload being signed in transactions.
pub type SignedPayload = generic::SignedPayload<RuntimeCall, SignedExtra>;
/// Extrinsic type that has already been checked.
pub type CheckedExtrinsic =
fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra, H160>;
/// Executive: handles dispatch to the various modules.
pub type Executive = frame_executive::Executive<
Runtime,
Block,
frame_system::ChainContext<Runtime>,
Runtime,
AllPalletsWithSystem,
>;
impl fp_self_contained::SelfContainedCall for RuntimeCall {
type SignedInfo = H160;
fn is_self_contained(&self) -> bool {
match self {
RuntimeCall::Ethereum(call) => call.is_self_contained(),
_ => false,
}
}
fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {
match self {
RuntimeCall::Ethereum(call) => call.check_self_contained(),
_ => None,
}
}
fn validate_self_contained(
&self,
info: &Self::SignedInfo,
dispatch_info: &DispatchInfoOf<RuntimeCall>,
len: usize,
) -> Option<TransactionValidity> {
match self {
RuntimeCall::Ethereum(call) => call.validate_self_contained(info, dispatch_info, len),
_ => None,
}
}
fn pre_dispatch_self_contained(
&self,
info: &Self::SignedInfo,
dispatch_info: &DispatchInfoOf<RuntimeCall>,
len: usize,
) -> Option<Result<(), TransactionValidityError>> {
match self {
RuntimeCall::Ethereum(call) => {
call.pre_dispatch_self_contained(info, dispatch_info, len)
}
_ => None,
}
}
fn apply_self_contained(
self,
info: Self::SignedInfo,
) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {
match self {
call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => {
Some(call.dispatch(RuntimeOrigin::from(
pallet_ethereum::RawOrigin::EthereumTransaction(info),
)))
}
_ => None,
}
}
}
#[cfg(feature = "runtime-benchmarks")]
#[macro_use]
extern crate frame_benchmarking;
#[cfg(feature = "runtime-benchmarks")]
mod benches {
define_benchmarks!(
[frame_benchmarking, BaselineBench::<Runtime>]
[frame_system, SystemBench::<Runtime>]
[pallet_balances, Balances]
[pallet_timestamp, Timestamp]
[pallet_dapps_staking, DappsStaking]
[pallet_block_reward, BlockReward]
[pallet_xc_asset_config, XcAssetConfig]
);
}
impl_runtime_apis! {
impl sp_api::Core<Block> for Runtime {
fn version() -> RuntimeVersion {
VERSION
}
fn execute_block(block: Block) {
Executive::execute_block(block)
}
fn initialize_block(header: &<Block as BlockT>::Header) {
Executive::initialize_block(header)
}
}
impl sp_api::Metadata<Block> for Runtime {
fn metadata() -> OpaqueMetadata {
OpaqueMetadata::new(Runtime::metadata().into())
}
}
impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
fn slot_duration() -> sp_consensus_aura::SlotDuration {
sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())
}
fn authorities() -> Vec<AuraId> {
Aura::authorities().into_inner()
}
}
impl sp_block_builder::BlockBuilder<Block> for Runtime {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
Executive::apply_extrinsic(extrinsic)
}
fn finalize_block() -> <Block as BlockT>::Header {
Executive::finalize_block()
}
fn inherent_extrinsics(data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
data.create_extrinsics()
}
fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult {
data.check_extrinsics(&block)
}
}
impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
fn validate_transaction(
source: TransactionSource,
tx: <Block as BlockT>::Extrinsic,
block_hash: <Block as BlockT>::Hash,
) -> TransactionValidity {
Executive::validate_transaction(source, tx, block_hash)
}
}
impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
fn offchain_worker(header: &<Block as BlockT>::Header) {
Executive::offchain_worker(header)
}
}
impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
fn account_nonce(account: AccountId) -> Index {
System::account_nonce(account)
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
Block,
Balance,
> for Runtime {
fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {
TransactionPayment::query_info(uxt, len)
}
fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {
TransactionPayment::query_fee_details(uxt, len)
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
for Runtime
{
fn query_call_info(
call: RuntimeCall,
len: u32,
) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
TransactionPayment::query_call_info(call, len)