-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathlib.rs
More file actions
1649 lines (1428 loc) · 52.6 KB
/
Copy pathlib.rs
File metadata and controls
1649 lines (1428 loc) · 52.6 KB
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 HydraDX-node.
// Copyright (C) 2020-2023 Intergalactic, Limited (GIB).
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
#![recursion_limit = "512"]
#![allow(clippy::match_like_matches_macro)]
#![allow(clippy::items_after_test_module)]
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
#[cfg(test)]
mod tests;
mod benchmarking;
mod migrations;
pub mod weights;
mod assets;
pub mod circuit_breaker;
pub mod evm;
pub mod gigahdx;
pub mod governance;
mod helpers;
mod system;
pub mod types;
pub mod xcm;
extern crate alloc;
use alloc::borrow::Cow;
#[allow(ambiguous_glob_reexports)]
pub use assets::*;
pub use cumulus_primitives_core::{GeneralIndex, Here, Junctions, NetworkId, NonFungible, Response};
pub use frame_support::{assert_ok, parameter_types, storage::with_transaction, traits::TrackedStorageKey};
pub use frame_system::RawOrigin;
pub use governance::origins::pallet_custom_origins;
pub use governance::*;
pub use pallet_asset_registry::AssetType;
pub use pallet_currencies_rpc_runtime_api::AccountData;
pub use pallet_referrals::{FeeDistribution, Level};
pub use polkadot_xcm::opaque::lts::InteriorLocation;
pub use system::*;
pub use xcm::*;
use codec::{Decode, Encode};
use hydradx_traits::evm::InspectEvmAccounts;
use primitives::EvmAddress;
use sp_core::{ConstU128, Get, H160, H256, U256};
use sp_genesis_builder::PresetId;
pub use sp_runtime::{
generic, impl_opaque_keys,
traits::{
AccountIdConversion, BlakeTwo256, Block as BlockT, DispatchInfoOf, Dispatchable, PostDispatchInfoOf,
UniqueSaturatedInto,
},
transaction_validity::{InvalidTransaction, TransactionValidity, TransactionValidityError},
DispatchError, Permill, TransactionOutcome,
};
use sp_std::{convert::From, prelude::*};
#[cfg(feature = "std")]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
// A few exports that help ease life for downstream crates.
use ethereum::AuthorizationList;
use frame_support::{construct_runtime, pallet_prelude::Hooks, traits::Contains, weights::Weight};
pub use hex_literal::hex;
use orml_traits::MultiCurrency;
/// Import HydraDX pallets
pub use pallet_claims;
use pallet_ethereum::{Transaction as EthereumTransaction, TransactionStatus};
use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, Runner};
pub use pallet_genesis_history::Chain;
use polkadot_xcm::prelude::XcmVersion;
pub use primitives::{
constants::time::SLOT_DURATION, AccountId, Amount, AssetId, Balance, BlockNumber, CollectionId, Hash, Index,
ItemId, Price, Signature,
};
use sp_api::impl_runtime_apis;
pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
/// to even the core data structures.
pub mod opaque {
use super::*;
use sp_runtime::{
generic,
traits::{BlakeTwo256, Hash as HashT},
};
pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
/// Opaque block header type.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// Opaque block type.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// Opaque block identifier type.
pub type BlockId = generic::BlockId<Block>;
/// Opaque block hash type.
pub type Hash = <BlakeTwo256 as HashT>::Output;
impl_opaque_keys! {
pub struct SessionKeys {
pub aura: Aura,
}
}
}
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: Cow::Borrowed("hydradx"),
impl_name: Cow::Borrowed("hydradx"),
authoring_version: 1,
spec_version: 428,
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
system_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(),
}
}
// Create the runtime by composing the FRAME pallets that were previously configured
construct_runtime!(
pub enum Runtime
{
System: frame_system exclude_parts { Origin } = 1,
Timestamp: pallet_timestamp = 3,
//NOTE: 5 - is used by Scheduler which must be after cumulus_pallet_parachain_system
Balances: pallet_balances = 7,
TransactionPayment: pallet_transaction_payment exclude_parts { Config } = 9,
// due to multi payment pallet prices, this needs to be initialized at the very beginning
MultiTransactionPayment: pallet_transaction_multi_payment = 203,
Treasury: pallet_treasury = 11,
Utility: pallet_utility = 13,
Preimage: pallet_preimage = 15,
Identity: pallet_identity = 17,
Democracy: pallet_democracy exclude_parts { Config } = 19,
// NOTE 19, 21, 23 & 27 are retired (was used by gov v1)
TechnicalCommittee: pallet_collective::<Instance2> = 25,
Proxy: pallet_proxy = 29,
Multisig: pallet_multisig = 31,
Uniques: pallet_uniques = 32,
StateTrieMigration: pallet_state_trie_migration = 35,
// OpenGov
ConvictionVoting: pallet_conviction_voting = 36,
Referenda: pallet_referenda = 37,
Origins: pallet_custom_origins = 38,
Whitelist: pallet_whitelist = 39,
Dispatcher: pallet_dispatcher = 40,
// HydraDX related modules
AssetRegistry: pallet_asset_registry = 51,
Claims: pallet_claims = 53,
GenesisHistory: pallet_genesis_history = 55,
CollatorRewards: pallet_collator_rewards = 57,
CollatorRotation: pallet_collator_rotation = 58,
Omnipool: pallet_omnipool = 59,
TransactionPause: pallet_transaction_pause = 60,
Duster: pallet_duster = 61,
OmnipoolWarehouseLM: warehouse_liquidity_mining::<Instance1> = 62,
OmnipoolLiquidityMining: pallet_omnipool_liquidity_mining = 63,
OTC: pallet_otc = 64,
CircuitBreaker: pallet_circuit_breaker = 65,
Router: pallet_route_executor = 67,
DynamicFees: pallet_dynamic_fees = 68,
Staking: pallet_staking = 69,
Stableswap: pallet_stableswap = 70,
Bonds: pallet_bonds = 71,
OtcSettlements: pallet_otc_settlements = 72,
LBP: pallet_lbp = 73,
XYK: pallet_xyk = 74,
Referrals: pallet_referrals = 75,
Liquidation: pallet_liquidation = 76,
HSM: pallet_hsm = 82,
Parameters: pallet_parameters = 83,
Signet: pallet_signet = 84,
EthDispenser: pallet_dispenser = 85,
GigaHdx: pallet_gigahdx = 86,
GigaHdxRewards: pallet_gigahdx_rewards = 87,
// ORML related modules
Tokens: orml_tokens = 77,
Currencies: pallet_currencies = 79,
Vesting: orml_vesting = 81,
// Frontier and EVM pallets
EVM: pallet_evm = 90,
EVMChainId: pallet_evm_chain_id = 91,
Ethereum: pallet_ethereum = 92,
EVMAccounts: pallet_evm_accounts = 93,
DynamicEvmFee: pallet_dynamic_evm_fee = 94,
XYKLiquidityMining: pallet_xyk_liquidity_mining = 95,
XYKWarehouseLM: warehouse_liquidity_mining::<Instance2> = 96,
RelayChainInfo: pallet_relaychain_info = 201,
//NOTE: DCA pallet should be declared before ParachainSystem pallet,
//otherwise there is no data about relay chain parent hash
DCA: pallet_dca = 66,
//NOTE: Scheduler must be before ParachainSystem otherwise RelayChainBlockNumberProvider
//will return 0 as current block number when used with Scheduler(democracy).
Scheduler: pallet_scheduler = 5,
// Parachain
ParachainSystem: cumulus_pallet_parachain_system exclude_parts { Config } = 103,
ParachainInfo: staging_parachain_info = 105,
PolkadotXcm: pallet_xcm = 107,
CumulusXcm: cumulus_pallet_xcm = 109,
XcmpQueue: cumulus_pallet_xcmp_queue exclude_parts { Call } = 111,
// 113 was used by DmpQueue which is now replaced by MessageQueue
MessageQueue: pallet_message_queue = 114,
WeightReclaim: cumulus_pallet_weight_reclaim = 115,
MultiBlockMigrations: pallet_migrations = 116,
// ORML XCM
OrmlXcm: orml_xcm = 135,
XTokens: orml_xtokens = 137,
UnknownTokens: orml_unknown_tokens = 139,
// Collator support
Authorship: pallet_authorship = 161,
CollatorSelection: pallet_collator_selection = 163,
Session: pallet_session = 165,
Aura: pallet_aura = 167,
AuraExt: cumulus_pallet_aura_ext = 169,
// Warehouse - let's allocate indices 100+ for warehouse pallets
EmaOracle: pallet_ema_oracle = 202,
Broadcast: pallet_broadcast = 204,
FeeProcessor: pallet_fee_processor = 207,
}
);
/// The address format for describing accounts.
pub type Address = 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, HydraUncheckedExtrinsic>;
/// 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>;
pub type InnerSignedExtra = (
frame_system::CheckNonZeroSender<Runtime>,
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>,
pallet_claims::ValidateClaim<Runtime>,
frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
);
/// Wrap the tuple with `StorageWeightReclaim`.
pub type SignedExtra = cumulus_pallet_weight_reclaim::StorageWeightReclaim<Runtime, InnerSignedExtra>;
/// Unchecked extrinsic type as expected by this runtime.
pub type HydraUncheckedExtrinsic = fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, 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,
migrations::SingleBlockMigrationsList,
>;
impl<LocalCall> frame_system::offchain::CreateTransactionBase<LocalCall> for Runtime
where
RuntimeCall: From<LocalCall>,
{
type RuntimeCall = RuntimeCall;
type Extrinsic = HydraUncheckedExtrinsic;
}
impl<LocalCall> hydradx_traits::CreateBare<LocalCall> for Runtime
where
RuntimeCall: From<LocalCall>,
{
fn create_bare(call: Self::RuntimeCall) -> HydraUncheckedExtrinsic {
HydraUncheckedExtrinsic::new_bare(call)
}
}
#[cfg(feature = "runtime-benchmarks")]
mod benches {
frame_support::parameter_types! {
pub const BenchmarkMaxBalance: crate::Balance = crate::Balance::MAX;
}
frame_benchmarking::define_benchmarks!(
[pallet_lbp, LBP]
[pallet_asset_registry, AssetRegistry]
[pallet_transaction_pause, TransactionPause]
[pallet_circuit_breaker, CircuitBreaker]
[pallet_bonds, Bonds]
[pallet_stableswap, Stableswap]
[pallet_claims, Claims]
[pallet_staking, Staking]
[pallet_referrals, Referrals]
[pallet_otc, OTC]
[pallet_otc_settlements, OtcSettlements]
[pallet_liquidation, Liquidation]
[pallet_state_trie_migration, StateTrieMigration]
[frame_system, SystemBench::<Runtime>]
[pallet_balances, Balances]
[pallet_timestamp, Timestamp]
[pallet_democracy, Democracy]
[pallet_treasury, Treasury]
[pallet_scheduler, Scheduler]
[pallet_utility, Utility]
[pallet_identity, Identity]
[pallet_collective_technical_committee, TechnicalCommittee]
[cumulus_pallet_xcmp_queue, XcmpQueue]
[pallet_message_queue, MessageQueue]
[pallet_preimage, Preimage]
[pallet_multisig, Multisig]
[pallet_proxy, Proxy]
[cumulus_pallet_parachain_system, ParachainSystem]
[pallet_xcm, PalletXcmExtrinsiscsBenchmark::<Runtime>]
[pallet_xcm_benchmarks::fungible, XcmBalances]
[pallet_xcm_benchmarks::generic, XcmGeneric]
[pallet_conviction_voting, ConvictionVoting]
[pallet_referenda, Referenda]
[pallet_whitelist, Whitelist]
[pallet_dispatcher, Dispatcher]
[pallet_hsm, HSM]
[pallet_dynamic_fees, DynamicFees]
[pallet_signet, Signet]
[pallet_dispenser, EthDispenser]
[pallet_gigahdx, GigaHdx]
[pallet_gigahdx_rewards, GigaHdxRewards]
//[ismp_parachain, IsmpParachain]
//[pallet_token_gateway, TokenGateway]
[frame_system_extensions, frame_system_benchmarking::extensions::Pallet::<Runtime>]
[pallet_transaction_payment, TransactionPayment]
[cumulus_pallet_weight_reclaim, WeightReclaim]
[pallet_currencies, benchmarking::currencies::Benchmark]
[orml_tokens, benchmarking::tokens::Benchmark]
[orml_vesting, benchmarking::vesting::Benchmark]
[pallet_transaction_multi_payment, benchmarking::multi_payment::Benchmark]
[pallet_duster, benchmarking::duster::Benchmark]
[pallet_omnipool, benchmarking::omnipool::Benchmark]
[pallet_route_executor, benchmarking::route_executor::Benchmark]
[pallet_dca, benchmarking::dca::Benchmark]
[pallet_fee_processor, benchmarking::fee_processor::Benchmark]
[pallet_xyk, benchmarking::xyk::Benchmark]
[pallet_dynamic_evm_fee, benchmarking::dynamic_evm_fee::Benchmark]
[pallet_xyk_liquidity_mining, benchmarking::xyk_liquidity_mining::Benchmark]
[pallet_omnipool_liquidity_mining, benchmarking::omnipool_liquidity_mining::Benchmark]
[pallet_ema_oracle, benchmarking::ema_oracle::Benchmark]
//[pallet_token_gateway_ismp, benchmarking::token_gateway_ismp::Benchmark]
[pallet_evm_accounts, benchmarking::evm_accounts::Benchmark]
[pallet_migrations, MultiBlockMigrations]
);
}
struct CheckInherents;
#[allow(deprecated)]
#[allow(dead_code)]
// There is some controversy around this deprecation. We can keep it as it is for now.
// See issue: https://github.com/paritytech/polkadot-sdk/issues/2841
impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {
fn check_inherents(
block: &Block,
relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,
) -> sp_inherents::CheckInherentsResult {
let relay_chain_slot = relay_state_proof
.read_slot()
.expect("Could not read the relay chain slot from the proof");
let inherent_data = cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(
relay_chain_slot,
sp_std::time::Duration::from_secs(6),
)
.create_inherent_data()
.expect("Could not create the timestamp inherent data");
inherent_data.check_extrinsics(block)
}
}
cumulus_pallet_parachain_system::register_validate_block! {
Runtime = Runtime,
BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
}
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) => {
// don't allow on-chain EVM transactions from a bound address
if EVMAccounts::bound_account_id(*info).is_some() {
return Some(Err(TransactionValidityError::Invalid(InvalidTransaction::BadSigner)));
}
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,
}
}
}
pub struct TransactionConverter;
impl fp_rpc::ConvertTransaction<HydraUncheckedExtrinsic> for TransactionConverter {
fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> HydraUncheckedExtrinsic {
HydraUncheckedExtrinsic::new_bare(pallet_ethereum::Call::<Runtime>::transact { transaction }.into())
}
}
impl fp_rpc::ConvertTransaction<sp_runtime::OpaqueExtrinsic> for TransactionConverter {
fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> sp_runtime::OpaqueExtrinsic {
let extrinsic =
HydraUncheckedExtrinsic::new_bare(pallet_ethereum::Call::<Runtime>::transact { transaction }.into());
let encoded = extrinsic.encode();
sp_runtime::OpaqueExtrinsic::decode(&mut &encoded[..]).expect("Encoded extrinsic is always valid")
}
}
use crate::evm::aave_trade_executor::AaveTradeExecutor;
use crate::evm::aave_trade_executor::PoolData;
use crate::evm::precompiles::erc20_mapping::HydraErc20Mapping;
use frame_support::{
genesis_builder_helper::{build_state, get_preset},
sp_runtime::{
traits::Convert, transaction_validity::TransactionSource, ApplyExtrinsicResult, ExtrinsicInclusionMode,
FixedPointNumber,
},
weights::WeightToFee as _,
};
use hydradx_traits::evm::Erc20Mapping;
use pallet_liquidation::BorrowingContract;
use pallet_route_executor::TradeExecution;
pub use polkadot_xcm::latest::Junction;
use polkadot_xcm::{IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm};
use primitives::constants::chain::CORE_ASSET_ID;
pub use sp_arithmetic::FixedU128;
use sp_core::OpaqueMetadata;
use xcm_runtime_apis::{
dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
fees::Error as XcmPaymentApiError,
};
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) -> ExtrinsicInclusionMode {
Executive::initialize_block(header)
}
}
impl sp_api::Metadata<Block> for Runtime {
fn metadata() -> OpaqueMetadata {
OpaqueMetadata::new(Runtime::metadata().into())
}
fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
Runtime::metadata_at_version(version)
}
fn metadata_versions() -> sp_std::vec::Vec<u32> {
Runtime::metadata_versions()
}
}
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)
}
}
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 sp_session::SessionKeys<Block> for Runtime {
fn decode_session_keys(
encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
opaque::SessionKeys::decode_into_raw_public_keys(&encoded)
}
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
opaque::SessionKeys::generate(seed)
}
}
impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
fn slot_duration() -> sp_consensus_aura::SlotDuration {
sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
}
fn authorities() -> Vec<AuraId> {
pallet_aura::Authorities::<Runtime>::get().into_inner()
}
}
impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
ParachainSystem::collect_collation_info(header)
}
}
impl cumulus_primitives_core::GetCoreSelectorApi<Block> for Runtime {
fn core_selector() -> (
cumulus_primitives_core::CoreSelector,
cumulus_primitives_core::ClaimQueueOffset,
) {
ParachainSystem::core_selector()
}
}
#[cfg(feature = "try-runtime")]
impl frame_try_runtime::TryRuntime<Block> for Runtime {
fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
log::info!("try-runtime::on_runtime_upgrade.");
let weight = Executive::try_runtime_upgrade(checks).unwrap();
(weight, BlockWeights::get().max_block)
}
fn execute_block(
block: Block,
state_root_check: bool,
signature_check: bool,
select: frame_try_runtime::TryStateSelect,
) -> Weight {
Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
}
}
impl pallet_currencies_rpc_runtime_api::CurrenciesApi<
Block,
AssetId,
AccountId,
Balance,
> for Runtime {
fn account(asset_id: AssetId, who: AccountId) -> AccountData<Balance> {
if asset_id == NativeAssetId::get() {
let data = System::account(&who).data;
AccountData {
free: data.free,
reserved: data.reserved,
frozen: data.frozen,
}
} else {
let tokens_data = Tokens::accounts(who.clone(), asset_id);
let mut data = AccountData {
free: tokens_data.free,
reserved: tokens_data.reserved,
frozen: tokens_data.frozen,
};
if matches!(AssetRegistry::asset_type(asset_id), Some(AssetKind::Erc20)) {
data.free = Self::free_balance(asset_id, who);
}
data
}
}
fn accounts(who: AccountId) -> Vec<(AssetId, AccountData<Balance>)> {
let mut result = Vec::new();
// Add native token (HDX)
let balance = System::account(&who).data;
result.push((
NativeAssetId::get(),
AccountData {
free: balance.free,
reserved: balance.reserved,
frozen: balance.frozen,
}
));
// Add tokens from orml_tokens
result.extend(
orml_tokens::Accounts::<Runtime>::iter_prefix(&who)
.map(|(asset_id, data)| {
let mut account_data = AccountData {
free: data.free,
reserved: data.reserved,
frozen: data.frozen,
};
// Update free balance for ERC20 tokens
if matches!(AssetRegistry::asset_type(asset_id), Some(AssetKind::Erc20)) {
account_data.free = Currencies::free_balance(asset_id, &who);
}
(asset_id, account_data)
})
);
// Add ERC20 tokens with non-zero balance not yet added previously
let existing_ids: Vec<_> = result.iter().map(|(id, _)| *id).collect();
result.extend(
pallet_asset_registry::Assets::<Runtime>::iter()
.filter(|(_, info)| info.asset_type == AssetType::Erc20)
.filter_map(|(asset_id, _)| {
if existing_ids.contains(&asset_id) {
return None;
}
let free = Currencies::free_balance(asset_id, &who);
if free > 0 {
Some((
asset_id,
AccountData {
free,
reserved: 0,
frozen: 0,
}
))
} else {
None
}
})
);
result
}
fn free_balance(asset_id: AssetId, who: AccountId) -> Balance {
Currencies::free_balance(asset_id, &who)
}
fn minimum_balance(asset_id: AssetId) -> Balance {
Currencies::minimum_balance(asset_id)
}
}
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,
) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
TransactionPayment::query_info(uxt, len)
}
fn query_fee_details(
uxt: <Block as BlockT>::Extrinsic,
len: u32,
) -> pallet_transaction_payment_rpc_runtime_api::FeeDetails<Balance> {
TransactionPayment::query_fee_details(uxt, len)
}
fn query_weight_to_fee(weight: Weight) -> Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> Balance {
TransactionPayment::length_to_fee(length)
}
}
// Frontier RPC support
impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {
fn chain_id() -> u64 {
<Runtime as pallet_evm::Config>::ChainId::get()
}
fn account_basic(address: H160) -> EVMAccount {
let (account, _) = EVM::account_basic(&address);
account
}
fn gas_price() -> U256 {
let (gas_price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();
gas_price
}
fn account_code_at(address: H160) -> Vec<u8> {
pallet_evm::AccountCodes::<Runtime>::get(address)
}
fn author() -> H160 {
<pallet_evm::Pallet<Runtime>>::find_author()
}
fn storage_at(address: H160, index: U256) -> H256 {
let tmp = index.to_big_endian();
pallet_evm::AccountStorages::<Runtime>::get(address, H256::from_slice(&tmp[..]))
}
fn call(
from: H160,
to: H160,
data: Vec<u8>,
value: U256,
gas_limit: U256,
max_fee_per_gas: Option<U256>,
max_priority_fee_per_gas: Option<U256>,
nonce: Option<U256>,
estimate: bool,
access_list: Option<Vec<(H160, Vec<H256>)>>,
authorization_list: Option<AuthorizationList>,
) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {
let mut config = <Runtime as pallet_evm::Config>::config().clone();
config.estimate = estimate;
let is_transactional = false;
let validate = true;
// Estimated encoded transaction size must be based on the heaviest transaction
// type (EIP1559Transaction) to be compatible with all transaction types.
let mut estimated_transaction_len = data.len() +
// pallet ethereum index: 1
// transact call index: 1
// Transaction enum variant: 1
// chain_id 8 bytes
// nonce: 32
// max_priority_fee_per_gas: 32
// max_fee_per_gas: 32
// gas_limit: 32
// action: 21 (enum varianrt + call address)
// value: 32
// access_list: 1 (empty vec size)
// 65 bytes signature
258;
if access_list.is_some() {
estimated_transaction_len += access_list.encoded_size();
}
let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
let without_base_extrinsic_weight = true;
let (weight_limit, proof_size_base_cost) =
match <Runtime as pallet_evm::Config>::GasWeightMapping::gas_to_weight(
gas_limit,
without_base_extrinsic_weight
) {
weight_limit if weight_limit.proof_size() > 0 => {
(Some(weight_limit), Some(estimated_transaction_len as u64))
}
_ => (None, None),
};
<Runtime as pallet_evm::Config>::Runner::call(
from,
to,
data,
value,
gas_limit.unique_saturated_into(),
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
access_list.unwrap_or_default(),
authorization_list.clone().unwrap_or_default(),
is_transactional,
validate,
weight_limit,
proof_size_base_cost,
&config,
)
.map_err(|err| err.error.into())
}
fn create(
from: H160,
data: Vec<u8>,
value: U256,
gas_limit: U256,
max_fee_per_gas: Option<U256>,
max_priority_fee_per_gas: Option<U256>,
nonce: Option<U256>,
estimate: bool,
access_list: Option<Vec<(H160, Vec<H256>)>>,
authorization_list: Option<AuthorizationList>,
) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {
let config = if estimate {
let mut config = <Runtime as pallet_evm::Config>::config().clone();
config.estimate = true;
Some(config)
} else {
None
};
let is_transactional = false;
let validate = true;
// Reused approach from Moonbeam since Frontier implementation doesn't support this
let mut estimated_transaction_len = data.len() +
// to: 20
// from: 20
// value: 32
// gas_limit: 32
// nonce: 32
// 1 byte transaction action variant
// chain id 8 bytes
// 65 bytes signature
210;
if max_fee_per_gas.is_some() {
estimated_transaction_len += 32;
}
if max_priority_fee_per_gas.is_some() {
estimated_transaction_len += 32;
}
if access_list.is_some() {
estimated_transaction_len += access_list.encoded_size();
}
let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
let without_base_extrinsic_weight = true;
let (weight_limit, proof_size_base_cost) =
match <Runtime as pallet_evm::Config>::GasWeightMapping::gas_to_weight(
gas_limit,
without_base_extrinsic_weight
) {
weight_limit if weight_limit.proof_size() > 0 => {
(Some(weight_limit), Some(estimated_transaction_len as u64))
}
_ => (None, None),
};
// the address needs to have a permission to deploy smart contract
if !EVMAccounts::can_deploy_contracts(from) {
return Err(pallet_evm_accounts::Error::<Runtime>::AddressNotWhitelisted.into())
};
#[allow(clippy::or_fun_call)] // suggestion not helpful here
<Runtime as pallet_evm::Config>::Runner::create(
from,
data,
value,
gas_limit.unique_saturated_into(),
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
Vec::new(),
authorization_list.clone().unwrap_or_default(),
is_transactional,
validate,
weight_limit,
proof_size_base_cost,
config
.as_ref()
.unwrap_or(<Runtime as pallet_evm::Config>::config()),
)
.map_err(|err| err.error.into())
}
fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {
pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
}
fn current_block() -> Option<pallet_ethereum::Block> {
pallet_ethereum::CurrentBlock::<Runtime>::get()
}
fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {
pallet_ethereum::CurrentReceipts::<Runtime>::get()
}
fn current_all() -> (
Option<pallet_ethereum::Block>,
Option<Vec<pallet_ethereum::Receipt>>,
Option<Vec<TransactionStatus>>,
) {
(
pallet_ethereum::CurrentBlock::<Runtime>::get(),
pallet_ethereum::CurrentReceipts::<Runtime>::get(),
pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get(),
)
}
fn extrinsic_filter(xts: Vec<<Block as BlockT>::Extrinsic>) -> Vec<EthereumTransaction> {
xts.into_iter()
.filter_map(|xt| match xt.0.function {
RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),
_ => None,
})
.collect::<Vec<EthereumTransaction>>()
}
fn elasticity() -> Option<Permill> {
None
}