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)*} {$($bench_custom:tt)*}) => {
20
    	use ethereum::AuthorizationList;
21

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

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

            
47
		impl_runtime_apis! {
48
			$($custom)*
49

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

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

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

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

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

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

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

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

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

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

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

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

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

            
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
				#[cfg(not(feature = "disable-genesis-builder"))]
125
				fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
126
					frame_support::genesis_builder_helper::get_preset::<RuntimeGenesisConfig>(id, genesis_config_preset::get_preset)
127
				}
128
				#[cfg(feature = "disable-genesis-builder")]
129
				fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
130
					None
131
				}
132

            
133
				#[cfg(not(feature = "disable-genesis-builder"))]
134
				fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
135
					genesis_config_preset::preset_names()
136
				}
137
				#[cfg(feature = "disable-genesis-builder")]
138
				fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
139
					Default::default()
140
				}
141
			}
142

            
143
			impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
144
				fn account_nonce(account: AccountId) -> Index {
145
					System::account_nonce(account)
146
				}
147
			}
148

            
149
			impl moonbeam_rpc_primitives_debug::DebugRuntimeApi<Block> for Runtime {
150
19
				fn trace_transaction(
151
19
					extrinsics: Vec<<Block as BlockT>::Extrinsic>,
152
19
					traced_transaction: &EthereumTransaction,
153
19
					header: &<Block as BlockT>::Header,
154
19
				) -> Result<
155
19
					(),
156
19
					sp_runtime::DispatchError,
157
19
				> {
158
					#[cfg(feature = "evm-tracing")]
159
					{
160
						use moonbeam_evm_tracer::tracer::{
161
							EthereumTracingStatus,
162
							EvmTracer,
163
							EthereumTracer
164
						};
165
						use frame_support::storage::unhashed;
166
						use frame_system::pallet_prelude::BlockNumberFor;
167

            
168
						// Tell the CallDispatcher we are tracing a specific Transaction.
169
19
						EthereumTracer::transaction(traced_transaction.hash(), || {
170
							// Initialize block: calls the "on_initialize" hook on every pallet
171
							// in AllPalletsWithSystem.
172
							// After pallet message queue was introduced, this must be done only after
173
							// enabling XCM tracing by calling ETHEREUM_TRACING_STATUS::using
174
							// in the storage
175
19
							Executive::initialize_block(header);
176

            
177
							// Apply the a subset of extrinsics: all the substrate-specific or ethereum
178
							// transactions that preceded the requested transaction.
179
38
							for ext in extrinsics.into_iter() {
180
38
								let _ = match &ext.0.function {
181
19
									RuntimeCall::Ethereum(transact { transaction }) => {
182
										// Reset the previously consumed weight when tracing ethereum transactions.
183
										// This is necessary because EVM tracing introduces additional
184
										// (ref_time) overhead, which differs from the production runtime behavior.
185
										// Without resetting the block weight, the extra tracing overhead could
186
										// leading to some transactions to incorrectly fail during tracing.
187
19
										frame_system::BlockWeight::<Runtime>::kill();
188

            
189
19
										if transaction == traced_transaction {
190
19
											EvmTracer::new().trace(|| Executive::apply_extrinsic(ext));
191
19
											return Ok(());
192
										} else {
193
											Executive::apply_extrinsic(ext)
194
										}
195
									}
196
19
									_ => Executive::apply_extrinsic(ext),
197
								};
198

            
199
19
								if let Some(EthereumTracingStatus::TransactionExited) = EthereumTracer::status() {
200
									return Ok(());
201
19
								}
202
							}
203

            
204
							if let Some(EthereumTracingStatus::Transaction(_)) = EthereumTracer::status() {
205
								// If the transaction was not found, it might be
206
								// an eth-xcm transaction that was executed at on_idle
207
								replay_on_idle();
208
							}
209

            
210
							if let Some(EthereumTracingStatus::TransactionExited) = EthereumTracer::status() {
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
19
						})
220
					}
221
					#[cfg(not(feature = "evm-tracing"))]
222
					Err(sp_runtime::DispatchError::Other(
223
						"Missing `evm-tracing` compile time feature flag.",
224
					))
225
19
				}
226

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

            
244
						// Tell the CallDispatcher we are tracing a full Block.
245
19
						EthereumTracer::block(|| {
246
19
							let mut config = <Runtime as pallet_evm::Config>::config().clone();
247
19
							config.estimate = true;
248

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

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

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

            
268
38
										let tx_hash = &transaction.hash();
269
38
										if known_transactions.contains(&tx_hash) {
270
											// Each known extrinsic is a new call stack.
271
38
											EvmTracer::emit_new();
272
38
											EvmTracer::new().trace(|| {
273
38
												if let Err(err) = Executive::apply_extrinsic(ext) {
274
38
													log::debug!(
275
														target: "tracing",
276
														"Could not trace eth transaction (hash: {}): {:?}",
277
														&tx_hash,
278
														err
279
													);
280
												}
281
38
											});
282
										} 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
38
										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
38
										}
301
									}
302
								};
303
							}
304

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

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

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

            
335
						// Initialize block: calls the "on_initialize" hook on every pallet
336
						// in AllPalletsWithSystem.
337
19
						Executive::initialize_block(header);
338

            
339
19
						EvmTracer::new().trace(|| {
340
19
							let is_transactional = false;
341
19
							let validate = true;
342

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

            
357
19
							let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
358

            
359
19
							let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::<Runtime>::transaction_weight(&transaction_data);
360

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

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

            
412
			impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {
413
19
				fn chain_id() -> u64 {
414
19
					<Runtime as pallet_evm::Config>::ChainId::get()
415
19
				}
416

            
417
19
				fn account_basic(address: H160) -> EVMAccount {
418
19
					let (account, _) = EVM::account_basic(&address);
419
19
					account
420
19
				}
421

            
422
19
				fn gas_price() -> U256 {
423
19
					let (gas_price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();
424
19
					gas_price
425
19
				}
426

            
427
19
				fn account_code_at(address: H160) -> Vec<u8> {
428
19
					pallet_evm::AccountCodes::<Runtime>::get(address)
429
19
				}
430

            
431
19
				fn author() -> H160 {
432
19
					<pallet_evm::Pallet<Runtime>>::find_author()
433
19
				}
434

            
435
19
				fn storage_at(address: H160, index: U256) -> H256 {
436
19
					let tmp: [u8; 32] = index.to_big_endian();
437
19
					pallet_evm::AccountStorages::<Runtime>::get(address, H256::from_slice(&tmp[..]))
438
19
				}
439

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

            
463
19
					let transaction_data = pallet_ethereum::TransactionData::new(
464
19
						pallet_ethereum::TransactionAction::Call(to),
465
19
						data.clone(),
466
19
						nonce.unwrap_or_default(),
467
19
						gas_limit,
468
19
						None,
469
19
						max_fee_per_gas.or(Some(U256::default())),
470
19
						max_priority_fee_per_gas.or(Some(U256::default())),
471
19
						value,
472
19
						Some(<Runtime as pallet_evm::Config>::ChainId::get()),
473
19
						access_list.clone().unwrap_or_default(),
474
19
						authorization_list.clone().unwrap_or_default(),
475
					);
476

            
477
19
					let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
478

            
479
19
					let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::<Runtime>::transaction_weight(&transaction_data);
480

            
481
19
					<Runtime as pallet_evm::Config>::Runner::call(
482
19
						from,
483
19
						to,
484
19
						data,
485
19
						value,
486
19
						gas_limit,
487
19
						max_fee_per_gas,
488
19
						max_priority_fee_per_gas,
489
19
						nonce,
490
19
						access_list.unwrap_or_default(),
491
19
						authorization_list.unwrap_or_default(),
492
19
						is_transactional,
493
19
						validate,
494
19
						weight_limit,
495
19
						proof_size_base_cost,
496
19
						config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),
497
19
					).map_err(|err| err.error.into())
498
19
				}
499

            
500
19
				fn create(
501
19
					from: H160,
502
19
					data: Vec<u8>,
503
19
					value: U256,
504
19
					gas_limit: U256,
505
19
					max_fee_per_gas: Option<U256>,
506
19
					max_priority_fee_per_gas: Option<U256>,
507
19
					nonce: Option<U256>,
508
19
					estimate: bool,
509
19
					access_list: Option<Vec<(H160, Vec<H256>)>>,
510
19
					authorization_list: Option<AuthorizationList>,
511
19
				) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {
512
19
					let config = if estimate {
513
						let mut config = <Runtime as pallet_evm::Config>::config().clone();
514
						config.estimate = true;
515
						Some(config)
516
					} else {
517
19
						None
518
					};
519
19
					let is_transactional = false;
520
19
					let validate = true;
521

            
522
19
					let transaction_data = pallet_ethereum::TransactionData::new(
523
19
						pallet_ethereum::TransactionAction::Create,
524
19
						data.clone(),
525
19
						nonce.unwrap_or_default(),
526
19
						gas_limit,
527
19
						None,
528
19
						max_fee_per_gas.or(Some(U256::default())),
529
19
						max_priority_fee_per_gas.or(Some(U256::default())),
530
19
						value,
531
19
						Some(<Runtime as pallet_evm::Config>::ChainId::get()),
532
19
						access_list.clone().unwrap_or_default(),
533
19
						authorization_list.clone().unwrap_or_default(),
534
					);
535

            
536
19
					let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
537

            
538
19
					let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::<Runtime>::transaction_weight(&transaction_data);
539

            
540
					#[allow(clippy::or_fun_call)] // suggestion not helpful here
541
19
					<Runtime as pallet_evm::Config>::Runner::create(
542
19
						from,
543
19
						data,
544
19
						value,
545
19
						gas_limit,
546
19
						max_fee_per_gas,
547
19
						max_priority_fee_per_gas,
548
19
						nonce,
549
19
						access_list.unwrap_or_default(),
550
19
						authorization_list.unwrap_or_default(),
551
19
						is_transactional,
552
19
						validate,
553
19
						weight_limit,
554
19
						proof_size_base_cost,
555
19
						config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),
556
19
					).map_err(|err| err.error.into())
557
19
				}
558

            
559
19
				fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {
560
19
					pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
561
19
				}
562

            
563
19
				fn current_block() -> Option<pallet_ethereum::Block> {
564
19
					pallet_ethereum::CurrentBlock::<Runtime>::get()
565
19
				}
566

            
567
19
				fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {
568
19
					pallet_ethereum::CurrentReceipts::<Runtime>::get()
569
19
				}
570

            
571
				fn current_all() -> (
572
					Option<pallet_ethereum::Block>,
573
					Option<Vec<pallet_ethereum::Receipt>>,
574
					Option<Vec<TransactionStatus>>,
575
				) {
576
					(
577
						pallet_ethereum::CurrentBlock::<Runtime>::get(),
578
						pallet_ethereum::CurrentReceipts::<Runtime>::get(),
579
						pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get(),
580
					)
581
				}
582

            
583
				fn extrinsic_filter(
584
					xts: Vec<<Block as BlockT>::Extrinsic>,
585
				) -> Vec<EthereumTransaction> {
586
					xts.into_iter().filter_map(|xt| match xt.0.function {
587
						RuntimeCall::Ethereum(transact { transaction }) => Some(transaction),
588
						_ => None
589
					}).collect::<Vec<EthereumTransaction>>()
590
				}
591

            
592
				fn elasticity() -> Option<Permill> {
593
					None
594
				}
595

            
596
				fn gas_limit_multiplier_support() {}
597

            
598
				fn pending_block(
599
					xts: Vec<<Block as sp_runtime::traits::Block>::Extrinsic>
600
				) -> (
601
					Option<pallet_ethereum::Block>, Option<sp_std::prelude::Vec<TransactionStatus>>
602
				) {
603
					for ext in xts.into_iter() {
604
						let _ = Executive::apply_extrinsic(ext);
605
					}
606

            
607
					Ethereum::on_finalize(System::block_number() + 1);
608

            
609
					(
610
						pallet_ethereum::CurrentBlock::<Runtime>::get(),
611
						pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
612
					)
613
				 }
614

            
615
				fn initialize_pending_block(header: &<Block as BlockT>::Header) {
616
					pallet_randomness::vrf::using_fake_vrf(|| {
617
						let _ = Executive::initialize_block(header);
618
					})
619
				}
620
			}
621

            
622
			impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {
623
				fn convert_transaction(
624
					transaction: pallet_ethereum::Transaction
625
				) -> <Block as BlockT>::Extrinsic {
626
					UncheckedExtrinsic::new_bare(
627
						pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
628
					)
629
				}
630
			}
631

            
632
			impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
633
			for Runtime {
634
				fn query_info(
635
					uxt: <Block as BlockT>::Extrinsic,
636
					len: u32,
637
				) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
638
					TransactionPayment::query_info(uxt, len)
639
				}
640

            
641
				fn query_fee_details(
642
					uxt: <Block as BlockT>::Extrinsic,
643
					len: u32,
644
				) -> pallet_transaction_payment::FeeDetails<Balance> {
645
					TransactionPayment::query_fee_details(uxt, len)
646
				}
647

            
648
				fn query_weight_to_fee(weight: Weight) -> Balance {
649
					TransactionPayment::weight_to_fee(weight)
650
				}
651

            
652
				fn query_length_to_fee(length: u32) -> Balance {
653
					TransactionPayment::length_to_fee(length)
654
				}
655
			}
656

            
657
			impl nimbus_primitives::NimbusApi<Block> for Runtime {
658
57
				fn can_author(
659
57
					author: nimbus_primitives::NimbusId,
660
57
					slot: u32,
661
57
					parent_header: &<Block as BlockT>::Header
662
57
				) -> bool {
663
					use pallet_parachain_staking::Config as PalletParachainStakingConfig;
664

            
665
57
					let block_number = parent_header.number + 1;
666

            
667
					// The Moonbeam runtimes use an entropy source that needs to do some accounting
668
					// work during block initialization. Therefore we initialize it here to match
669
					// the state it will be in when the next block is being executed.
670
					use frame_support::traits::OnInitialize;
671
57
					System::initialize(
672
57
						&block_number,
673
57
						&parent_header.hash(),
674
57
						&parent_header.digest,
675
					);
676

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

            
698
						// predict eligibility post-selection by computing selection results now
699
						let (eligible, _) =
700
							pallet_author_slot_filter::compute_pseudo_random_subset::<Self>(
701
								candidates,
702
								&slot
703
							);
704
						eligible.contains(&author_account_id)
705
					} else {
706
57
						AuthorInherent::can_author(&author, &slot)
707
					}
708
57
				}
709
			}
710

            
711
			impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
712
				fn collect_collation_info(
713
					header: &<Block as BlockT>::Header
714
				) -> cumulus_primitives_core::CollationInfo {
715
					ParachainSystem::collect_collation_info(header)
716
				}
717
			}
718

            
719
			impl session_keys_primitives::VrfApi<Block> for Runtime {
720
				fn get_last_vrf_output() -> Option<<Block as BlockT>::Hash> {
721
					// TODO: remove in future runtime upgrade along with storage item
722
					if pallet_randomness::Pallet::<Self>::not_first_block().is_none() {
723
						return None;
724
					}
725
					pallet_randomness::Pallet::<Self>::local_vrf_output()
726
				}
727
				fn vrf_key_lookup(
728
					nimbus_id: nimbus_primitives::NimbusId
729
				) -> Option<session_keys_primitives::VrfId> {
730
					use session_keys_primitives::KeysLookup;
731
					AuthorMapping::lookup_keys(&nimbus_id)
732
				}
733
			}
734

            
735
			impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
736
				fn query_acceptable_payment_assets(
737
					xcm_version: xcm::Version
738
				) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
739
					XcmWeightTrader::query_acceptable_payment_assets(xcm_version)
740
				}
741

            
742
				fn query_weight_to_asset_fee(
743
					weight: Weight, asset: VersionedAssetId
744
				) -> Result<u128, XcmPaymentApiError> {
745
					XcmWeightTrader::query_weight_to_asset_fee(weight, asset)
746
				}
747

            
748
				fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
749
					PolkadotXcm::query_xcm_weight(message)
750
				}
751

            
752
				fn query_delivery_fees(
753
					destination: VersionedLocation, message: VersionedXcm<()>
754
				) -> Result<VersionedAssets, XcmPaymentApiError> {
755
					PolkadotXcm::query_delivery_fees(destination, message)
756
				}
757
			}
758

            
759
			impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller>
760
				for Runtime {
761
					fn dry_run_call(
762
						origin: OriginCaller,
763
						call: RuntimeCall,
764
						result_xcms_version: XcmVersion
765
					) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
766
						PolkadotXcm::dry_run_call::<
767
							Runtime,
768
							xcm_config::XcmRouter,
769
							OriginCaller,
770
							RuntimeCall>(origin, call, result_xcms_version)
771
					}
772

            
773
					fn dry_run_xcm(
774
						origin_location: VersionedLocation,
775
						xcm: VersionedXcm<RuntimeCall>
776
					) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
777
						PolkadotXcm::dry_run_xcm::<xcm_config::XcmRouter>(origin_location, xcm)
778
					}
779
				}
780

            
781
			impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
782
				fn convert_location(location: VersionedLocation) -> Result<
783
					AccountId,
784
					xcm_runtime_apis::conversions::Error
785
				> {
786
					xcm_runtime_apis::conversions::LocationToAccountHelper::<
787
						AccountId,
788
						xcm_config::LocationToAccountId,
789
					>::convert_location(location)
790
				}
791
			}
792

            
793
			#[cfg(feature = "runtime-benchmarks")]
794
			impl frame_benchmarking::Benchmark<Block> for Runtime {
795

            
796
				fn benchmark_metadata(extra: bool) -> (
797
					Vec<frame_benchmarking::BenchmarkList>,
798
					Vec<frame_support::traits::StorageInfo>,
799
				) {
800
					use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};
801
					use frame_system_benchmarking::Pallet as SystemBench;
802
					use frame_support::traits::StorageInfoTrait;
803

            
804
					use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
805
					use pallet_transaction_payment::benchmarking::Pallet as TransactionPaymentBenchmark;
806

            
807
					let mut list = Vec::<BenchmarkList>::new();
808
					list_benchmarks!(list, extra);
809

            
810
					let storage_info = AllPalletsWithSystem::storage_info();
811

            
812
					return (list, storage_info)
813
				}
814

            
815
				#[allow(non_local_definitions)]
816
				fn dispatch_benchmark(
817
					config: frame_benchmarking::BenchmarkConfig,
818
				) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
819
					use frame_benchmarking::{add_benchmark, BenchmarkBatch, Benchmarking};
820
					use frame_support::traits::TrackedStorageKey;
821
					use cumulus_primitives_core::ParaId;
822

            
823
					use xcm::latest::prelude::{
824
						GeneralIndex, Junction, Junctions, Location, Response, NetworkId, AssetId,
825
						Assets as XcmAssets, Fungible, Asset, ParentThen, Parachain, Parent, WeightLimit
826
					};
827
					use xcm_config::SelfReserve;
828
					use frame_benchmarking::BenchmarkError;
829

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

            
839
						fn verify_set_code() {
840
							System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
841
						}
842
					}
843

            
844
					// Needed to run `charge_transaction_payment` benchmark which distributes
845
					// fees to block author. Moonbeam requires an author to be set for fee distribution.
846
					use pallet_transaction_payment::benchmarking::Pallet as TransactionPaymentBenchmark;
847
					impl pallet_transaction_payment::benchmarking::Config for Runtime {
848
						fn setup_benchmark_environment() {
849
							// Set a dummy author for the block so fee distribution doesn't panic
850
							let author: AccountId = frame_benchmarking::whitelisted_caller();
851
							pallet_author_inherent::Author::<Runtime>::put(author);
852
						}
853
					}
854

            
855
					use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
856
					parameter_types! {
857
						pub const RandomParaId: ParaId = ParaId::new(43211234);
858
					}
859

            
860
					/// Custom delivery helper for Moonbeam that works with H160 accounts.
861
					/// This is needed because Moonbeam uses AccountKey20 (H160) accounts
862
					/// instead of AccountId32, and the standard ToParentDeliveryHelper
863
					/// fails when trying to deposit assets to an origin location.
864
					pub struct TestDeliveryHelper;
865
					impl xcm_builder::EnsureDelivery for TestDeliveryHelper {
866
						fn ensure_successful_delivery(
867
							origin_ref: &Location,
868
							dest: &Location,
869
							_fee_reason: xcm_executor::traits::FeeReason,
870
						) -> (Option<xcm_executor::FeesMode>, Option<XcmAssets>) {
871
							use xcm_executor::traits::ConvertLocation;
872

            
873
							// Ensure the XCM sender is properly configured for benchmarks
874
							// This sets up the HostConfiguration for sending messages
875
							<xcm_config::XcmRouter as xcm::latest::SendXcm>::ensure_successful_delivery(Some(dest.clone()));
876

            
877
							// Open HRMP channel for sibling parachain destinations
878
							if let Some(Parachain(para_id)) = dest.interior().first() {
879
								ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
880
									(*para_id).into()
881
								);
882
							}
883

            
884
							// Deposit existential deposit to the origin account if we can convert it
885
							if let Some(account) = xcm_config::LocationToH160::convert_location(origin_ref) {
886
								let balance = ExistentialDeposit::get() * 1000u128;
887
								let _ = <Balances as frame_support::traits::Currency<_>>::
888
									make_free_balance_be(&account.into(), balance);
889
							}
890

            
891
							(None, None)
892
						}
893
					}
894

            
895
					impl pallet_xcm::benchmarking::Config for Runtime {
896
				        type DeliveryHelper = TestDeliveryHelper;
897

            
898
						fn get_asset() -> Asset {
899
							Asset {
900
								id: AssetId(SelfReserve::get()),
901
								fun: Fungible(ExistentialDeposit::get()),
902
							}
903
						}
904

            
905
						fn reachable_dest() -> Option<Location> {
906
							Some(Parent.into())
907
						}
908

            
909
						fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
910
							None
911
						}
912

            
913
						fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
914
							use xcm_config::SelfReserve;
915

            
916
							ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
917
								RandomParaId::get().into()
918
							);
919

            
920
							Some((
921
								Asset {
922
									fun: Fungible(ExistentialDeposit::get()),
923
									id: AssetId(SelfReserve::get().into())
924
								},
925
								// Moonbeam can reserve transfer native token to
926
								// some random parachain.
927
								ParentThen(Parachain(RandomParaId::get().into()).into()).into(),
928
							))
929
						}
930

            
931
						fn set_up_complex_asset_transfer(
932
						) -> Option<(XcmAssets, u32, Location, Box<dyn FnOnce()>)> {
933
							use xcm_config::SelfReserve;
934

            
935
							let destination: xcm::v5::Location = Parent.into();
936

            
937
							let fee_amount: u128 = <Runtime as pallet_balances::Config>::ExistentialDeposit::get();
938
							let fee_asset: Asset = (SelfReserve::get(), fee_amount).into();
939

            
940
							// Give some multiple of transferred amount
941
							let balance = fee_amount * 1000;
942
							let who = frame_benchmarking::whitelisted_caller();
943
							let _ =
944
								<Balances as frame_support::traits::Currency<_>>::make_free_balance_be(&who, balance);
945

            
946
							// verify initial balance
947
							assert_eq!(Balances::free_balance(&who), balance);
948

            
949
							// set up foreign asset
950
							let asset_amount: u128 = 10u128;
951
							let initial_asset_amount: u128 = asset_amount * 10;
952

            
953
							let asset_id = pallet_moonbeam_foreign_assets::default_asset_id::<Runtime>() + 1;
954
							let (_, location, _) = pallet_moonbeam_foreign_assets::create_default_minted_foreign_asset::<Runtime>(
955
								asset_id,
956
								initial_asset_amount,
957
							);
958
							let transfer_asset: Asset = (AssetId(location), asset_amount).into();
959

            
960
							let assets: XcmAssets = vec![fee_asset.clone(), transfer_asset].into();
961
							let fee_index: u32 = 0;
962

            
963
							let verify: Box<dyn FnOnce()> = Box::new(move || {
964
								// verify balance after transfer, decreased by
965
								// transferred amount (and delivery fees)
966
								assert!(Balances::free_balance(&who) <= balance - fee_amount);
967
							});
968

            
969
							Some((assets, fee_index, destination, verify))
970
						}
971
					}
972

            
973
					impl pallet_xcm_benchmarks::Config for Runtime {
974
						type XcmConfig = xcm_config::XcmExecutorConfig;
975
						type AccountIdConverter = xcm_config::LocationToAccountId;
976
						type DeliveryHelper = TestDeliveryHelper;
977
						fn valid_destination() -> Result<Location, BenchmarkError> {
978
							Ok(Location::parent())
979
						}
980
						fn worst_case_holding(_depositable_count: u32) -> XcmAssets {
981
						// 100 fungibles
982
							const HOLDING_FUNGIBLES: u32 = 100;
983
							let fungibles_amount: u128 = 100;
984
							let assets = (0..HOLDING_FUNGIBLES).map(|i| {
985
								let location: Location = GeneralIndex(i as u128).into();
986
								Asset {
987
									id: AssetId(location),
988
									fun: Fungible(fungibles_amount * i as u128),
989
								}
990
								.into()
991
							})
992
							.chain(
993
								core::iter::once(
994
									Asset {
995
										id: AssetId(Location::parent()),
996
										fun: Fungible(u128::MAX)
997
									}
998
								)
999
							)
							.collect::<Vec<_>>();
							for (i, asset) in assets.iter().enumerate() {
								if let Asset {
									id: AssetId(location),
									fun: Fungible(_)
								} = asset {
									EvmForeignAssets::set_asset(
										location.clone(),
										i as u128
									);
									XcmWeightTrader::set_asset_price(
										location.clone(),
										1u128.pow(18)
									);
								}
							}
							assets.into()
						}
					}
					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 worst_case_for_trader() -> Result<(Asset, WeightLimit), 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)
						}
					}
					$($bench_custom)*
					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")
				}
			}
958795
		}
	};
}