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
							let without_base_extrinsic_weight = true;
341

            
342

            
343
							// Estimated encoded transaction size must be based on the heaviest transaction
344
							// type (EIP1559Transaction) to be compatible with all transaction types.
345
							let mut estimated_transaction_len = data.len() +
346
							// pallet ethereum index: 1
347
							// transact call index: 1
348
							// Transaction enum variant: 1
349
							// chain_id 8 bytes
350
							// nonce: 32
351
							// max_priority_fee_per_gas: 32
352
							// max_fee_per_gas: 32
353
							// gas_limit: 32
354
							// action: 21 (enum varianrt + call address)
355
							// value: 32
356
							// access_list: 1 (empty vec size)
357
							// 65 bytes signature
358
							258;
359

            
360
							if access_list.is_some() {
361
								estimated_transaction_len += access_list.encoded_size();
362
							}
363

            
364
							let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
365

            
366
							let (weight_limit, proof_size_base_cost) =
367
								match <Runtime as pallet_evm::Config>::GasWeightMapping::gas_to_weight(
368
									gas_limit,
369
									without_base_extrinsic_weight
370
								) {
371
									weight_limit if weight_limit.proof_size() > 0 => {
372
										(Some(weight_limit), Some(estimated_transaction_len as u64))
373
									}
374
									_ => (None, None),
375
								};
376

            
377
							let _ = <Runtime as pallet_evm::Config>::Runner::call(
378
								from,
379
								to,
380
								data,
381
								value,
382
								gas_limit,
383
								max_fee_per_gas,
384
								max_priority_fee_per_gas,
385
								nonce,
386
								access_list.unwrap_or_default(),
387
								is_transactional,
388
								validate,
389
								weight_limit,
390
								proof_size_base_cost,
391
								<Runtime as pallet_evm::Config>::config(),
392
							);
393
22
						});
394
22
						Ok(())
395
22
					}
396
22
					#[cfg(not(feature = "evm-tracing"))]
397
22
					Err(sp_runtime::DispatchError::Other(
398
22
						"Missing `evm-tracing` compile time feature flag.",
399
22
					))
400
22
				}
401
			}
402

            
403
			impl moonbeam_rpc_primitives_txpool::TxPoolRuntimeApi<Block> for Runtime {
404
22
				fn extrinsic_filter(
405
22
					xts_ready: Vec<<Block as BlockT>::Extrinsic>,
406
22
					xts_future: Vec<<Block as BlockT>::Extrinsic>,
407
22
				) -> TxPoolResponse {
408
22
					TxPoolResponse {
409
22
						ready: xts_ready
410
22
							.into_iter()
411
22
							.filter_map(|xt| match xt.0.function {
412
								RuntimeCall::Ethereum(transact { transaction }) => Some(transaction),
413
								_ => None,
414
22
							})
415
22
							.collect(),
416
22
						future: xts_future
417
22
							.into_iter()
418
22
							.filter_map(|xt| match xt.0.function {
419
								RuntimeCall::Ethereum(transact { transaction }) => Some(transaction),
420
								_ => None,
421
22
							})
422
22
							.collect(),
423
22
					}
424
22
				}
425
			}
426

            
427
			impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {
428
22
				fn chain_id() -> u64 {
429
22
					<Runtime as pallet_evm::Config>::ChainId::get()
430
22
				}
431

            
432
22
				fn account_basic(address: H160) -> EVMAccount {
433
22
					let (account, _) = EVM::account_basic(&address);
434
22
					account
435
22
				}
436

            
437
22
				fn gas_price() -> U256 {
438
22
					let (gas_price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();
439
22
					gas_price
440
22
				}
441

            
442
22
				fn account_code_at(address: H160) -> Vec<u8> {
443
22
					pallet_evm::AccountCodes::<Runtime>::get(address)
444
22
				}
445

            
446
22
				fn author() -> H160 {
447
22
					<pallet_evm::Pallet<Runtime>>::find_author()
448
22
				}
449

            
450
22
				fn storage_at(address: H160, index: U256) -> H256 {
451
22
					let mut tmp = [0u8; 32];
452
22
					index.to_big_endian(&mut tmp);
453
22
					pallet_evm::AccountStorages::<Runtime>::get(address, H256::from_slice(&tmp[..]))
454
22
				}
455

            
456
22
				fn call(
457
22
					from: H160,
458
22
					to: H160,
459
22
					data: Vec<u8>,
460
22
					value: U256,
461
22
					gas_limit: U256,
462
22
					max_fee_per_gas: Option<U256>,
463
22
					max_priority_fee_per_gas: Option<U256>,
464
22
					nonce: Option<U256>,
465
22
					estimate: bool,
466
22
					access_list: Option<Vec<(H160, Vec<H256>)>>,
467
22
				) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {
468
22
					let config = if estimate {
469
						let mut config = <Runtime as pallet_evm::Config>::config().clone();
470
						config.estimate = true;
471
						Some(config)
472
					} else {
473
22
						None
474
					};
475
22
					let is_transactional = false;
476
22
					let validate = true;
477
22

            
478
22
					// Estimated encoded transaction size must be based on the heaviest transaction
479
22
					// type (EIP1559Transaction) to be compatible with all transaction types.
480
22
					let mut estimated_transaction_len = data.len() +
481
22
						// pallet ethereum index: 1
482
22
						// transact call index: 1
483
22
						// Transaction enum variant: 1
484
22
						// chain_id 8 bytes
485
22
						// nonce: 32
486
22
						// max_priority_fee_per_gas: 32
487
22
						// max_fee_per_gas: 32
488
22
						// gas_limit: 32
489
22
						// action: 21 (enum varianrt + call address)
490
22
						// value: 32
491
22
						// access_list: 1 (empty vec size)
492
22
						// 65 bytes signature
493
22
						258;
494
22

            
495
22
					if access_list.is_some() {
496
						estimated_transaction_len += access_list.encoded_size();
497
					}
498

            
499
22
					let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
500
22
					let without_base_extrinsic_weight = true;
501

            
502
22
					let (weight_limit, proof_size_base_cost) =
503
22
						match <Runtime as pallet_evm::Config>::GasWeightMapping::gas_to_weight(
504
22
							gas_limit,
505
22
							without_base_extrinsic_weight
506
22
						) {
507
22
							weight_limit if weight_limit.proof_size() > 0 => {
508
22
								(Some(weight_limit), Some(estimated_transaction_len as u64))
509
							}
510
							_ => (None, None),
511
						};
512

            
513
22
					<Runtime as pallet_evm::Config>::Runner::call(
514
22
						from,
515
22
						to,
516
22
						data,
517
22
						value,
518
22
						gas_limit,
519
22
						max_fee_per_gas,
520
22
						max_priority_fee_per_gas,
521
22
						nonce,
522
22
						access_list.unwrap_or_default(),
523
22
						is_transactional,
524
22
						validate,
525
22
						weight_limit,
526
22
						proof_size_base_cost,
527
22
						config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),
528
22
					).map_err(|err| err.error.into())
529
22
				}
530

            
531
22
				fn create(
532
22
					from: H160,
533
22
					data: Vec<u8>,
534
22
					value: U256,
535
22
					gas_limit: U256,
536
22
					max_fee_per_gas: Option<U256>,
537
22
					max_priority_fee_per_gas: Option<U256>,
538
22
					nonce: Option<U256>,
539
22
					estimate: bool,
540
22
					access_list: Option<Vec<(H160, Vec<H256>)>>,
541
22
				) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {
542
22
					let config = if estimate {
543
						let mut config = <Runtime as pallet_evm::Config>::config().clone();
544
						config.estimate = true;
545
						Some(config)
546
					} else {
547
22
						None
548
					};
549
22
					let is_transactional = false;
550
22
					let validate = true;
551
22

            
552
22
					let mut estimated_transaction_len = data.len() +
553
22
						// from: 20
554
22
						// value: 32
555
22
						// gas_limit: 32
556
22
						// nonce: 32
557
22
						// 1 byte transaction action variant
558
22
						// chain id 8 bytes
559
22
						// 65 bytes signature
560
22
						190;
561
22

            
562
22
					if max_fee_per_gas.is_some() {
563
						estimated_transaction_len += 32;
564
					}
565
22
					if max_priority_fee_per_gas.is_some() {
566
						estimated_transaction_len += 32;
567
					}
568
22
					if access_list.is_some() {
569
						estimated_transaction_len += access_list.encoded_size();
570
					}
571

            
572
22
					let gas_limit = if gas_limit > U256::from(u64::MAX) {
573
						u64::MAX
574
					} else {
575
22
						gas_limit.low_u64()
576
					};
577
22
					let without_base_extrinsic_weight = true;
578

            
579
22
					let (weight_limit, proof_size_base_cost) =
580
22
						match <Runtime as pallet_evm::Config>::GasWeightMapping::gas_to_weight(
581
22
							gas_limit,
582
22
							without_base_extrinsic_weight
583
22
						) {
584
22
							weight_limit if weight_limit.proof_size() > 0 => {
585
22
								(Some(weight_limit), Some(estimated_transaction_len as u64))
586
							}
587
							_ => (None, None),
588
						};
589

            
590
					#[allow(clippy::or_fun_call)] // suggestion not helpful here
591
22
					<Runtime as pallet_evm::Config>::Runner::create(
592
22
						from,
593
22
						data,
594
22
						value,
595
22
						gas_limit,
596
22
						max_fee_per_gas,
597
22
						max_priority_fee_per_gas,
598
22
						nonce,
599
22
						access_list.unwrap_or_default(),
600
22
						is_transactional,
601
22
						validate,
602
22
						weight_limit,
603
22
						proof_size_base_cost,
604
22
						config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),
605
22
					).map_err(|err| err.error.into())
606
22
				}
607

            
608
22
				fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {
609
22
					pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
610
22
				}
611

            
612
22
				fn current_block() -> Option<pallet_ethereum::Block> {
613
22
					pallet_ethereum::CurrentBlock::<Runtime>::get()
614
22
				}
615

            
616
22
				fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {
617
22
					pallet_ethereum::CurrentReceipts::<Runtime>::get()
618
22
				}
619

            
620
				fn current_all() -> (
621
					Option<pallet_ethereum::Block>,
622
					Option<Vec<pallet_ethereum::Receipt>>,
623
					Option<Vec<TransactionStatus>>,
624
				) {
625
					(
626
						pallet_ethereum::CurrentBlock::<Runtime>::get(),
627
						pallet_ethereum::CurrentReceipts::<Runtime>::get(),
628
						pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get(),
629
					)
630
				}
631

            
632
				fn extrinsic_filter(
633
					xts: Vec<<Block as BlockT>::Extrinsic>,
634
				) -> Vec<EthereumTransaction> {
635
					xts.into_iter().filter_map(|xt| match xt.0.function {
636
						RuntimeCall::Ethereum(transact { transaction }) => Some(transaction),
637
						_ => None
638
					}).collect::<Vec<EthereumTransaction>>()
639
				}
640

            
641
				fn elasticity() -> Option<Permill> {
642
					None
643
				}
644

            
645
				fn gas_limit_multiplier_support() {}
646

            
647
				fn pending_block(
648
					xts: Vec<<Block as sp_runtime::traits::Block>::Extrinsic>
649
				) -> (
650
					Option<pallet_ethereum::Block>, Option<sp_std::prelude::Vec<TransactionStatus>>
651
				) {
652
					for ext in xts.into_iter() {
653
						let _ = Executive::apply_extrinsic(ext);
654
					}
655

            
656
					Ethereum::on_finalize(System::block_number() + 1);
657

            
658
					(
659
						pallet_ethereum::CurrentBlock::<Runtime>::get(),
660
						pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
661
					)
662
				 }
663

            
664
				fn initialize_pending_block(header: &<Block as BlockT>::Header) {
665
					pallet_randomness::vrf::using_fake_vrf(|| {
666
						let _ = Executive::initialize_block(header);
667
					})
668
				}
669
			}
670

            
671
			impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {
672
				fn convert_transaction(
673
					transaction: pallet_ethereum::Transaction
674
				) -> <Block as BlockT>::Extrinsic {
675
					UncheckedExtrinsic::new_unsigned(
676
						pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
677
					)
678
				}
679
			}
680

            
681
			impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
682
			for Runtime {
683
				fn query_info(
684
					uxt: <Block as BlockT>::Extrinsic,
685
					len: u32,
686
				) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
687
					TransactionPayment::query_info(uxt, len)
688
				}
689

            
690
				fn query_fee_details(
691
					uxt: <Block as BlockT>::Extrinsic,
692
					len: u32,
693
				) -> pallet_transaction_payment::FeeDetails<Balance> {
694
					TransactionPayment::query_fee_details(uxt, len)
695
				}
696

            
697
				fn query_weight_to_fee(weight: Weight) -> Balance {
698
					TransactionPayment::weight_to_fee(weight)
699
				}
700

            
701
				fn query_length_to_fee(length: u32) -> Balance {
702
					TransactionPayment::length_to_fee(length)
703
				}
704
			}
705

            
706
			impl nimbus_primitives::NimbusApi<Block> for Runtime {
707
66
				fn can_author(
708
66
					author: nimbus_primitives::NimbusId,
709
66
					slot: u32,
710
66
					parent_header: &<Block as BlockT>::Header
711
66
				) -> bool {
712
66
					use pallet_parachain_staking::Config as PalletParachainStakingConfig;
713
66

            
714
66
					let block_number = parent_header.number + 1;
715
66

            
716
66
					// The Moonbeam runtimes use an entropy source that needs to do some accounting
717
66
					// work during block initialization. Therefore we initialize it here to match
718
66
					// the state it will be in when the next block is being executed.
719
66
					use frame_support::traits::OnInitialize;
720
66
					System::initialize(
721
66
						&block_number,
722
66
						&parent_header.hash(),
723
66
						&parent_header.digest,
724
66
					);
725
66

            
726
66
					// Because the staking solution calculates the next staking set at the beginning
727
66
					// of the first block in the new round, the only way to accurately predict the
728
66
					// authors is to compute the selection during prediction.
729
66
					if pallet_parachain_staking::Pallet::<Self>::round()
730
66
						.should_update(block_number) {
731
						// get author account id
732
						use nimbus_primitives::AccountLookup;
733
						let author_account_id = if let Some(account) =
734
							pallet_author_mapping::Pallet::<Self>::lookup_account(&author) {
735
							account
736
						} else {
737
							// return false if author mapping not registered like in can_author impl
738
							return false
739
						};
740
						let candidates = pallet_parachain_staking::Pallet::<Self>::compute_top_candidates();
741
						if candidates.is_empty() {
742
							// If there are zero selected candidates, we use the same eligibility
743
							// as the previous round
744
							return AuthorInherent::can_author(&author, &slot);
745
						}
746

            
747
						// predict eligibility post-selection by computing selection results now
748
						let (eligible, _) =
749
							pallet_author_slot_filter::compute_pseudo_random_subset::<Self>(
750
								candidates,
751
								&slot
752
							);
753
						eligible.contains(&author_account_id)
754
					} else {
755
66
						AuthorInherent::can_author(&author, &slot)
756
					}
757
				}
758
			}
759

            
760
			impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
761
				fn collect_collation_info(
762
					header: &<Block as BlockT>::Header
763
				) -> cumulus_primitives_core::CollationInfo {
764
					ParachainSystem::collect_collation_info(header)
765
				}
766
			}
767

            
768
			impl session_keys_primitives::VrfApi<Block> for Runtime {
769
				fn get_last_vrf_output() -> Option<<Block as BlockT>::Hash> {
770
					// TODO: remove in future runtime upgrade along with storage item
771
					if pallet_randomness::Pallet::<Self>::not_first_block().is_none() {
772
						return None;
773
					}
774
					pallet_randomness::Pallet::<Self>::local_vrf_output()
775
				}
776
				fn vrf_key_lookup(
777
					nimbus_id: nimbus_primitives::NimbusId
778
				) -> Option<session_keys_primitives::VrfId> {
779
					use session_keys_primitives::KeysLookup;
780
					AuthorMapping::lookup_keys(&nimbus_id)
781
				}
782
			}
783

            
784
			impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
785
				fn query_acceptable_payment_assets(
786
					xcm_version: xcm::Version
787
				) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
788
					XcmWeightTrader::query_acceptable_payment_assets(xcm_version)
789
				}
790

            
791
				fn query_weight_to_asset_fee(
792
					weight: Weight, asset: VersionedAssetId
793
				) -> Result<u128, XcmPaymentApiError> {
794
					XcmWeightTrader::query_weight_to_asset_fee(weight, asset)
795
				}
796

            
797
				fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
798
					PolkadotXcm::query_xcm_weight(message)
799
				}
800

            
801
				fn query_delivery_fees(
802
					destination: VersionedLocation, message: VersionedXcm<()>
803
				) -> Result<VersionedAssets, XcmPaymentApiError> {
804
					PolkadotXcm::query_delivery_fees(destination, message)
805
				}
806
			}
807

            
808
			impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller>
809
				for Runtime {
810
					fn dry_run_call(
811
						origin: OriginCaller,
812
						call: RuntimeCall
813
					) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
814
						PolkadotXcm::dry_run_call::<
815
							Runtime,
816
							xcm_config::XcmRouter,
817
							OriginCaller,
818
							RuntimeCall>(origin, call)
819
					}
820

            
821
					fn dry_run_xcm(
822
						origin_location: VersionedLocation,
823
						xcm: VersionedXcm<RuntimeCall>
824
					) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
825
						PolkadotXcm::dry_run_xcm::<
826
							Runtime,
827
							xcm_config::XcmRouter,
828
							RuntimeCall,
829
							xcm_config::XcmExecutorConfig>(origin_location, xcm)
830
					}
831
				}
832

            
833
			impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
834
				fn convert_location(location: VersionedLocation) -> Result<
835
					AccountId,
836
					xcm_runtime_apis::conversions::Error
837
				> {
838
					xcm_runtime_apis::conversions::LocationToAccountHelper::<
839
						AccountId,
840
						xcm_config::LocationToAccountId,
841
					>::convert_location(location)
842
				}
843
			}
844

            
845
			#[cfg(feature = "runtime-benchmarks")]
846
			impl frame_benchmarking::Benchmark<Block> for Runtime {
847

            
848
				fn benchmark_metadata(extra: bool) -> (
849
					Vec<frame_benchmarking::BenchmarkList>,
850
					Vec<frame_support::traits::StorageInfo>,
851
				) {
852
					use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};
853
					use frame_system_benchmarking::Pallet as SystemBench;
854
					use moonbeam_xcm_benchmarks::generic::benchmarking as MoonbeamXcmBenchmarks;
855
					use frame_support::traits::StorageInfoTrait;
856
					use MoonbeamXcmBenchmarks::XcmGenericBenchmarks as MoonbeamXcmGenericBench;
857

            
858
					use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
859

            
860
					let mut list = Vec::<BenchmarkList>::new();
861
					list_benchmarks!(list, extra);
862

            
863
					let storage_info = AllPalletsWithSystem::storage_info();
864

            
865
					return (list, storage_info)
866
				}
867

            
868
				fn dispatch_benchmark(
869
					config: frame_benchmarking::BenchmarkConfig,
870
				) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
871
					use frame_benchmarking::{add_benchmark, BenchmarkBatch, Benchmarking};
872
					use frame_support::traits::TrackedStorageKey;
873
					use cumulus_primitives_core::ParaId;
874

            
875
					use xcm::latest::prelude::{
876
						GeneralIndex, Junction, Junctions, Location, Response, NetworkId, AssetId,
877
						Assets as XcmAssets, Fungible, Asset, ParentThen, Parachain, Parent
878
					};
879
					use xcm_config::SelfReserve;
880
					use frame_benchmarking::BenchmarkError;
881

            
882
					use frame_system_benchmarking::Pallet as SystemBench;
883
					// Needed to run `set_code` and `apply_authorized_upgrade` frame_system benchmarks
884
					// https://github.com/paritytech/cumulus/pull/2766
885
					impl frame_system_benchmarking::Config for Runtime {
886
						fn setup_set_code_requirements(code: &Vec<u8>) -> Result<(), BenchmarkError> {
887
							ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
888
							Ok(())
889
						}
890

            
891
						fn verify_set_code() {
892
							System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
893
						}
894
					}
895

            
896
					impl moonbeam_xcm_benchmarks::Config for Runtime {}
897
					impl moonbeam_xcm_benchmarks::generic::Config for Runtime {}
898

            
899
					use pallet_asset_manager::Config as PalletAssetManagerConfig;
900

            
901
					use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
902
					parameter_types! {
903
						pub const RandomParaId: ParaId = ParaId::new(43211234);
904
					}
905

            
906
					pub struct TestDeliveryHelper;
907
					impl xcm_builder::EnsureDelivery for TestDeliveryHelper {
908
						fn ensure_successful_delivery(
909
							origin_ref: &Location,
910
							_dest: &Location,
911
							_fee_reason: xcm_executor::traits::FeeReason,
912
						) -> (Option<xcm_executor::FeesMode>, Option<XcmAssets>) {
913
							use xcm_executor::traits::ConvertLocation;
914
							let account = xcm_config::LocationToH160::convert_location(origin_ref)
915
								.expect("Invalid location");
916
							// Give the existential deposit at least
917
							let balance = ExistentialDeposit::get();
918
							let _ = <Balances as frame_support::traits::Currency<_>>::
919
								make_free_balance_be(&account.into(), balance);
920

            
921
							(None, None)
922
						}
923
					}
924

            
925
					impl pallet_xcm::benchmarking::Config for Runtime {
926
				        type DeliveryHelper = TestDeliveryHelper;
927

            
928
						fn get_asset() -> Asset {
929
							Asset {
930
								id: AssetId(SelfReserve::get()),
931
								fun: Fungible(ExistentialDeposit::get()),
932
							}
933
						}
934

            
935
						fn reachable_dest() -> Option<Location> {
936
							Some(Parent.into())
937
						}
938

            
939
						fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
940
							None
941
						}
942

            
943
						fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
944
							use xcm_config::SelfReserve;
945

            
946
							ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
947
								RandomParaId::get().into()
948
							);
949

            
950
							Some((
951
								Asset {
952
									fun: Fungible(ExistentialDeposit::get()),
953
									id: AssetId(SelfReserve::get().into())
954
								},
955
								// Moonbeam can reserve transfer native token to
956
								// some random parachain.
957
								ParentThen(Parachain(RandomParaId::get().into()).into()).into(),
958
							))
959
						}
960

            
961
						fn set_up_complex_asset_transfer(
962
						) -> Option<(XcmAssets, u32, Location, Box<dyn FnOnce()>)> {
963
							use xcm_config::SelfReserve;
964

            
965
							let destination: xcm::v4::Location = Parent.into();
966

            
967
							let fee_amount: u128 = <Runtime as pallet_balances::Config>::ExistentialDeposit::get();
968
							let fee_asset: Asset = (SelfReserve::get(), fee_amount).into();
969

            
970
							// Give some multiple of transferred amount
971
							let balance = fee_amount * 1000;
972
							let who = frame_benchmarking::whitelisted_caller();
973
							let _ =
974
								<Balances as frame_support::traits::Currency<_>>::make_free_balance_be(&who, balance);
975

            
976
							// verify initial balance
977
							assert_eq!(Balances::free_balance(&who), balance);
978

            
979
							// set up local asset
980
							let asset_amount: u128 = 10u128;
981
							let initial_asset_amount: u128 = asset_amount * 10;
982

            
983
							let (asset_id, _, _) = pallet_assets::benchmarking::create_default_minted_asset::<
984
								Runtime,
985
								()
986
							>(true, initial_asset_amount);
987
							let transfer_asset: Asset = (SelfReserve::get(), asset_amount).into();
988

            
989
							let assets: XcmAssets = vec![fee_asset.clone(), transfer_asset].into();
990
							let fee_index: u32 = 0;
991

            
992
							let verify: Box<dyn FnOnce()> = Box::new(move || {
993
								// verify balance after transfer, decreased by
994
								// transferred amount (and delivery fees)
995
								assert!(Balances::free_balance(&who) <= balance - fee_amount);
996
							});
997

            
998
							Some((assets, fee_index, destination, verify))
999
						}
					}
					impl pallet_xcm_benchmarks::Config for Runtime {
						type XcmConfig = xcm_config::XcmExecutorConfig;
						type AccountIdConverter = xcm_config::LocationToAccountId;
						type DeliveryHelper = ();
						fn valid_destination() -> Result<Location, BenchmarkError> {
							Ok(Location::parent())
						}
						fn worst_case_holding(_depositable_count: u32) -> XcmAssets {
						// 100 fungibles
							const HOLDING_FUNGIBLES: u32 = 100;
							let fungibles_amount: u128 = 100;
							let assets = (0..HOLDING_FUNGIBLES).map(|i| {
								let location: Location = GeneralIndex(i as u128).into();
								Asset {
									id: AssetId(location),
									fun: Fungible(fungibles_amount * i as u128),
								}
								.into()
							})
							.chain(
								core::iter::once(
									Asset {
										id: AssetId(Location::parent()),
										fun: Fungible(u128::MAX)
									}
								)
							)
							.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 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")
				}
			}
		}
	};
}