1
// Copyright 2019-2025 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

            
177
22
									// Reset the previously consumed weight when tracing ethereum transactions.
178
22
									// This is necessary because EVM tracing introduces additional
179
22
									// (ref_time) overhead, which differs from the production runtime behavior.
180
22
									// Without resetting the block weight, the extra tracing overhead could
181
22
									// leading to some transactions to incorrectly fail during tracing.
182
22
									frame_system::BlockWeight::<Runtime>::kill();
183
22

            
184
22
									if transaction == traced_transaction {
185
22
										EvmTracer::new().trace(|| Executive::apply_extrinsic(ext));
186
22
										return Ok(());
187
									} else {
188
										Executive::apply_extrinsic(ext)
189
									}
190
								}
191
22
								_ => Executive::apply_extrinsic(ext),
192
							};
193
22
							if let Some(EthereumXcmTracingStatus::TransactionExited) = unhashed::get(
194
22
								ETHEREUM_XCM_TRACING_STORAGE_KEY
195
22
							) {
196
								return Ok(());
197
							}
198
						}
199

            
200
						if let Some(EthereumXcmTracingStatus::Transaction(_)) = unhashed::get(
201
							ETHEREUM_XCM_TRACING_STORAGE_KEY
202
						) {
203
							// If the transaction was not found, it might be
204
							// an eth-xcm transaction that was executed at on_idle
205
							replay_on_idle();
206
						}
207

            
208
						if let Some(EthereumXcmTracingStatus::TransactionExited) = unhashed::get(
209
							ETHEREUM_XCM_TRACING_STORAGE_KEY
210
						) {
211
							// The transaction was found
212
							Ok(())
213
						} else {
214
							// The transaction was not-found
215
							Err(sp_runtime::DispatchError::Other(
216
								"Failed to find Ethereum transaction among the extrinsics.",
217
							))
218
						}
219
					}
220
					#[cfg(not(feature = "evm-tracing"))]
221
					Err(sp_runtime::DispatchError::Other(
222
						"Missing `evm-tracing` compile time feature flag.",
223
					))
224
				}
225

            
226
22
				fn trace_block(
227
22
					extrinsics: Vec<<Block as BlockT>::Extrinsic>,
228
22
					known_transactions: Vec<H256>,
229
22
					header: &<Block as BlockT>::Header,
230
22
				) -> Result<
231
22
					(),
232
22
					sp_runtime::DispatchError,
233
22
				> {
234
22
					#[cfg(feature = "evm-tracing")]
235
22
					{
236
22
						use moonbeam_evm_tracer::tracer::EvmTracer;
237
22
						use frame_system::pallet_prelude::BlockNumberFor;
238
22
						use xcm_primitives::EthereumXcmTracingStatus;
239
22

            
240
22
						// Tell the CallDispatcher we are tracing a full Block.
241
22
						frame_support::storage::unhashed::put::<EthereumXcmTracingStatus>(
242
22
							xcm_primitives::ETHEREUM_XCM_TRACING_STORAGE_KEY,
243
22
							&EthereumXcmTracingStatus::Block,
244
22
						);
245
22

            
246
22
						let mut config = <Runtime as pallet_evm::Config>::config().clone();
247
22
						config.estimate = true;
248
22

            
249
22
						// Initialize block: calls the "on_initialize" hook on every pallet
250
22
						// in AllPalletsWithSystem.
251
22
						// After pallet message queue was introduced, this must be done only after
252
22
						// enabling XCM tracing by setting ETHEREUM_XCM_TRACING_STORAGE_KEY
253
22
						// in the storage
254
22
						Executive::initialize_block(header);
255

            
256
						// Apply all extrinsics. Ethereum extrinsics are traced.
257
88
						for ext in extrinsics.into_iter() {
258
44
							match &ext.0.function {
259
44
								RuntimeCall::Ethereum(transact { transaction }) => {
260
44

            
261
44
									// Reset the previously consumed weight when tracing multiple transactions.
262
44
									// This is necessary because EVM tracing introduces additional
263
44
									// (ref_time) overhead, which differs from the production runtime behavior.
264
44
									// Without resetting the block weight, the extra tracing overhead could
265
44
									// leading to some transactions to incorrectly fail during tracing.
266
44
									frame_system::BlockWeight::<Runtime>::kill();
267
44

            
268
44
									let tx_hash = &transaction.hash();
269
44
									if known_transactions.contains(&tx_hash) {
270
44
										// Each known extrinsic is a new call stack.
271
44
										EvmTracer::emit_new();
272
44
										EvmTracer::new().trace(|| {
273
											if let Err(err) = Executive::apply_extrinsic(ext) {
274
												log::debug!(
275
													target: "tracing",
276
													"Could not trace eth transaction (hash: {}): {:?}",
277
													&tx_hash,
278
													err
279
												);
280
											}
281
44
										});
282
44
									} else {
283
										if let Err(err) = Executive::apply_extrinsic(ext) {
284
											log::debug!(
285
												target: "tracing",
286
												"Failed to apply eth extrinsic (hash: {}): {:?}",
287
												&tx_hash,
288
												err
289
											);
290
										}
291
									}
292
								}
293
								_ => {
294
44
									if let Err(err) = Executive::apply_extrinsic(ext) {
295
										log::debug!(
296
											target: "tracing",
297
											"Failed to apply non-eth extrinsic: {:?}",
298
											err
299
										);
300
									}
301
								}
302
							};
303
						}
304

            
305
						// Replay on_idle
306
						// Some XCM messages with eth-xcm transaction might be executed at on_idle
307
22
						replay_on_idle();
308
22

            
309
22
						Ok(())
310
22
					}
311
22
					#[cfg(not(feature = "evm-tracing"))]
312
22
					Err(sp_runtime::DispatchError::Other(
313
22
						"Missing `evm-tracing` compile time feature flag.",
314
22
					))
315
22
				}
316

            
317
22
				fn trace_call(
318
22
					header: &<Block as BlockT>::Header,
319
22
					from: H160,
320
22
					to: H160,
321
22
					data: Vec<u8>,
322
22
					value: U256,
323
22
					gas_limit: U256,
324
22
					max_fee_per_gas: Option<U256>,
325
22
					max_priority_fee_per_gas: Option<U256>,
326
22
					nonce: Option<U256>,
327
22
					access_list: Option<Vec<(H160, Vec<H256>)>>,
328
22
				) -> Result<(), sp_runtime::DispatchError> {
329
22
					#[cfg(feature = "evm-tracing")]
330
22
					{
331
22
						use moonbeam_evm_tracer::tracer::EvmTracer;
332
22

            
333
22
						// Initialize block: calls the "on_initialize" hook on every pallet
334
22
						// in AllPalletsWithSystem.
335
22
						Executive::initialize_block(header);
336
22

            
337
22
						EvmTracer::new().trace(|| {
338
							let is_transactional = false;
339
							let validate = true;
340

            
341
							let transaction_data = pallet_ethereum::TransactionData::new(
342
								pallet_ethereum::TransactionAction::Call(to),
343
								data.clone(),
344
								nonce.unwrap_or_default(),
345
								gas_limit,
346
								None,
347
								max_fee_per_gas.or(Some(U256::default())),
348
								max_priority_fee_per_gas.or(Some(U256::default())),
349
								value,
350
								Some(<Runtime as pallet_evm::Config>::ChainId::get()),
351
								access_list.clone().unwrap_or_default(),
352
							);
353

            
354
							let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
355

            
356
							let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::<Runtime>::transaction_weight(&transaction_data);
357

            
358
							let _ = <Runtime as pallet_evm::Config>::Runner::call(
359
								from,
360
								to,
361
								data,
362
								value,
363
								gas_limit,
364
								max_fee_per_gas,
365
								max_priority_fee_per_gas,
366
								nonce,
367
								access_list.unwrap_or_default(),
368
								is_transactional,
369
								validate,
370
								weight_limit,
371
								proof_size_base_cost,
372
								<Runtime as pallet_evm::Config>::config(),
373
							);
374
22
						});
375
22
						Ok(())
376
22
					}
377
22
					#[cfg(not(feature = "evm-tracing"))]
378
22
					Err(sp_runtime::DispatchError::Other(
379
22
						"Missing `evm-tracing` compile time feature flag.",
380
22
					))
381
22
				}
382
			}
383

            
384
			impl moonbeam_rpc_primitives_txpool::TxPoolRuntimeApi<Block> for Runtime {
385
22
				fn extrinsic_filter(
386
22
					xts_ready: Vec<<Block as BlockT>::Extrinsic>,
387
22
					xts_future: Vec<<Block as BlockT>::Extrinsic>,
388
22
				) -> TxPoolResponse {
389
22
					TxPoolResponse {
390
22
						ready: xts_ready
391
22
							.into_iter()
392
22
							.filter_map(|xt| match xt.0.function {
393
								RuntimeCall::Ethereum(transact { transaction }) => Some(transaction),
394
								_ => None,
395
22
							})
396
22
							.collect(),
397
22
						future: xts_future
398
22
							.into_iter()
399
22
							.filter_map(|xt| match xt.0.function {
400
								RuntimeCall::Ethereum(transact { transaction }) => Some(transaction),
401
								_ => None,
402
22
							})
403
22
							.collect(),
404
22
					}
405
22
				}
406
			}
407

            
408
			impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {
409
22
				fn chain_id() -> u64 {
410
22
					<Runtime as pallet_evm::Config>::ChainId::get()
411
22
				}
412

            
413
22
				fn account_basic(address: H160) -> EVMAccount {
414
22
					let (account, _) = EVM::account_basic(&address);
415
22
					account
416
22
				}
417

            
418
22
				fn gas_price() -> U256 {
419
22
					let (gas_price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();
420
22
					gas_price
421
22
				}
422

            
423
22
				fn account_code_at(address: H160) -> Vec<u8> {
424
22
					pallet_evm::AccountCodes::<Runtime>::get(address)
425
22
				}
426

            
427
22
				fn author() -> H160 {
428
22
					<pallet_evm::Pallet<Runtime>>::find_author()
429
22
				}
430

            
431
22
				fn storage_at(address: H160, index: U256) -> H256 {
432
22
					let mut tmp = [0u8; 32];
433
22
					index.to_big_endian(&mut tmp);
434
22
					pallet_evm::AccountStorages::<Runtime>::get(address, H256::from_slice(&tmp[..]))
435
22
				}
436

            
437
22
				fn call(
438
22
					from: H160,
439
22
					to: H160,
440
22
					data: Vec<u8>,
441
22
					value: U256,
442
22
					gas_limit: U256,
443
22
					max_fee_per_gas: Option<U256>,
444
22
					max_priority_fee_per_gas: Option<U256>,
445
22
					nonce: Option<U256>,
446
22
					estimate: bool,
447
22
					access_list: Option<Vec<(H160, Vec<H256>)>>,
448
22
				) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {
449
22
					let config = if estimate {
450
						let mut config = <Runtime as pallet_evm::Config>::config().clone();
451
						config.estimate = true;
452
						Some(config)
453
					} else {
454
22
						None
455
					};
456
22
					let is_transactional = false;
457
22
					let validate = true;
458
22

            
459
22
					let transaction_data = pallet_ethereum::TransactionData::new(
460
22
						pallet_ethereum::TransactionAction::Call(to),
461
22
						data.clone(),
462
22
						nonce.unwrap_or_default(),
463
22
						gas_limit,
464
22
						None,
465
22
						max_fee_per_gas.or(Some(U256::default())),
466
22
						max_priority_fee_per_gas.or(Some(U256::default())),
467
22
						value,
468
22
						Some(<Runtime as pallet_evm::Config>::ChainId::get()),
469
22
						access_list.clone().unwrap_or_default(),
470
22
					);
471
22

            
472
22
					let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
473
22

            
474
22
					let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::<Runtime>::transaction_weight(&transaction_data);
475
22

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

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

            
515
22
					let transaction_data = pallet_ethereum::TransactionData::new(
516
22
						pallet_ethereum::TransactionAction::Create,
517
22
						data.clone(),
518
22
						nonce.unwrap_or_default(),
519
22
						gas_limit,
520
22
						None,
521
22
						max_fee_per_gas.or(Some(U256::default())),
522
22
						max_priority_fee_per_gas.or(Some(U256::default())),
523
22
						value,
524
22
						Some(<Runtime as pallet_evm::Config>::ChainId::get()),
525
22
						access_list.clone().unwrap_or_default(),
526
22
					);
527
22

            
528
22
					let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
529
22

            
530
22
					let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::<Runtime>::transaction_weight(&transaction_data);
531
22

            
532
22
					#[allow(clippy::or_fun_call)] // suggestion not helpful here
533
22
					<Runtime as pallet_evm::Config>::Runner::create(
534
22
						from,
535
22
						data,
536
22
						value,
537
22
						gas_limit,
538
22
						max_fee_per_gas,
539
22
						max_priority_fee_per_gas,
540
22
						nonce,
541
22
						access_list.unwrap_or_default(),
542
22
						is_transactional,
543
22
						validate,
544
22
						weight_limit,
545
22
						proof_size_base_cost,
546
22
						config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),
547
22
					).map_err(|err| err.error.into())
548
22
				}
549

            
550
22
				fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {
551
22
					pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
552
22
				}
553

            
554
22
				fn current_block() -> Option<pallet_ethereum::Block> {
555
22
					pallet_ethereum::CurrentBlock::<Runtime>::get()
556
22
				}
557

            
558
22
				fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {
559
22
					pallet_ethereum::CurrentReceipts::<Runtime>::get()
560
22
				}
561

            
562
				fn current_all() -> (
563
					Option<pallet_ethereum::Block>,
564
					Option<Vec<pallet_ethereum::Receipt>>,
565
					Option<Vec<TransactionStatus>>,
566
				) {
567
					(
568
						pallet_ethereum::CurrentBlock::<Runtime>::get(),
569
						pallet_ethereum::CurrentReceipts::<Runtime>::get(),
570
						pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get(),
571
					)
572
				}
573

            
574
				fn extrinsic_filter(
575
					xts: Vec<<Block as BlockT>::Extrinsic>,
576
				) -> Vec<EthereumTransaction> {
577
					xts.into_iter().filter_map(|xt| match xt.0.function {
578
						RuntimeCall::Ethereum(transact { transaction }) => Some(transaction),
579
						_ => None
580
					}).collect::<Vec<EthereumTransaction>>()
581
				}
582

            
583
				fn elasticity() -> Option<Permill> {
584
					None
585
				}
586

            
587
				fn gas_limit_multiplier_support() {}
588

            
589
				fn pending_block(
590
					xts: Vec<<Block as sp_runtime::traits::Block>::Extrinsic>
591
				) -> (
592
					Option<pallet_ethereum::Block>, Option<sp_std::prelude::Vec<TransactionStatus>>
593
				) {
594
					for ext in xts.into_iter() {
595
						let _ = Executive::apply_extrinsic(ext);
596
					}
597

            
598
					Ethereum::on_finalize(System::block_number() + 1);
599

            
600
					(
601
						pallet_ethereum::CurrentBlock::<Runtime>::get(),
602
						pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
603
					)
604
				 }
605

            
606
				fn initialize_pending_block(header: &<Block as BlockT>::Header) {
607
					pallet_randomness::vrf::using_fake_vrf(|| {
608
						let _ = Executive::initialize_block(header);
609
					})
610
				}
611
			}
612

            
613
			impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {
614
				fn convert_transaction(
615
					transaction: pallet_ethereum::Transaction
616
				) -> <Block as BlockT>::Extrinsic {
617
					UncheckedExtrinsic::new_unsigned(
618
						pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
619
					)
620
				}
621
			}
622

            
623
			impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
624
			for Runtime {
625
				fn query_info(
626
					uxt: <Block as BlockT>::Extrinsic,
627
					len: u32,
628
				) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
629
					TransactionPayment::query_info(uxt, len)
630
				}
631

            
632
				fn query_fee_details(
633
					uxt: <Block as BlockT>::Extrinsic,
634
					len: u32,
635
				) -> pallet_transaction_payment::FeeDetails<Balance> {
636
					TransactionPayment::query_fee_details(uxt, len)
637
				}
638

            
639
				fn query_weight_to_fee(weight: Weight) -> Balance {
640
					TransactionPayment::weight_to_fee(weight)
641
				}
642

            
643
				fn query_length_to_fee(length: u32) -> Balance {
644
					TransactionPayment::length_to_fee(length)
645
				}
646
			}
647

            
648
			impl nimbus_primitives::NimbusApi<Block> for Runtime {
649
66
				fn can_author(
650
66
					author: nimbus_primitives::NimbusId,
651
66
					slot: u32,
652
66
					parent_header: &<Block as BlockT>::Header
653
66
				) -> bool {
654
66
					use pallet_parachain_staking::Config as PalletParachainStakingConfig;
655
66

            
656
66
					let block_number = parent_header.number + 1;
657
66

            
658
66
					// The Moonbeam runtimes use an entropy source that needs to do some accounting
659
66
					// work during block initialization. Therefore we initialize it here to match
660
66
					// the state it will be in when the next block is being executed.
661
66
					use frame_support::traits::OnInitialize;
662
66
					System::initialize(
663
66
						&block_number,
664
66
						&parent_header.hash(),
665
66
						&parent_header.digest,
666
66
					);
667
66

            
668
66
					// Because the staking solution calculates the next staking set at the beginning
669
66
					// of the first block in the new round, the only way to accurately predict the
670
66
					// authors is to compute the selection during prediction.
671
66
					if pallet_parachain_staking::Pallet::<Self>::round()
672
66
						.should_update(block_number) {
673
						// get author account id
674
						use nimbus_primitives::AccountLookup;
675
						let author_account_id = if let Some(account) =
676
							pallet_author_mapping::Pallet::<Self>::lookup_account(&author) {
677
							account
678
						} else {
679
							// return false if author mapping not registered like in can_author impl
680
							return false
681
						};
682
						let candidates = pallet_parachain_staking::Pallet::<Self>::compute_top_candidates();
683
						if candidates.is_empty() {
684
							// If there are zero selected candidates, we use the same eligibility
685
							// as the previous round
686
							return AuthorInherent::can_author(&author, &slot);
687
						}
688

            
689
						// predict eligibility post-selection by computing selection results now
690
						let (eligible, _) =
691
							pallet_author_slot_filter::compute_pseudo_random_subset::<Self>(
692
								candidates,
693
								&slot
694
							);
695
						eligible.contains(&author_account_id)
696
					} else {
697
66
						AuthorInherent::can_author(&author, &slot)
698
					}
699
				}
700
			}
701

            
702
			impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
703
				fn collect_collation_info(
704
					header: &<Block as BlockT>::Header
705
				) -> cumulus_primitives_core::CollationInfo {
706
					ParachainSystem::collect_collation_info(header)
707
				}
708
			}
709

            
710
			impl session_keys_primitives::VrfApi<Block> for Runtime {
711
				fn get_last_vrf_output() -> Option<<Block as BlockT>::Hash> {
712
					// TODO: remove in future runtime upgrade along with storage item
713
					if pallet_randomness::Pallet::<Self>::not_first_block().is_none() {
714
						return None;
715
					}
716
					pallet_randomness::Pallet::<Self>::local_vrf_output()
717
				}
718
				fn vrf_key_lookup(
719
					nimbus_id: nimbus_primitives::NimbusId
720
				) -> Option<session_keys_primitives::VrfId> {
721
					use session_keys_primitives::KeysLookup;
722
					AuthorMapping::lookup_keys(&nimbus_id)
723
				}
724
			}
725

            
726
			impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
727
				fn query_acceptable_payment_assets(
728
					xcm_version: xcm::Version
729
				) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
730
					XcmWeightTrader::query_acceptable_payment_assets(xcm_version)
731
				}
732

            
733
				fn query_weight_to_asset_fee(
734
					weight: Weight, asset: VersionedAssetId
735
				) -> Result<u128, XcmPaymentApiError> {
736
					XcmWeightTrader::query_weight_to_asset_fee(weight, asset)
737
				}
738

            
739
				fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
740
					PolkadotXcm::query_xcm_weight(message)
741
				}
742

            
743
				fn query_delivery_fees(
744
					destination: VersionedLocation, message: VersionedXcm<()>
745
				) -> Result<VersionedAssets, XcmPaymentApiError> {
746
					PolkadotXcm::query_delivery_fees(destination, message)
747
				}
748
			}
749

            
750
			impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller>
751
				for Runtime {
752
					fn dry_run_call(
753
						origin: OriginCaller,
754
						call: RuntimeCall
755
					) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
756
						PolkadotXcm::dry_run_call::<
757
							Runtime,
758
							xcm_config::XcmRouter,
759
							OriginCaller,
760
							RuntimeCall>(origin, call)
761
					}
762

            
763
					fn dry_run_xcm(
764
						origin_location: VersionedLocation,
765
						xcm: VersionedXcm<RuntimeCall>
766
					) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
767
						PolkadotXcm::dry_run_xcm::<
768
							Runtime,
769
							xcm_config::XcmRouter,
770
							RuntimeCall,
771
							xcm_config::XcmExecutorConfig>(origin_location, xcm)
772
					}
773
				}
774

            
775
			impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
776
				fn convert_location(location: VersionedLocation) -> Result<
777
					AccountId,
778
					xcm_runtime_apis::conversions::Error
779
				> {
780
					xcm_runtime_apis::conversions::LocationToAccountHelper::<
781
						AccountId,
782
						xcm_config::LocationToAccountId,
783
					>::convert_location(location)
784
				}
785
			}
786

            
787
			#[cfg(feature = "runtime-benchmarks")]
788
			impl frame_benchmarking::Benchmark<Block> for Runtime {
789

            
790
				fn benchmark_metadata(extra: bool) -> (
791
					Vec<frame_benchmarking::BenchmarkList>,
792
					Vec<frame_support::traits::StorageInfo>,
793
				) {
794
					use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};
795
					use frame_system_benchmarking::Pallet as SystemBench;
796
					use moonbeam_xcm_benchmarks::generic::benchmarking as MoonbeamXcmBenchmarks;
797
					use frame_support::traits::StorageInfoTrait;
798
					use MoonbeamXcmBenchmarks::XcmGenericBenchmarks as MoonbeamXcmGenericBench;
799

            
800
					use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
801

            
802
					let mut list = Vec::<BenchmarkList>::new();
803
					list_benchmarks!(list, extra);
804

            
805
					let storage_info = AllPalletsWithSystem::storage_info();
806

            
807
					return (list, storage_info)
808
				}
809

            
810
				fn dispatch_benchmark(
811
					config: frame_benchmarking::BenchmarkConfig,
812
				) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
813
					use frame_benchmarking::{add_benchmark, BenchmarkBatch, Benchmarking};
814
					use frame_support::traits::TrackedStorageKey;
815
					use cumulus_primitives_core::ParaId;
816

            
817
					use xcm::latest::prelude::{
818
						GeneralIndex, Junction, Junctions, Location, Response, NetworkId, AssetId,
819
						Assets as XcmAssets, Fungible, Asset, ParentThen, Parachain, Parent
820
					};
821
					use xcm_config::SelfReserve;
822
					use frame_benchmarking::BenchmarkError;
823

            
824
					use frame_system_benchmarking::Pallet as SystemBench;
825
					// Needed to run `set_code` and `apply_authorized_upgrade` frame_system benchmarks
826
					// https://github.com/paritytech/cumulus/pull/2766
827
					impl frame_system_benchmarking::Config for Runtime {
828
						fn setup_set_code_requirements(code: &Vec<u8>) -> Result<(), BenchmarkError> {
829
							ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
830
							Ok(())
831
						}
832

            
833
						fn verify_set_code() {
834
							System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
835
						}
836
					}
837

            
838
					impl moonbeam_xcm_benchmarks::Config for Runtime {}
839
					impl moonbeam_xcm_benchmarks::generic::Config for Runtime {}
840

            
841
					use pallet_asset_manager::Config as PalletAssetManagerConfig;
842

            
843
					use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
844
					parameter_types! {
845
						pub const RandomParaId: ParaId = ParaId::new(43211234);
846
					}
847

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

            
863
							(None, None)
864
						}
865
					}
866

            
867
					impl pallet_xcm::benchmarking::Config for Runtime {
868
				        type DeliveryHelper = TestDeliveryHelper;
869

            
870
						fn get_asset() -> Asset {
871
							Asset {
872
								id: AssetId(SelfReserve::get()),
873
								fun: Fungible(ExistentialDeposit::get()),
874
							}
875
						}
876

            
877
						fn reachable_dest() -> Option<Location> {
878
							Some(Parent.into())
879
						}
880

            
881
						fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
882
							None
883
						}
884

            
885
						fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
886
							use xcm_config::SelfReserve;
887

            
888
							ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
889
								RandomParaId::get().into()
890
							);
891

            
892
							Some((
893
								Asset {
894
									fun: Fungible(ExistentialDeposit::get()),
895
									id: AssetId(SelfReserve::get().into())
896
								},
897
								// Moonbeam can reserve transfer native token to
898
								// some random parachain.
899
								ParentThen(Parachain(RandomParaId::get().into()).into()).into(),
900
							))
901
						}
902

            
903
						fn set_up_complex_asset_transfer(
904
						) -> Option<(XcmAssets, u32, Location, Box<dyn FnOnce()>)> {
905
							use xcm_config::SelfReserve;
906

            
907
							let destination: xcm::v4::Location = Parent.into();
908

            
909
							let fee_amount: u128 = <Runtime as pallet_balances::Config>::ExistentialDeposit::get();
910
							let fee_asset: Asset = (SelfReserve::get(), fee_amount).into();
911

            
912
							// Give some multiple of transferred amount
913
							let balance = fee_amount * 1000;
914
							let who = frame_benchmarking::whitelisted_caller();
915
							let _ =
916
								<Balances as frame_support::traits::Currency<_>>::make_free_balance_be(&who, balance);
917

            
918
							// verify initial balance
919
							assert_eq!(Balances::free_balance(&who), balance);
920

            
921
							// set up local asset
922
							let asset_amount: u128 = 10u128;
923
							let initial_asset_amount: u128 = asset_amount * 10;
924

            
925
							let (asset_id, _, _) = pallet_assets::benchmarking::create_default_minted_asset::<
926
								Runtime,
927
								()
928
							>(true, initial_asset_amount);
929
							let transfer_asset: Asset = (SelfReserve::get(), asset_amount).into();
930

            
931
							let assets: XcmAssets = vec![fee_asset.clone(), transfer_asset].into();
932
							let fee_index: u32 = 0;
933

            
934
							let verify: Box<dyn FnOnce()> = Box::new(move || {
935
								// verify balance after transfer, decreased by
936
								// transferred amount (and delivery fees)
937
								assert!(Balances::free_balance(&who) <= balance - fee_amount);
938
							});
939

            
940
							Some((assets, fee_index, destination, verify))
941
						}
942
					}
943

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

            
973

            
974
							for (i, asset) in assets.iter().enumerate() {
975
								if let Asset {
976
									id: AssetId(location),
977
									fun: Fungible(_)
978
								} = asset {
979
									EvmForeignAssets::set_asset(
980
										location.clone(),
981
										i as u128
982
									);
983
									XcmWeightTrader::set_asset_price(
984
										location.clone(),
985
										1u128.pow(18)
986
									);
987
								}
988
							}
989
							assets.into()
990
						}
991
					}
992

            
993
					impl pallet_xcm_benchmarks::generic::Config for Runtime {
994
						type RuntimeCall = RuntimeCall;
995
						type TransactAsset = Balances;
996

            
997
						fn worst_case_response() -> (u64, Response) {
998
							(0u64, Response::Version(Default::default()))
999
						}
						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")
				}
			}
		}
	};
}