1
// Copyright 2019-2022 PureStake Inc.
2
// This file is part of Moonbeam.
3

            
4
// Moonbeam is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Moonbeam is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Moonbeam.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
#[macro_export]
18
macro_rules! impl_runtime_apis_plus_common {
19
	{$($custom:tt)*} => {
20

            
21
		#[cfg(feature = "evm-tracing")]
22
		// Helper function to replay the "on_idle" hook for all pallets, we need this for
23
		// evm-tracing because some ethereum-xcm transactions might be executed at on_idle.
24
		//
25
		// We need to make sure that we replay on_idle exactly the same way as the
26
		// original block execution, but unfortunatly frame executive diosn't provide a function
27
		// to replay only on_idle, so we need to copy here some code inside frame executive.
28
22
		fn replay_on_idle() {
29
22
			use frame_system::pallet_prelude::BlockNumberFor;
30
22
			use frame_support::traits::OnIdle;
31
22

            
32
22
			let weight = <frame_system::Pallet<Runtime>>::block_weight();
33
22
			let max_weight = <
34
22
					<Runtime as frame_system::Config>::BlockWeights as
35
22
					frame_support::traits::Get<_>
36
22
				>::get().max_block;
37
22
			let remaining_weight = max_weight.saturating_sub(weight.total());
38
22
			if remaining_weight.all_gt(Weight::zero()) {
39
22
				let _ = <AllPalletsWithSystem as OnIdle<BlockNumberFor<Runtime>>>::on_idle(
40
22
					<frame_system::Pallet<Runtime>>::block_number(),
41
22
					remaining_weight,
42
22
				);
43
22
			}
44
22
		}
45
22

            
46
22
		impl_runtime_apis! {
47
			$($custom)*
48

            
49
			impl sp_api::Core<Block> for Runtime {
50
				fn version() -> RuntimeVersion {
51
					VERSION
52
				}
53

            
54
				fn execute_block(block: Block) {
55
					Executive::execute_block(block)
56
				}
57

            
58
				fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
59
					Executive::initialize_block(header)
60
				}
61
			}
62

            
63
			impl sp_api::Metadata<Block> for Runtime {
64
				fn metadata() -> OpaqueMetadata {
65
					OpaqueMetadata::new(Runtime::metadata().into())
66
				}
67

            
68
				fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
69
					Runtime::metadata_at_version(version)
70
				}
71

            
72
				fn metadata_versions() -> Vec<u32> {
73
					Runtime::metadata_versions()
74
				}
75
			}
76

            
77
			impl sp_block_builder::BlockBuilder<Block> for Runtime {
78
				fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
79
					Executive::apply_extrinsic(extrinsic)
80
				}
81

            
82
				fn finalize_block() -> <Block as BlockT>::Header {
83
					Executive::finalize_block()
84
				}
85

            
86
				fn inherent_extrinsics(
87
					data: sp_inherents::InherentData,
88
				) -> Vec<<Block as BlockT>::Extrinsic> {
89
					data.create_extrinsics()
90
				}
91

            
92
				fn check_inherents(
93
					block: Block,
94
					data: sp_inherents::InherentData,
95
				) -> sp_inherents::CheckInherentsResult {
96
					data.check_extrinsics(&block)
97
				}
98
			}
99

            
100
			impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
101
				fn offchain_worker(header: &<Block as BlockT>::Header) {
102
					Executive::offchain_worker(header)
103
				}
104
			}
105

            
106
			impl sp_session::SessionKeys<Block> for Runtime {
107
				fn decode_session_keys(
108
					encoded: Vec<u8>,
109
				) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
110
					opaque::SessionKeys::decode_into_raw_public_keys(&encoded)
111
				}
112

            
113
				fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
114
					opaque::SessionKeys::generate(seed)
115
				}
116
			}
117

            
118
			#[cfg(not(feature = "disable-genesis-builder"))]
119
			impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
120
				fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
121
					frame_support::genesis_builder_helper::build_state::<RuntimeGenesisConfig>(config)
122
				}
123

            
124
				fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
125
					frame_support::genesis_builder_helper::get_preset::<RuntimeGenesisConfig>(id, genesis_config_preset::get_preset)
126
				}
127

            
128
				fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
129
					genesis_config_preset::preset_names()
130
				}
131
			}
132

            
133
			impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
134
				fn account_nonce(account: AccountId) -> Index {
135
					System::account_nonce(account)
136
				}
137
			}
138

            
139
			impl moonbeam_rpc_primitives_debug::DebugRuntimeApi<Block> for Runtime {
140
22
				fn trace_transaction(
141
22
					extrinsics: Vec<<Block as BlockT>::Extrinsic>,
142
22
					traced_transaction: &EthereumTransaction,
143
22
					header: &<Block as BlockT>::Header,
144
22
				) -> Result<
145
22
					(),
146
22
					sp_runtime::DispatchError,
147
22
				> {
148
22
					#[cfg(feature = "evm-tracing")]
149
22
					{
150
22
						use moonbeam_evm_tracer::tracer::EvmTracer;
151
22
						use xcm_primitives::{
152
22
							ETHEREUM_XCM_TRACING_STORAGE_KEY,
153
22
							EthereumXcmTracingStatus
154
22
						};
155
22
						use frame_support::storage::unhashed;
156
22
						use frame_system::pallet_prelude::BlockNumberFor;
157
22

            
158
22
						// Tell the CallDispatcher we are tracing a specific Transaction.
159
22
						unhashed::put::<EthereumXcmTracingStatus>(
160
22
							ETHEREUM_XCM_TRACING_STORAGE_KEY,
161
22
							&EthereumXcmTracingStatus::Transaction(traced_transaction.hash()),
162
22
						);
163
22

            
164
22
						// Initialize block: calls the "on_initialize" hook on every pallet
165
22
						// in AllPalletsWithSystem.
166
22
						// After pallet message queue was introduced, this must be done only after
167
22
						// enabling XCM tracing by setting ETHEREUM_XCM_TRACING_STORAGE_KEY
168
22
						// in the storage
169
22
						Executive::initialize_block(header);
170

            
171
						// Apply the a subset of extrinsics: all the substrate-specific or ethereum
172
						// transactions that preceded the requested transaction.
173
44
						for ext in extrinsics.into_iter() {
174
22
							let _ = match &ext.0.function {
175
22
								RuntimeCall::Ethereum(transact { transaction }) => {
176
22
									if transaction == traced_transaction {
177
22
										EvmTracer::new().trace(|| Executive::apply_extrinsic(ext));
178
22
										return Ok(());
179
									} else {
180
										Executive::apply_extrinsic(ext)
181
									}
182
								}
183
22
								_ => Executive::apply_extrinsic(ext),
184
							};
185
22
							if let Some(EthereumXcmTracingStatus::TransactionExited) = unhashed::get(
186
22
								ETHEREUM_XCM_TRACING_STORAGE_KEY
187
22
							) {
188
								return Ok(());
189
							}
190
						}
191

            
192
						if let Some(EthereumXcmTracingStatus::Transaction(_)) = unhashed::get(
193
							ETHEREUM_XCM_TRACING_STORAGE_KEY
194
						) {
195
							// If the transaction was not found, it might be
196
							// an eth-xcm transaction that was executed at on_idle
197
							replay_on_idle();
198
						}
199

            
200
						if let Some(EthereumXcmTracingStatus::TransactionExited) = unhashed::get(
201
							ETHEREUM_XCM_TRACING_STORAGE_KEY
202
						) {
203
							// The transaction was found
204
							Ok(())
205
						} else {
206
							// The transaction was not-found
207
							Err(sp_runtime::DispatchError::Other(
208
								"Failed to find Ethereum transaction among the extrinsics.",
209
							))
210
						}
211
					}
212
					#[cfg(not(feature = "evm-tracing"))]
213
					Err(sp_runtime::DispatchError::Other(
214
						"Missing `evm-tracing` compile time feature flag.",
215
					))
216
				}
217

            
218
22
				fn trace_block(
219
22
					extrinsics: Vec<<Block as BlockT>::Extrinsic>,
220
22
					known_transactions: Vec<H256>,
221
22
					header: &<Block as BlockT>::Header,
222
22
				) -> Result<
223
22
					(),
224
22
					sp_runtime::DispatchError,
225
22
				> {
226
22
					#[cfg(feature = "evm-tracing")]
227
22
					{
228
22
						use moonbeam_evm_tracer::tracer::EvmTracer;
229
22
						use frame_system::pallet_prelude::BlockNumberFor;
230
22
						use xcm_primitives::EthereumXcmTracingStatus;
231
22

            
232
22
						// Tell the CallDispatcher we are tracing a full Block.
233
22
						frame_support::storage::unhashed::put::<EthereumXcmTracingStatus>(
234
22
							xcm_primitives::ETHEREUM_XCM_TRACING_STORAGE_KEY,
235
22
							&EthereumXcmTracingStatus::Block,
236
22
						);
237
22

            
238
22
						let mut config = <Runtime as pallet_evm::Config>::config().clone();
239
22
						config.estimate = true;
240
22

            
241
22
						// Initialize block: calls the "on_initialize" hook on every pallet
242
22
						// in AllPalletsWithSystem.
243
22
						// After pallet message queue was introduced, this must be done only after
244
22
						// enabling XCM tracing by setting ETHEREUM_XCM_TRACING_STORAGE_KEY
245
22
						// in the storage
246
22
						Executive::initialize_block(header);
247

            
248
						// Apply all extrinsics. Ethereum extrinsics are traced.
249
88
						for ext in extrinsics.into_iter() {
250
44
							match &ext.0.function {
251
44
								RuntimeCall::Ethereum(transact { transaction }) => {
252
44
									if known_transactions.contains(&transaction.hash()) {
253
44
										// Each known extrinsic is a new call stack.
254
44
										EvmTracer::emit_new();
255
44
										EvmTracer::new().trace(|| Executive::apply_extrinsic(ext));
256
44
									} else {
257
										let _ = Executive::apply_extrinsic(ext);
258
									}
259
								}
260
44
								_ => {
261
44
									let _ = Executive::apply_extrinsic(ext);
262
44
								}
263
							};
264
						}
265

            
266
						// Replay on_idle
267
						// Some XCM messages with eth-xcm transaction might be executed at on_idle
268
22
						replay_on_idle();
269
22

            
270
22
						Ok(())
271
22
					}
272
22
					#[cfg(not(feature = "evm-tracing"))]
273
22
					Err(sp_runtime::DispatchError::Other(
274
22
						"Missing `evm-tracing` compile time feature flag.",
275
22
					))
276
22
				}
277

            
278
22
				fn trace_call(
279
22
					header: &<Block as BlockT>::Header,
280
22
					from: H160,
281
22
					to: H160,
282
22
					data: Vec<u8>,
283
22
					value: U256,
284
22
					gas_limit: U256,
285
22
					max_fee_per_gas: Option<U256>,
286
22
					max_priority_fee_per_gas: Option<U256>,
287
22
					nonce: Option<U256>,
288
22
					access_list: Option<Vec<(H160, Vec<H256>)>>,
289
22
				) -> Result<(), sp_runtime::DispatchError> {
290
22
					#[cfg(feature = "evm-tracing")]
291
22
					{
292
22
						use moonbeam_evm_tracer::tracer::EvmTracer;
293
22

            
294
22
						// Initialize block: calls the "on_initialize" hook on every pallet
295
22
						// in AllPalletsWithSystem.
296
22
						Executive::initialize_block(header);
297
22

            
298
22
						EvmTracer::new().trace(|| {
299
							let is_transactional = false;
300
							let validate = true;
301
							let without_base_extrinsic_weight = true;
302

            
303

            
304
							// Estimated encoded transaction size must be based on the heaviest transaction
305
							// type (EIP1559Transaction) to be compatible with all transaction types.
306
							let mut estimated_transaction_len = data.len() +
307
							// pallet ethereum index: 1
308
							// transact call index: 1
309
							// Transaction enum variant: 1
310
							// chain_id 8 bytes
311
							// nonce: 32
312
							// max_priority_fee_per_gas: 32
313
							// max_fee_per_gas: 32
314
							// gas_limit: 32
315
							// action: 21 (enum varianrt + call address)
316
							// value: 32
317
							// access_list: 1 (empty vec size)
318
							// 65 bytes signature
319
							258;
320

            
321
							if access_list.is_some() {
322
								estimated_transaction_len += access_list.encoded_size();
323
							}
324

            
325
							let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
326

            
327
							let (weight_limit, proof_size_base_cost) =
328
								match <Runtime as pallet_evm::Config>::GasWeightMapping::gas_to_weight(
329
									gas_limit,
330
									without_base_extrinsic_weight
331
								) {
332
									weight_limit if weight_limit.proof_size() > 0 => {
333
										(Some(weight_limit), Some(estimated_transaction_len as u64))
334
									}
335
									_ => (None, None),
336
								};
337

            
338
							let _ = <Runtime as pallet_evm::Config>::Runner::call(
339
								from,
340
								to,
341
								data,
342
								value,
343
								gas_limit,
344
								max_fee_per_gas,
345
								max_priority_fee_per_gas,
346
								nonce,
347
								access_list.unwrap_or_default(),
348
								is_transactional,
349
								validate,
350
								weight_limit,
351
								proof_size_base_cost,
352
								<Runtime as pallet_evm::Config>::config(),
353
							);
354
22
						});
355
22
						Ok(())
356
22
					}
357
22
					#[cfg(not(feature = "evm-tracing"))]
358
22
					Err(sp_runtime::DispatchError::Other(
359
22
						"Missing `evm-tracing` compile time feature flag.",
360
22
					))
361
22
				}
362
			}
363

            
364
			impl moonbeam_rpc_primitives_txpool::TxPoolRuntimeApi<Block> for Runtime {
365
22
				fn extrinsic_filter(
366
22
					xts_ready: Vec<<Block as BlockT>::Extrinsic>,
367
22
					xts_future: Vec<<Block as BlockT>::Extrinsic>,
368
22
				) -> TxPoolResponse {
369
22
					TxPoolResponse {
370
22
						ready: xts_ready
371
22
							.into_iter()
372
22
							.filter_map(|xt| match xt.0.function {
373
								RuntimeCall::Ethereum(transact { transaction }) => Some(transaction),
374
								_ => None,
375
22
							})
376
22
							.collect(),
377
22
						future: xts_future
378
22
							.into_iter()
379
22
							.filter_map(|xt| match xt.0.function {
380
								RuntimeCall::Ethereum(transact { transaction }) => Some(transaction),
381
								_ => None,
382
22
							})
383
22
							.collect(),
384
22
					}
385
22
				}
386
			}
387

            
388
			impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {
389
22
				fn chain_id() -> u64 {
390
22
					<Runtime as pallet_evm::Config>::ChainId::get()
391
22
				}
392

            
393
22
				fn account_basic(address: H160) -> EVMAccount {
394
22
					let (account, _) = EVM::account_basic(&address);
395
22
					account
396
22
				}
397

            
398
22
				fn gas_price() -> U256 {
399
22
					let (gas_price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();
400
22
					gas_price
401
22
				}
402

            
403
22
				fn account_code_at(address: H160) -> Vec<u8> {
404
22
					pallet_evm::AccountCodes::<Runtime>::get(address)
405
22
				}
406

            
407
22
				fn author() -> H160 {
408
22
					<pallet_evm::Pallet<Runtime>>::find_author()
409
22
				}
410

            
411
22
				fn storage_at(address: H160, index: U256) -> H256 {
412
22
					let mut tmp = [0u8; 32];
413
22
					index.to_big_endian(&mut tmp);
414
22
					pallet_evm::AccountStorages::<Runtime>::get(address, H256::from_slice(&tmp[..]))
415
22
				}
416

            
417
22
				fn call(
418
22
					from: H160,
419
22
					to: H160,
420
22
					data: Vec<u8>,
421
22
					value: U256,
422
22
					gas_limit: U256,
423
22
					max_fee_per_gas: Option<U256>,
424
22
					max_priority_fee_per_gas: Option<U256>,
425
22
					nonce: Option<U256>,
426
22
					estimate: bool,
427
22
					access_list: Option<Vec<(H160, Vec<H256>)>>,
428
22
				) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {
429
22
					let config = if estimate {
430
						let mut config = <Runtime as pallet_evm::Config>::config().clone();
431
						config.estimate = true;
432
						Some(config)
433
					} else {
434
22
						None
435
					};
436
22
					let is_transactional = false;
437
22
					let validate = true;
438
22

            
439
22
					// Estimated encoded transaction size must be based on the heaviest transaction
440
22
					// type (EIP1559Transaction) to be compatible with all transaction types.
441
22
					let mut estimated_transaction_len = data.len() +
442
22
						// pallet ethereum index: 1
443
22
						// transact call index: 1
444
22
						// Transaction enum variant: 1
445
22
						// chain_id 8 bytes
446
22
						// nonce: 32
447
22
						// max_priority_fee_per_gas: 32
448
22
						// max_fee_per_gas: 32
449
22
						// gas_limit: 32
450
22
						// action: 21 (enum varianrt + call address)
451
22
						// value: 32
452
22
						// access_list: 1 (empty vec size)
453
22
						// 65 bytes signature
454
22
						258;
455
22

            
456
22
					if access_list.is_some() {
457
						estimated_transaction_len += access_list.encoded_size();
458
					}
459

            
460
22
					let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
461
22
					let without_base_extrinsic_weight = true;
462

            
463
22
					let (weight_limit, proof_size_base_cost) =
464
22
						match <Runtime as pallet_evm::Config>::GasWeightMapping::gas_to_weight(
465
22
							gas_limit,
466
22
							without_base_extrinsic_weight
467
22
						) {
468
22
							weight_limit if weight_limit.proof_size() > 0 => {
469
22
								(Some(weight_limit), Some(estimated_transaction_len as u64))
470
							}
471
							_ => (None, None),
472
						};
473

            
474
22
					<Runtime as pallet_evm::Config>::Runner::call(
475
22
						from,
476
22
						to,
477
22
						data,
478
22
						value,
479
22
						gas_limit,
480
22
						max_fee_per_gas,
481
22
						max_priority_fee_per_gas,
482
22
						nonce,
483
22
						access_list.unwrap_or_default(),
484
22
						is_transactional,
485
22
						validate,
486
22
						weight_limit,
487
22
						proof_size_base_cost,
488
22
						config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),
489
22
					).map_err(|err| err.error.into())
490
22
				}
491

            
492
22
				fn create(
493
22
					from: H160,
494
22
					data: Vec<u8>,
495
22
					value: U256,
496
22
					gas_limit: U256,
497
22
					max_fee_per_gas: Option<U256>,
498
22
					max_priority_fee_per_gas: Option<U256>,
499
22
					nonce: Option<U256>,
500
22
					estimate: bool,
501
22
					access_list: Option<Vec<(H160, Vec<H256>)>>,
502
22
				) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {
503
22
					let config = if estimate {
504
						let mut config = <Runtime as pallet_evm::Config>::config().clone();
505
						config.estimate = true;
506
						Some(config)
507
					} else {
508
22
						None
509
					};
510
22
					let is_transactional = false;
511
22
					let validate = true;
512
22

            
513
22
					let mut estimated_transaction_len = data.len() +
514
22
						// from: 20
515
22
						// value: 32
516
22
						// gas_limit: 32
517
22
						// nonce: 32
518
22
						// 1 byte transaction action variant
519
22
						// chain id 8 bytes
520
22
						// 65 bytes signature
521
22
						190;
522
22

            
523
22
					if max_fee_per_gas.is_some() {
524
						estimated_transaction_len += 32;
525
					}
526
22
					if max_priority_fee_per_gas.is_some() {
527
						estimated_transaction_len += 32;
528
					}
529
22
					if access_list.is_some() {
530
						estimated_transaction_len += access_list.encoded_size();
531
					}
532

            
533
22
					let gas_limit = if gas_limit > U256::from(u64::MAX) {
534
						u64::MAX
535
					} else {
536
22
						gas_limit.low_u64()
537
					};
538
22
					let without_base_extrinsic_weight = true;
539

            
540
22
					let (weight_limit, proof_size_base_cost) =
541
22
						match <Runtime as pallet_evm::Config>::GasWeightMapping::gas_to_weight(
542
22
							gas_limit,
543
22
							without_base_extrinsic_weight
544
22
						) {
545
22
							weight_limit if weight_limit.proof_size() > 0 => {
546
22
								(Some(weight_limit), Some(estimated_transaction_len as u64))
547
							}
548
							_ => (None, None),
549
						};
550

            
551
					#[allow(clippy::or_fun_call)] // suggestion not helpful here
552
22
					<Runtime as pallet_evm::Config>::Runner::create(
553
22
						from,
554
22
						data,
555
22
						value,
556
22
						gas_limit,
557
22
						max_fee_per_gas,
558
22
						max_priority_fee_per_gas,
559
22
						nonce,
560
22
						access_list.unwrap_or_default(),
561
22
						is_transactional,
562
22
						validate,
563
22
						weight_limit,
564
22
						proof_size_base_cost,
565
22
						config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),
566
22
					).map_err(|err| err.error.into())
567
22
				}
568

            
569
22
				fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {
570
22
					pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
571
22
				}
572

            
573
22
				fn current_block() -> Option<pallet_ethereum::Block> {
574
22
					pallet_ethereum::CurrentBlock::<Runtime>::get()
575
22
				}
576

            
577
22
				fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {
578
22
					pallet_ethereum::CurrentReceipts::<Runtime>::get()
579
22
				}
580

            
581
				fn current_all() -> (
582
					Option<pallet_ethereum::Block>,
583
					Option<Vec<pallet_ethereum::Receipt>>,
584
					Option<Vec<TransactionStatus>>,
585
				) {
586
					(
587
						pallet_ethereum::CurrentBlock::<Runtime>::get(),
588
						pallet_ethereum::CurrentReceipts::<Runtime>::get(),
589
						pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get(),
590
					)
591
				}
592

            
593
				fn extrinsic_filter(
594
					xts: Vec<<Block as BlockT>::Extrinsic>,
595
				) -> Vec<EthereumTransaction> {
596
					xts.into_iter().filter_map(|xt| match xt.0.function {
597
						RuntimeCall::Ethereum(transact { transaction }) => Some(transaction),
598
						_ => None
599
					}).collect::<Vec<EthereumTransaction>>()
600
				}
601

            
602
				fn elasticity() -> Option<Permill> {
603
					None
604
				}
605

            
606
				fn gas_limit_multiplier_support() {}
607

            
608
				fn pending_block(
609
					xts: Vec<<Block as sp_runtime::traits::Block>::Extrinsic>
610
				) -> (
611
					Option<pallet_ethereum::Block>, Option<sp_std::prelude::Vec<TransactionStatus>>
612
				) {
613
					for ext in xts.into_iter() {
614
						let _ = Executive::apply_extrinsic(ext);
615
					}
616

            
617
					Ethereum::on_finalize(System::block_number() + 1);
618

            
619
					(
620
						pallet_ethereum::CurrentBlock::<Runtime>::get(),
621
						pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
622
					)
623
				 }
624

            
625
				fn initialize_pending_block(header: &<Block as BlockT>::Header) {
626
					pallet_randomness::vrf::using_fake_vrf(|| {
627
						let _ = Executive::initialize_block(header);
628
					})
629
				}
630
			}
631

            
632
			impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {
633
				fn convert_transaction(
634
					transaction: pallet_ethereum::Transaction
635
				) -> <Block as BlockT>::Extrinsic {
636
					UncheckedExtrinsic::new_unsigned(
637
						pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
638
					)
639
				}
640
			}
641

            
642
			impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
643
			for Runtime {
644
				fn query_info(
645
					uxt: <Block as BlockT>::Extrinsic,
646
					len: u32,
647
				) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
648
					TransactionPayment::query_info(uxt, len)
649
				}
650

            
651
				fn query_fee_details(
652
					uxt: <Block as BlockT>::Extrinsic,
653
					len: u32,
654
				) -> pallet_transaction_payment::FeeDetails<Balance> {
655
					TransactionPayment::query_fee_details(uxt, len)
656
				}
657

            
658
				fn query_weight_to_fee(weight: Weight) -> Balance {
659
					TransactionPayment::weight_to_fee(weight)
660
				}
661

            
662
				fn query_length_to_fee(length: u32) -> Balance {
663
					TransactionPayment::length_to_fee(length)
664
				}
665
			}
666

            
667
			impl nimbus_primitives::NimbusApi<Block> for Runtime {
668
66
				fn can_author(
669
66
					author: nimbus_primitives::NimbusId,
670
66
					slot: u32,
671
66
					parent_header: &<Block as BlockT>::Header
672
66
				) -> bool {
673
66
					use pallet_parachain_staking::Config as PalletParachainStakingConfig;
674
66

            
675
66
					let block_number = parent_header.number + 1;
676
66

            
677
66
					// The Moonbeam runtimes use an entropy source that needs to do some accounting
678
66
					// work during block initialization. Therefore we initialize it here to match
679
66
					// the state it will be in when the next block is being executed.
680
66
					use frame_support::traits::OnInitialize;
681
66
					System::initialize(
682
66
						&block_number,
683
66
						&parent_header.hash(),
684
66
						&parent_header.digest,
685
66
					);
686
66

            
687
66
					// Because the staking solution calculates the next staking set at the beginning
688
66
					// of the first block in the new round, the only way to accurately predict the
689
66
					// authors is to compute the selection during prediction.
690
66
					if pallet_parachain_staking::Pallet::<Self>::round()
691
66
						.should_update(block_number) {
692
						// get author account id
693
						use nimbus_primitives::AccountLookup;
694
						let author_account_id = if let Some(account) =
695
							pallet_author_mapping::Pallet::<Self>::lookup_account(&author) {
696
							account
697
						} else {
698
							// return false if author mapping not registered like in can_author impl
699
							return false
700
						};
701
						let candidates = pallet_parachain_staking::Pallet::<Self>::compute_top_candidates();
702
						if candidates.is_empty() {
703
							// If there are zero selected candidates, we use the same eligibility
704
							// as the previous round
705
							return AuthorInherent::can_author(&author, &slot);
706
						}
707

            
708
						// predict eligibility post-selection by computing selection results now
709
						let (eligible, _) =
710
							pallet_author_slot_filter::compute_pseudo_random_subset::<Self>(
711
								candidates,
712
								&slot
713
							);
714
						eligible.contains(&author_account_id)
715
					} else {
716
66
						AuthorInherent::can_author(&author, &slot)
717
					}
718
				}
719
			}
720

            
721
			impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
722
				fn collect_collation_info(
723
					header: &<Block as BlockT>::Header
724
				) -> cumulus_primitives_core::CollationInfo {
725
					ParachainSystem::collect_collation_info(header)
726
				}
727
			}
728

            
729
			impl session_keys_primitives::VrfApi<Block> for Runtime {
730
				fn get_last_vrf_output() -> Option<<Block as BlockT>::Hash> {
731
					// TODO: remove in future runtime upgrade along with storage item
732
					if pallet_randomness::Pallet::<Self>::not_first_block().is_none() {
733
						return None;
734
					}
735
					pallet_randomness::Pallet::<Self>::local_vrf_output()
736
				}
737
				fn vrf_key_lookup(
738
					nimbus_id: nimbus_primitives::NimbusId
739
				) -> Option<session_keys_primitives::VrfId> {
740
					use session_keys_primitives::KeysLookup;
741
					AuthorMapping::lookup_keys(&nimbus_id)
742
				}
743
			}
744

            
745
			impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
746
				fn query_acceptable_payment_assets(
747
					xcm_version: xcm::Version
748
				) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
749
					XcmWeightTrader::query_acceptable_payment_assets(xcm_version)
750
				}
751

            
752
				fn query_weight_to_asset_fee(
753
					weight: Weight, asset: VersionedAssetId
754
				) -> Result<u128, XcmPaymentApiError> {
755
					XcmWeightTrader::query_weight_to_asset_fee(weight, asset)
756
				}
757

            
758
				fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
759
					PolkadotXcm::query_xcm_weight(message)
760
				}
761

            
762
				fn query_delivery_fees(
763
					destination: VersionedLocation, message: VersionedXcm<()>
764
				) -> Result<VersionedAssets, XcmPaymentApiError> {
765
					PolkadotXcm::query_delivery_fees(destination, message)
766
				}
767
			}
768

            
769
			impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller>
770
				for Runtime {
771
					fn dry_run_call(
772
						origin: OriginCaller,
773
						call: RuntimeCall
774
					) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
775
						PolkadotXcm::dry_run_call::<
776
							Runtime,
777
							xcm_config::XcmRouter,
778
							OriginCaller,
779
							RuntimeCall>(origin, call)
780
					}
781

            
782
					fn dry_run_xcm(
783
						origin_location: VersionedLocation,
784
						xcm: VersionedXcm<RuntimeCall>
785
					) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
786
						PolkadotXcm::dry_run_xcm::<
787
							Runtime,
788
							xcm_config::XcmRouter,
789
							RuntimeCall,
790
							xcm_config::XcmExecutorConfig>(origin_location, xcm)
791
					}
792
				}
793

            
794
			impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
795
				fn convert_location(location: VersionedLocation) -> Result<
796
					AccountId,
797
					xcm_runtime_apis::conversions::Error
798
				> {
799
					xcm_runtime_apis::conversions::LocationToAccountHelper::<
800
						AccountId,
801
						xcm_config::LocationToAccountId,
802
					>::convert_location(location)
803
				}
804
			}
805

            
806
			#[cfg(feature = "runtime-benchmarks")]
807
			impl frame_benchmarking::Benchmark<Block> for Runtime {
808

            
809
				fn benchmark_metadata(extra: bool) -> (
810
					Vec<frame_benchmarking::BenchmarkList>,
811
					Vec<frame_support::traits::StorageInfo>,
812
				) {
813
					use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};
814
					use moonbeam_xcm_benchmarks::generic::benchmarking as MoonbeamXcmBenchmarks;
815
					use frame_support::traits::StorageInfoTrait;
816
					use MoonbeamXcmBenchmarks::XcmGenericBenchmarks as MoonbeamXcmGenericBench;
817

            
818
					use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
819

            
820
					let mut list = Vec::<BenchmarkList>::new();
821
					list_benchmarks!(list, extra);
822

            
823
					let storage_info = AllPalletsWithSystem::storage_info();
824

            
825
					return (list, storage_info)
826
				}
827

            
828
				fn dispatch_benchmark(
829
					config: frame_benchmarking::BenchmarkConfig,
830
				) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
831
					use frame_benchmarking::{add_benchmark, BenchmarkBatch, Benchmarking};
832
					use frame_support::traits::TrackedStorageKey;
833
					use cumulus_primitives_core::ParaId;
834

            
835
					use xcm::latest::prelude::{
836
						GeneralIndex, Junction, Junctions, Location, Response, NetworkId, AssetId,
837
						Assets as XcmAssets, Fungible, Asset, ParentThen, Parachain, Parent
838
					};
839
					use xcm_config::SelfReserve;
840
					use frame_benchmarking::BenchmarkError;
841

            
842
					use frame_system_benchmarking::Pallet as SystemBench;
843
					impl frame_system_benchmarking::Config for Runtime {}
844

            
845
					impl moonbeam_xcm_benchmarks::Config for Runtime {}
846
					impl moonbeam_xcm_benchmarks::generic::Config for Runtime {}
847

            
848
					use pallet_asset_manager::Config as PalletAssetManagerConfig;
849

            
850
					use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
851
					parameter_types! {
852
						pub const RandomParaId: ParaId = ParaId::new(43211234);
853
					}
854

            
855
					pub struct TestDeliveryHelper;
856
					impl xcm_builder::EnsureDelivery for TestDeliveryHelper {
857
						fn ensure_successful_delivery(
858
							origin_ref: &Location,
859
							_dest: &Location,
860
							_fee_reason: xcm_executor::traits::FeeReason,
861
						) -> (Option<xcm_executor::FeesMode>, Option<XcmAssets>) {
862
							use xcm_executor::traits::ConvertLocation;
863
							let account = xcm_config::LocationToH160::convert_location(origin_ref)
864
								.expect("Invalid location");
865
							// Give the existential deposit at least
866
							let balance = ExistentialDeposit::get();
867
							let _ = <Balances as frame_support::traits::Currency<_>>::
868
								make_free_balance_be(&account.into(), balance);
869

            
870
							(None, None)
871
						}
872
					}
873

            
874
					impl pallet_xcm::benchmarking::Config for Runtime {
875
				        type DeliveryHelper = TestDeliveryHelper;
876

            
877
						fn get_asset() -> Asset {
878
							Asset {
879
								id: AssetId(SelfReserve::get()),
880
								fun: Fungible(ExistentialDeposit::get()),
881
							}
882
						}
883

            
884
						fn reachable_dest() -> Option<Location> {
885
							Some(Parent.into())
886
						}
887

            
888
						fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
889
							None
890
						}
891

            
892
						fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
893
							use xcm_config::SelfReserve;
894

            
895
							ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
896
								RandomParaId::get().into()
897
							);
898

            
899
							Some((
900
								Asset {
901
									fun: Fungible(ExistentialDeposit::get()),
902
									id: AssetId(SelfReserve::get().into())
903
								},
904
								// Moonbeam can reserve transfer native token to
905
								// some random parachain.
906
								ParentThen(Parachain(RandomParaId::get().into()).into()).into(),
907
							))
908
						}
909

            
910
						fn set_up_complex_asset_transfer(
911
						) -> Option<(XcmAssets, u32, Location, Box<dyn FnOnce()>)> {
912
							use xcm_config::SelfReserve;
913

            
914
							let destination: xcm::v4::Location = Parent.into();
915

            
916
							let fee_amount: u128 = <Runtime as pallet_balances::Config>::ExistentialDeposit::get();
917
							let fee_asset: Asset = (SelfReserve::get(), fee_amount).into();
918

            
919
							// Give some multiple of transferred amount
920
							let balance = fee_amount * 1000;
921
							let who = frame_benchmarking::whitelisted_caller();
922
							let _ =
923
								<Balances as frame_support::traits::Currency<_>>::make_free_balance_be(&who, balance);
924

            
925
							// verify initial balance
926
							assert_eq!(Balances::free_balance(&who), balance);
927

            
928
							// set up local asset
929
							let asset_amount: u128 = 10u128;
930
							let initial_asset_amount: u128 = asset_amount * 10;
931

            
932
							let (asset_id, _, _) = pallet_assets::benchmarking::create_default_minted_asset::<
933
								Runtime,
934
								()
935
							>(true, initial_asset_amount);
936
							let transfer_asset: Asset = (SelfReserve::get(), asset_amount).into();
937

            
938
							let assets: XcmAssets = vec![fee_asset.clone(), transfer_asset].into();
939
							let fee_index: u32 = 0;
940

            
941
							let verify: Box<dyn FnOnce()> = Box::new(move || {
942
								// verify balance after transfer, decreased by
943
								// transferred amount (and delivery fees)
944
								assert!(Balances::free_balance(&who) <= balance - fee_amount);
945
							});
946

            
947
							Some((assets, fee_index, destination, verify))
948
						}
949
					}
950

            
951
					impl pallet_xcm_benchmarks::Config for Runtime {
952
						type XcmConfig = xcm_config::XcmExecutorConfig;
953
						type AccountIdConverter = xcm_config::LocationToAccountId;
954
						type DeliveryHelper = ();
955
						fn valid_destination() -> Result<Location, BenchmarkError> {
956
							Ok(Location::parent())
957
						}
958
						fn worst_case_holding(_depositable_count: u32) -> XcmAssets {
959
						// 100 fungibles
960
							const HOLDING_FUNGIBLES: u32 = 100;
961
							let fungibles_amount: u128 = 100;
962
							let assets = (0..HOLDING_FUNGIBLES).map(|i| {
963
								let location: Location = GeneralIndex(i as u128).into();
964
								Asset {
965
									id: AssetId(location),
966
									fun: Fungible(fungibles_amount * i as u128),
967
								}
968
								.into()
969
							})
970
							.chain(
971
								core::iter::once(
972
									Asset {
973
										id: AssetId(Location::parent()),
974
										fun: Fungible(u128::MAX)
975
									}
976
								)
977
							)
978
							.collect::<Vec<_>>();
979

            
980

            
981
							for (i, asset) in assets.iter().enumerate() {
982
								if let Asset {
983
									id: AssetId(location),
984
									fun: Fungible(_)
985
								} = asset {
986
									EvmForeignAssets::set_asset(
987
										location.clone(),
988
										i as u128
989
									);
990
									XcmWeightTrader::set_asset_price(
991
										location.clone(),
992
										1u128.pow(18)
993
									);
994
								}
995
							}
996
							assets.into()
997
						}
998
					}
999

            
					impl pallet_xcm_benchmarks::generic::Config for Runtime {
						type RuntimeCall = RuntimeCall;
						type TransactAsset = Balances;
						fn worst_case_response() -> (u64, Response) {
							(0u64, Response::Version(Default::default()))
						}
						fn worst_case_asset_exchange()
							-> Result<(XcmAssets, XcmAssets), BenchmarkError> {
							Err(BenchmarkError::Skip)
						}
						fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
							Err(BenchmarkError::Skip)
						}
						fn export_message_origin_and_destination()
							-> Result<(Location, NetworkId, Junctions), BenchmarkError> {
							Err(BenchmarkError::Skip)
						}
						fn transact_origin_and_runtime_call()
							-> Result<(Location, RuntimeCall), BenchmarkError> {
							Ok((Location::parent(), frame_system::Call::remark_with_event {
								remark: vec![]
							}.into()))
						}
						fn subscribe_origin() -> Result<Location, BenchmarkError> {
							Ok(Location::parent())
						}
						fn claimable_asset()
							-> Result<(Location, Location, XcmAssets), BenchmarkError> {
							let origin = Location::parent();
							let assets: XcmAssets = (AssetId(Location::parent()), 1_000u128)
								.into();
							let ticket = Location { parents: 0, interior: [].into() /* Here */ };
							Ok((origin, ticket, assets))
						}
						fn fee_asset() -> Result<Asset, BenchmarkError> {
							Err(BenchmarkError::Skip)
						}
						fn unlockable_asset()
							-> Result<(Location, Location, Asset), BenchmarkError> {
							Err(BenchmarkError::Skip)
						}
						fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
							Err(BenchmarkError::Skip)
						}
					}
					let whitelist: Vec<TrackedStorageKey> = vec![
						// Block Number
						hex_literal::hex!(  "26aa394eea5630e07c48ae0c9558cef7"
											"02a5c1b19ab7a04f536c519aca4983ac")
							.to_vec().into(),
						// Total Issuance
						hex_literal::hex!(  "c2261276cc9d1f8598ea4b6a74b15c2f"
											"57c875e4cff74148e4628f264b974c80")
							.to_vec().into(),
						// Execution Phase
						hex_literal::hex!(  "26aa394eea5630e07c48ae0c9558cef7"
											"ff553b5a9862a516939d82b3d3d8661a")
							.to_vec().into(),
						// Event Count
						hex_literal::hex!(  "26aa394eea5630e07c48ae0c9558cef7"
											"0a98fdbe9ce6c55837576c60c7af3850")
							.to_vec().into(),
						// System Events
						hex_literal::hex!(  "26aa394eea5630e07c48ae0c9558cef7"
											"80d41e5e16056765bc8461851072c9d7")
							.to_vec().into(),
						// System BlockWeight
						hex_literal::hex!(  "26aa394eea5630e07c48ae0c9558cef7"
											"34abf5cb34d6244378cddbf18e849d96")
							.to_vec().into(),
						// ParachainStaking Round
						hex_literal::hex!(  "a686a3043d0adcf2fa655e57bc595a78"
											"13792e785168f725b60e2969c7fc2552")
							.to_vec().into(),
						// Treasury Account (py/trsry)
						hex_literal::hex!(  "26aa394eea5630e07c48ae0c9558cef7"
											"b99d880ec681799c0cf30e8886371da9"
											"7be2919ac397ba499ea5e57132180ec6"
											"6d6f646c70792f747273727900000000"
											"00000000"
						).to_vec().into(),
						// Treasury Account (pc/trsry)
						hex_literal::hex!(  "26aa394eea5630e07c48ae0c9558cef7"
											"b99d880ec681799c0cf30e8886371da9"
											"7be2919ac397ba499ea5e57132180ec6"
											"6d6f646c70632f747273727900000000"
											"00000000"
						).to_vec().into(),
						// ParachainInfo ParachainId
						hex_literal::hex!(  "0d715f2646c8f85767b5d2764bb27826"
											"04a74d81251e398fd8a0a4d55023bb3f")
							.to_vec().into(),
						// Parameters Parameters
						hex_literal::hex!(  "c63bdd4a39095ccf55623a6f2872bf8a" // Pallet: "Parameters"
											"c63bdd4a39095ccf55623a6f2872bf8a" // Storage Prefix: "Parameters"
											// MoonbaseRuntimeRuntimeParamsRuntimeParametersKey(FeesTreasuryProportion)
											"71d0aacb690b61280d0c97c6b6a666640000"
										)
							.to_vec().into(),
					];
					let mut batches = Vec::<BenchmarkBatch>::new();
					let params = (&config, &whitelist);
					add_benchmarks!(params, batches);
					if batches.is_empty() {
						return Err("Benchmark not found for this pallet.".into());
					}
					Ok(batches)
				}
			}
			#[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()");
					// NOTE: intentional expect: we don't want to propagate the error backwards,
					// and want to have a backtrace here. If any of the pre/post migration checks
					// fail, we shall stop right here and right now.
					let weight = Executive::try_runtime_upgrade(checks)
						.expect("runtime upgrade logic *must* be infallible");
					(weight, RuntimeBlockWeights::get().max_block)
				}
				fn execute_block(
					block: Block,
					state_root_check: bool,
					signature_check: bool,
					select: frame_try_runtime::TryStateSelect
				) -> Weight {
					log::info!(
						"try-runtime: executing block {:?} / root checks: {:?} / try-state-select: {:?}",
						block.header.hash(),
						state_root_check,
						select,
					);
					// NOTE: intentional unwrap: we don't want to propagate the error backwards,
					// and want to have a backtrace here.
					Executive::try_execute_block(
						block,
						state_root_check,
						signature_check,
						select,
					).expect("execute-block failed")
				}
			}
		}
	};
}