This repository has been archived by the owner on Mar 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathlib.rs
911 lines (769 loc) · 27.2 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
// This file is part of Darwinia.
//
// Copyright (C) 2018-2021 Darwinia Network
// SPDX-License-Identifier: GPL-3.0
//
// Darwinia 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.
//
// Darwinia 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 Darwinia. If not, see <https://www.gnu.org/licenses/>.
//! The Darwinia Node Template 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 mod constants {
// --- substrate ---
use sp_staking::SessionIndex;
// --- darwinia ---
use crate::*;
pub const NANO: Balance = 1;
pub const MICRO: Balance = 1_000 * NANO;
pub const MILLI: Balance = 1_000 * MICRO;
pub const COIN: Balance = 1_000 * MILLI;
pub const CAP: Balance = 10_000_000_000 * COIN;
pub const TOTAL_POWER: Power = 1_000_000_000;
// Time is measured by number of blocks.
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
pub const HOURS: BlockNumber = 60 * MINUTES;
pub const DAYS: BlockNumber = 24 * HOURS;
pub const MILLISECS_PER_BLOCK: Moment = 6000;
pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK;
pub const BLOCKS_PER_SESSION: BlockNumber = 3 * MINUTES;
pub const SESSIONS_PER_ERA: SessionIndex = 6;
// 1 in 4 blocks (on average, not counting collisions) will be primary babe blocks.
pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4);
pub const fn deposit(items: u32, bytes: u32) -> Balance {
items as Balance * 20 * COIN + (bytes as Balance) * 100 * MICRO
}
}
pub mod impls {
//! Some configurable implementations as associated type for the substrate runtime.
pub mod relay {
// --- darwinia ---
use crate::*;
use darwinia_relay_primitives::relayer_game::*;
use ethereum_primitives::EthereumBlockNumber;
pub struct EthereumRelayerGameAdjustor;
impl AdjustableRelayerGame for EthereumRelayerGameAdjustor {
type Moment = BlockNumber;
type Balance = Balance;
type RelayHeaderId = EthereumBlockNumber;
fn max_active_games() -> u8 {
32
}
fn affirm_time(round: u32) -> Self::Moment {
match round {
// 1.5 mins
0 => 15,
// 0.5 mins
_ => 5,
}
}
fn complete_proofs_time(round: u32) -> Self::Moment {
match round {
// 1.5 mins
0 => 15,
// 0.5 mins
_ => 5,
}
}
fn update_sample_points(sample_points: &mut Vec<Vec<Self::RelayHeaderId>>) {
sample_points.push(vec![sample_points.last().unwrap().last().unwrap() - 1]);
}
fn estimate_stake(round: u32, affirmations_count: u32) -> Self::Balance {
match round {
0 => match affirmations_count {
0 => 1000 * COIN,
_ => 1500 * COIN,
},
_ => 100 * COIN,
}
}
}
}
// --- crates ---
use smallvec::smallvec;
// --- substrate ---
use frame_support::{
traits::{Currency, Imbalance, OnUnbalanced},
weights::{WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial},
};
// --- darwinia ---
use crate::*;
darwinia_support::impl_account_data! {
struct AccountData<Balance>
for
RingInstance,
KtonInstance
where
Balance = Balance
{
// other data
}
}
pub struct Author;
impl OnUnbalanced<NegativeImbalance> for Author {
fn on_nonzero_unbalanced(amount: NegativeImbalance) {
Ring::resolve_creating(&Authorship::author(), amount);
}
}
pub struct DealWithFees;
impl OnUnbalanced<NegativeImbalance> for DealWithFees {
fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {
if let Some(fees) = fees_then_tips.next() {
// for fees, 80% to treasury, 20% to author
let mut split = fees.ration(80, 20);
if let Some(tips) = fees_then_tips.next() {
// for tips, if any, 80% to treasury, 20% to author (though this can be anything)
tips.ration_merge_into(80, 20, &mut split);
}
Treasury::on_unbalanced(split.0);
Author::on_unbalanced(split.1);
}
}
}
/// 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 Crab, extrinsic base weight (smallest non-zero weight) is mapped to 100 MILLI:
let p = 100 * MILLI;
let q = Balance::from(ExtrinsicBaseWeight::get());
smallvec![WeightToFeeCoefficient {
degree: 1,
negative: false,
coeff_frac: Perbill::from_rational_approximation(p % q, q),
coeff_integer: p / q,
}]
}
}
}
pub mod wasm {
//! Make the WASM binary available.
#[cfg(all(feature = "std", any(target_arch = "x86_64", target_arch = "x86")))]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
#[cfg(all(feature = "std", not(any(target_arch = "x86_64", target_arch = "x86"))))]
pub const WASM_BINARY: &[u8] = include_bytes!("../../../../wasm/pangolin_runtime.compact.wasm");
#[cfg(all(feature = "std", not(any(target_arch = "x86_64", target_arch = "x86"))))]
pub const WASM_BINARY_BLOATY: &[u8] = include_bytes!("../../../../wasm/pangolin_runtime.wasm");
/// Wasm binary unwrapped. If built with `BUILD_DUMMY_WASM_BINARY`, the function panics.
#[cfg(feature = "std")]
pub fn wasm_binary_unwrap() -> &'static [u8] {
#[cfg(all(feature = "std", any(target_arch = "x86_64", target_arch = "x86")))]
return WASM_BINARY.expect(
"Development wasm binary is not available. This means the client is \
built with `SKIP_WASM_BUILD` flag and it is only usable for \
production chains. Please rebuild with the flag disabled.",
);
#[cfg(all(feature = "std", not(any(target_arch = "x86_64", target_arch = "x86"))))]
return WASM_BINARY;
}
}
pub mod system;
pub use system::*;
pub mod babe;
pub use babe::*;
pub mod timestamp;
pub use timestamp::*;
pub mod balances;
pub use balances::*;
pub mod transaction_payment;
pub use transaction_payment::*;
pub mod authorship;
pub use authorship::*;
pub mod election_provider_multi_phase;
pub use election_provider_multi_phase::*;
pub mod staking;
pub use staking::*;
pub mod offences;
pub use offences::*;
pub mod session_historical;
pub use session_historical::*;
pub mod session;
pub use session::*;
pub mod grandpa;
pub use grandpa::*;
pub mod im_online;
pub use im_online::*;
pub mod authority_discovery;
pub use authority_discovery::*;
pub mod header_mmr;
pub use header_mmr::*;
pub mod democracy;
pub use democracy::*;
pub mod collective;
pub use collective::*;
pub mod elections_phragmen;
pub use elections_phragmen::*;
pub mod membership;
pub use membership::*;
pub mod treasury;
pub use treasury::*;
pub mod sudo;
pub use sudo::*;
pub mod claims;
pub use claims::*;
pub mod vesting;
pub use vesting::*;
pub mod utility;
pub use utility::*;
pub mod identity;
pub use identity::*;
pub mod society;
pub use society::*;
pub mod recovery;
pub use recovery::*;
pub mod scheduler;
pub use scheduler::*;
pub mod proxy;
pub use proxy::*;
pub mod multisig;
pub use multisig::*;
pub mod crab_issuing;
pub use crab_issuing::*;
pub mod crab_backing;
pub use crab_backing::*;
pub mod ethereum_relay;
pub use ethereum_relay::*;
pub mod ethereum_backing;
pub use ethereum_backing::*;
pub mod relayer_game;
pub use relayer_game::*;
pub mod relay_authorities;
pub use relay_authorities::*;
pub mod tron_backing;
pub use tron_backing::*;
pub mod evm;
pub use evm::*;
pub mod dvm;
pub use dvm::*;
// --- darwinia ---
pub use constants::*;
pub use darwinia_staking::StakerStatus;
pub use wasm::*;
// --- crates ---
use codec::{Decode, Encode};
// --- substrate ---
use frame_support::{
traits::{KeyOwnerProofSystem, Randomness},
weights::constants::ExtrinsicBaseWeight,
};
use pallet_grandpa::{
fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList,
};
use pallet_transaction_payment::FeeDetails;
use pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo as TransactionPaymentRuntimeDispatchInfo;
use sp_api::impl_runtime_apis;
use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H160, H256, U256};
use sp_runtime::{
create_runtime_str, generic,
traits::{Block as BlockT, NumberFor, SaturatedConversion, StaticLookup},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, MultiAddress, OpaqueExtrinsic, Perbill, RuntimeDebug,
};
use sp_std::prelude::*;
#[cfg(feature = "std")]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
// --- darwinia ---
use darwinia_balances_rpc_runtime_api::RuntimeDispatchInfo as BalancesRuntimeDispatchInfo;
use darwinia_evm::{Account as EVMAccount, FeeCalculator, Runner};
use darwinia_header_mmr_rpc_runtime_api::RuntimeDispatchInfo as HeaderMMRRuntimeDispatchInfo;
use darwinia_staking_rpc_runtime_api::RuntimeDispatchInfo as StakingRuntimeDispatchInfo;
use drml_primitives::*;
use dvm_rpc_runtime_api::TransactionStatus;
use impls::*;
/// The address format for describing accounts.
type Address = MultiAddress<AccountId, ()>;
/// Block type as expected by this runtime.
type Block = generic::Block<Header, UncheckedExtrinsic>;
/// The SignedExtension to the basic transaction logic.
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>,
darwinia_ethereum_relay::CheckEthereumRelayHeaderParcel<Runtime>,
);
/// Unchecked extrinsic type as expected by this runtime.
type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
/// Executive: handles dispatch to the various modules.
type Executive = frame_executive::Executive<
Runtime,
Block,
frame_system::ChainContext<Runtime>,
Runtime,
AllModules,
// (),
// CustomOnRuntimeUpgrade,
>;
/// The payload being signed in transactions.
type SignedPayload = generic::SignedPayload<Call, SignedExtra>;
type Ring = Balances;
/// This runtime version.
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("Pangolin"),
impl_name: create_runtime_str!("Pangolin"),
authoring_version: 1,
// crate version 2.1.0
spec_version: 210,
impl_version: 1,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
};
/// 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(),
}
}
frame_support::construct_runtime! {
pub enum Runtime
where
Block = Block,
NodeBlock = OpaqueBlock,
UncheckedExtrinsic = UncheckedExtrinsic
{
// Basic stuff; balances is uncallable initially.
System: frame_system::{Module, Call, Storage, Config, Event<T>} = 0,
RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage} = 1,
// Must be before session.
Babe: pallet_babe::{Module, Call, Storage, Config, ValidateUnsigned} = 2,
Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent} = 3,
Balances: darwinia_balances::<Instance0>::{Module, Call, Storage, Config<T>, Event<T>} = 4,
Kton: darwinia_balances::<Instance1>::{Module, Call, Storage, Config<T>, Event<T>} = 5,
TransactionPayment: pallet_transaction_payment::{Module, Storage} = 6,
// Consensus support.
Authorship: pallet_authorship::{Module, Call, Storage, Inherent} = 7,
ElectionProviderMultiPhase: pallet_election_provider_multi_phase::{Module, Call, Storage, Event<T>, ValidateUnsigned} = 8,
Staking: darwinia_staking::{Module, Call, Storage, Config<T>, Event<T>, ValidateUnsigned} = 9,
Offences: pallet_offences::{Module, Call, Storage, Event} = 10,
Historical: pallet_session_historical::{Module} = 11,
Session: pallet_session::{Module, Call, Storage, Config<T>, Event} = 12,
Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event, ValidateUnsigned} = 13,
ImOnline: pallet_im_online::{Module, Call, Storage, Config<T>, Event<T>, ValidateUnsigned} = 14,
AuthorityDiscovery: pallet_authority_discovery::{Module, Call, Config} = 15,
HeaderMMR: darwinia_header_mmr::{Module, Call, Storage} = 16,
// Governance stuff; uncallable initially.
Democracy: darwinia_democracy::{Module, Call, Storage, Config, Event<T>} = 17,
Council: pallet_collective::<Instance0>::{Module, Call, Storage, Origin<T>, Config<T>, Event<T>} = 18,
TechnicalCommittee: pallet_collective::<Instance1>::{Module, Call, Storage, Origin<T>, Config<T>, Event<T>} = 19,
ElectionsPhragmen: darwinia_elections_phragmen::{Module, Call, Storage, Config<T>, Event<T>} = 20,
TechnicalMembership: pallet_membership::<Instance0>::{Module, Call, Storage, Config<T>, Event<T>} = 21,
Treasury: darwinia_treasury::{Module, Call, Storage, Event<T>} = 22,
Sudo: pallet_sudo::{Module, Call, Storage, Config<T>, Event<T>} = 23,
// Claims. Usable initially.
Claims: darwinia_claims::{Module, Call, Storage, Config, Event<T>, ValidateUnsigned} = 24,
// Vesting. Usable initially, but removed once all vesting is finished.
Vesting: darwinia_vesting::{Module, Call, Storage, Event<T>, Config<T>} = 25,
// Utility module.
Utility: pallet_utility::{Module, Call, Event} = 26,
// Less simple identity module.
Identity: pallet_identity::{Module, Call, Storage, Event<T>} = 27,
// Society module.
Society: pallet_society::{Module, Call, Storage, Event<T>} = 28,
// Social recovery module.
Recovery: pallet_recovery::{Module, Call, Storage, Event<T>} = 29,
// System scheduler.
Scheduler: pallet_scheduler::{Module, Call, Storage, Event<T>} = 30,
// Proxy module. Late addition.
Proxy: pallet_proxy::{Module, Call, Storage, Event<T>} = 31,
// Multisig module. Late addition.
Multisig: pallet_multisig::{Module, Call, Storage, Event<T>} = 32,
CrabIssuing: darwinia_crab_issuing::{Module, Call, Storage, Config, Event<T>} = 33,
CrabBacking: darwinia_crab_backing::{Module, Storage, Config<T>} = 34,
EthereumRelay: darwinia_ethereum_relay::{Module, Call, Storage, Config<T>, Event<T>} = 35,
EthereumBacking: darwinia_ethereum_backing::{Module, Call, Storage, Config<T>, Event<T>} = 36,
EthereumRelayerGame: darwinia_relayer_game::<Instance0>::{Module, Storage} = 37,
EthereumRelayAuthorities: darwinia_relay_authorities::<Instance0>::{Module, Call, Storage, Config<T>, Event<T>} = 38,
TronBacking: darwinia_tron_backing::{Module, Storage, Config<T>} = 39,
EVM: darwinia_evm::{Module, Call, Storage, Config, Event<T>} = 40,
Ethereum: dvm_ethereum::{Module, Call, Storage, Config, Event, ValidateUnsigned} = 41,
}
}
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
where
Call: From<LocalCall>,
{
fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
call: Call,
public: <Signature as sp_runtime::traits::Verify>::Signer,
account: AccountId,
nonce: Nonce,
) -> Option<(
Call,
<UncheckedExtrinsic as sp_runtime::traits::Extrinsic>::SignaturePayload,
)> {
// take the biggest period possible.
let period = BlockHashCount::get()
.checked_next_power_of_two()
.map(|c| c / 2)
.unwrap_or(2) as u64;
let current_block = System::block_number()
.saturated_into::<u64>()
// The `System::block_number` is initialized with `n+1`,
// so the actual block number is `n`.
.saturating_sub(1);
let tip = 0;
let extra: SignedExtra = (
frame_system::CheckSpecVersion::<Runtime>::new(),
frame_system::CheckTxVersion::<Runtime>::new(),
frame_system::CheckGenesis::<Runtime>::new(),
frame_system::CheckEra::<Runtime>::from(generic::Era::mortal(period, current_block)),
frame_system::CheckNonce::<Runtime>::from(nonce),
frame_system::CheckWeight::<Runtime>::new(),
pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
darwinia_ethereum_relay::CheckEthereumRelayHeaderParcel::<Runtime>::new(),
);
let raw_payload = SignedPayload::new(call, extra)
.map_err(|e| {
log::warn!("Unable to create signed payload: {:?}", e);
})
.ok()?;
let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
let (call, extra, _) = raw_payload.deconstruct();
let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
Some((call, (address, signature, extra)))
}
}
impl frame_system::offchain::SigningTypes for Runtime {
type Public = <Signature as sp_runtime::traits::Verify>::Signer;
type Signature = Signature;
}
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
where
Call: From<C>,
{
type Extrinsic = UncheckedExtrinsic;
type OverarchingCall = Call;
}
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 {
Runtime::metadata().into()
}
}
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: sp_inherents::InherentData
) -> Vec<<Block as BlockT>::Extrinsic> {
data.create_extrinsics()
}
fn check_inherents(
block: Block,
data: sp_inherents::InherentData,
) -> sp_inherents::CheckInherentsResult {
data.check_extrinsics(&block)
}
fn random_seed() -> <Block as BlockT>::Hash {
RandomnessCollectiveFlip::random_seed()
}
}
impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
fn validate_transaction(
source: TransactionSource,
tx: <Block as BlockT>::Extrinsic,
) -> TransactionValidity {
Executive::validate_transaction(source, tx)
}
}
impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
fn offchain_worker(header: &<Block as BlockT>::Header) {
Executive::offchain_worker(header)
}
}
impl fg_primitives::GrandpaApi<Block> for Runtime {
fn grandpa_authorities() -> GrandpaAuthorityList {
Grandpa::grandpa_authorities()
}
fn submit_report_equivocation_unsigned_extrinsic(
equivocation_proof: fg_primitives::EquivocationProof<
<Block as BlockT>::Hash,
NumberFor<Block>,
>,
key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,
) -> Option<()> {
let key_owner_proof = key_owner_proof.decode()?;
Grandpa::submit_unsigned_equivocation_report(
equivocation_proof,
key_owner_proof,
)
}
fn generate_key_ownership_proof(
_set_id: fg_primitives::SetId,
authority_id: GrandpaId,
) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {
Historical::prove((fg_primitives::KEY_TYPE, authority_id))
.map(|p| p.encode())
.map(fg_primitives::OpaqueKeyOwnershipProof::new)
}
}
impl sp_consensus_babe::BabeApi<Block> for Runtime {
fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration {
// The choice of `c` parameter (where `1 - c` represents the
// probability of a slot being empty), is done in accordance to the
// slot duration and expected target block time, for safely
// resisting network delays of maximum two seconds.
// <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>
sp_consensus_babe::BabeGenesisConfiguration {
slot_duration: Babe::slot_duration(),
epoch_length: EpochDuration::get(),
c: PRIMARY_PROBABILITY,
genesis_authorities: Babe::authorities(),
randomness: Babe::randomness(),
allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryPlainSlots,
}
}
fn current_epoch_start() -> sp_consensus_babe::Slot {
Babe::current_epoch_start()
}
fn current_epoch() -> sp_consensus_babe::Epoch {
Babe::current_epoch()
}
fn next_epoch() -> sp_consensus_babe::Epoch {
Babe::next_epoch()
}
fn generate_key_ownership_proof(
_slot: sp_consensus_babe::Slot,
authority_id: sp_consensus_babe::AuthorityId,
) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> {
Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id))
.map(|p| p.encode())
.map(sp_consensus_babe::OpaqueKeyOwnershipProof::new)
}
fn submit_report_equivocation_unsigned_extrinsic(
equivocation_proof: sp_consensus_babe::EquivocationProof<<Block as BlockT>::Header>,
key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof,
) -> Option<()> {
let key_owner_proof = key_owner_proof.decode()?;
Babe::submit_unsigned_equivocation_report(
equivocation_proof,
key_owner_proof,
)
}
}
impl sp_authority_discovery::AuthorityDiscoveryApi<Block> for Runtime {
fn authorities() -> Vec<AuthorityDiscoveryId> {
AuthorityDiscovery::authorities()
}
}
impl sp_session::SessionKeys<Block> for Runtime {
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
SessionKeys::generate(seed)
}
fn decode_session_keys(
encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
SessionKeys::decode_into_raw_public_keys(&encoded)
}
}
impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
fn account_nonce(account: AccountId) -> Nonce {
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) -> TransactionPaymentRuntimeDispatchInfo<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 darwinia_balances_rpc_runtime_api::BalancesApi<Block, AccountId, Balance> for Runtime {
fn usable_balance(instance: u8, account: AccountId) -> BalancesRuntimeDispatchInfo<Balance> {
match instance {
0 => Ring::usable_balance_rpc(account),
1 => Kton::usable_balance_rpc(account),
_ => Default::default()
}
}
}
impl darwinia_header_mmr_rpc_runtime_api::HeaderMMRApi<Block, Hash> for Runtime {
fn gen_proof(
block_number_of_member_leaf: u64,
block_number_of_last_leaf: u64
) -> HeaderMMRRuntimeDispatchInfo<Hash> {
HeaderMMR::gen_proof_rpc(block_number_of_member_leaf, block_number_of_last_leaf )
}
}
impl darwinia_staking_rpc_runtime_api::StakingApi<Block, AccountId, Power> for Runtime {
fn power_of(account: AccountId) -> StakingRuntimeDispatchInfo<Power> {
Staking::power_of_rpc(account)
}
}
impl dvm_rpc_runtime_api::EthereumRuntimeRPCApi<Block> for Runtime {
fn chain_id() -> u64 {
<Runtime as darwinia_evm::Config>::ChainId::get()
}
fn gas_price() -> U256 {
<Runtime as darwinia_evm::Config>::FeeCalculator::min_gas_price()
}
fn account_basic(address: H160) -> EVMAccount {
// --- darwinia ---
use darwinia_evm::AccountBasicMapping;
<Runtime as darwinia_evm::Config>::AccountBasicMapping::account_basic(&address)
}
fn account_code_at(address: H160) -> Vec<u8> {
darwinia_evm::Module::<Runtime>::account_codes(address)
}
fn author() -> H160 {
<dvm_ethereum::Module<Runtime>>::find_author()
}
fn storage_at(address: H160, index: U256) -> H256 {
let mut tmp = [0u8; 32];
index.to_big_endian(&mut tmp);
darwinia_evm::Module::<Runtime>::account_storages(address, H256::from_slice(&tmp[..]))
}
fn call(
from: H160,
to: H160,
data: Vec<u8>,
value: U256,
gas_limit: U256,
gas_price: Option<U256>,
nonce: Option<U256>,
estimate: bool,
) -> Result<darwinia_evm::CallInfo, sp_runtime::DispatchError> {
let config = if estimate {
let mut config = <Runtime as darwinia_evm::Config>::config().clone();
config.estimate = true;
Some(config)
} else {
None
};
<Runtime as darwinia_evm::Config>::Runner::call(
from,
to,
data,
value,
gas_limit.low_u64(),
gas_price,
nonce,
config.as_ref().unwrap_or(<Runtime as darwinia_evm::Config>::config()),
).map_err(|err| err.into())
}
fn create(
from: H160,
data: Vec<u8>,
value: U256,
gas_limit: U256,
gas_price: Option<U256>,
nonce: Option<U256>,
estimate: bool,
) -> Result<darwinia_evm::CreateInfo, sp_runtime::DispatchError> {
let config = if estimate {
let mut config = <Runtime as darwinia_evm::Config>::config().clone();
config.estimate = true;
Some(config)
} else {
None
};
<Runtime as darwinia_evm::Config>::Runner::create(
from,
data,
value,
gas_limit.low_u64(),
gas_price,
nonce,
config.as_ref().unwrap_or(<Runtime as darwinia_evm::Config>::config()),
).map_err(|err| err.into())
}
fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {
Ethereum::current_transaction_statuses()
}
fn current_block() -> Option<dvm_ethereum::Block> {
Ethereum::current_block()
}
fn current_receipts() -> Option<Vec<dvm_ethereum::Receipt>> {
Ethereum::current_receipts()
}
fn current_all() -> (
Option<dvm_ethereum::Block>,
Option<Vec<dvm_ethereum::Receipt>>,
Option<Vec<TransactionStatus>>
) {
(
Ethereum::current_block(),
Ethereum::current_receipts(),
Ethereum::current_transaction_statuses()
)
}
}
#[cfg(feature = "try-runtime")]
impl frame_try_runtime::TryRuntime<Block> for Runtime {
fn on_runtime_upgrade() -> Result<(Weight, Weight), sp_runtime::RuntimeString> {
let weight = Executive::try_runtime_upgrade()?;
Ok((weight, RuntimeBlockWeights::get().max_block))
}
}
}
pub struct TransactionConverter;
impl dvm_rpc_runtime_api::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {
fn convert_transaction(&self, transaction: dvm_ethereum::Transaction) -> UncheckedExtrinsic {
UncheckedExtrinsic::new_unsigned(
<dvm_ethereum::Call<Runtime>>::transact(transaction).into(),
)
}
}
impl dvm_rpc_runtime_api::ConvertTransaction<OpaqueExtrinsic> for TransactionConverter {
fn convert_transaction(&self, transaction: dvm_ethereum::Transaction) -> OpaqueExtrinsic {
let extrinsic = UncheckedExtrinsic::new_unsigned(
<dvm_ethereum::Call<Runtime>>::transact(transaction).into(),
);
let encoded = extrinsic.encode();
OpaqueExtrinsic::decode(&mut &encoded[..]).expect("Encoded extrinsic is always valid")
}
}
// pub struct CustomOnRuntimeUpgrade;
// impl frame_support::traits::OnRuntimeUpgrade for CustomOnRuntimeUpgrade {
// fn on_runtime_upgrade() -> frame_support::weights::Weight {
// // --- substrate ---
// use frame_support::migration::*;
// MAXIMUM_BLOCK_WEIGHT
// }
// }