Skip to main content

revive_dev_runtime/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18#![cfg_attr(not(feature = "std"), no_std)]
19
20// Make the WASM binary available.
21#[cfg(feature = "std")]
22include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
23
24extern crate alloc;
25
26use alloc::{vec, vec::Vec};
27use currency::*;
28use frame_support::weights::{
29	constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_REF_TIME_PER_SECOND},
30	Weight,
31};
32use frame_system::limits::BlockWeights;
33use pallet_revive::{
34	evm::{
35		fees::{BlockRatioFee, Info as FeeInfo},
36		runtime::EthExtra,
37	},
38	AccountId32Mapper,
39};
40use pallet_transaction_payment::{ConstFeeMultiplier, FeeDetails, Multiplier, RuntimeDispatchInfo};
41use polkadot_sdk::{
42	polkadot_sdk_frame::{
43		deps::sp_genesis_builder,
44		runtime::{apis, prelude::*},
45		traits::Block as BlockT,
46	},
47	*,
48};
49use sp_weights::ConstantMultiplier;
50
51pub use polkadot_sdk::{
52	parachains_common::{AccountId, Balance, BlockNumber, Hash, Header, Nonce, Signature},
53	polkadot_sdk_frame::runtime::types_common::OpaqueBlock,
54};
55
56pub mod currency {
57	use super::Balance;
58	pub const DOLLARS: Balance = 1_000_000_000_000;
59	pub const CENTS: Balance = DOLLARS / 100;
60	pub const MILLICENTS: Balance = CENTS / 1_000;
61}
62
63/// Provides getters for genesis configuration presets.
64pub mod genesis_config_presets {
65	use super::*;
66	use crate::{
67		currency::DOLLARS, sp_keyring::Sr25519Keyring, Balance, BalancesConfig, ReviveConfig,
68		RuntimeGenesisConfig, SudoConfig,
69	};
70
71	use alloc::{vec, vec::Vec};
72	use pallet_revive::is_eth_derived;
73	use serde_json::Value;
74
75	pub const ENDOWMENT: Balance = 10_000_000_000_001 * DOLLARS;
76
77	fn well_known_accounts() -> Vec<AccountId> {
78		Sr25519Keyring::well_known()
79			.map(|k| k.to_account_id())
80			.chain([
81				// subxt_signer::eth::dev::alith()
82				array_bytes::hex_n_into_unchecked(
83					"f24ff3a9cf04c71dbc94d0b566f7a27b94566caceeeeeeeeeeeeeeeeeeeeeeee",
84				),
85				// subxt_signer::eth::dev::baltathar()
86				array_bytes::hex_n_into_unchecked(
87					"3cd0a705a2dc65e5b1e1205896baa2be8a07c6e0eeeeeeeeeeeeeeeeeeeeeeee",
88				),
89				// subxt_signer::eth::dev::charleth()
90				array_bytes::hex_n_into_unchecked(
91					"798d4ba9baf0064ec19eb4f0a1a45785ae9d6dfceeeeeeeeeeeeeeeeeeeeeeee",
92				),
93				// subxt_signer::eth::dev::dorothy()
94				array_bytes::hex_n_into_unchecked(
95					"773539d4ac0e786233d90a233654ccee26a613d9eeeeeeeeeeeeeeeeeeeeeeee",
96				),
97				// subxt_signer::eth::dev::ethan()
98				array_bytes::hex_n_into_unchecked(
99					"ff64d3f6efe2317ee2807d223a0bdc4c0c49dfdbeeeeeeeeeeeeeeeeeeeeeeee",
100				),
101			])
102			.collect::<Vec<_>>()
103	}
104
105	/// Returns a development genesis config preset.
106	pub fn development_config_genesis() -> Value {
107		let endowed_accounts = well_known_accounts();
108		frame_support::build_struct_json_patch!(RuntimeGenesisConfig {
109			balances: BalancesConfig {
110				balances: endowed_accounts
111					.iter()
112					.cloned()
113					.map(|id| (id, ENDOWMENT))
114					.collect::<Vec<_>>(),
115			},
116			sudo: SudoConfig { key: Some(Sr25519Keyring::Alice.to_account_id()) },
117			revive: ReviveConfig {
118				mapped_accounts: endowed_accounts
119					.iter()
120					.filter(|x| !is_eth_derived(x))
121					.cloned()
122					.collect(),
123			},
124		})
125	}
126
127	/// Get the set of the available genesis config presets.
128	pub fn get_preset(id: &PresetId) -> Option<Vec<u8>> {
129		let patch = match id.as_ref() {
130			sp_genesis_builder::DEV_RUNTIME_PRESET => development_config_genesis(),
131			_ => return None,
132		};
133		Some(
134			serde_json::to_string(&patch)
135				.expect("serialization to json is expected to work. qed.")
136				.into_bytes(),
137		)
138	}
139
140	/// List of supported presets.
141	pub fn preset_names() -> Vec<PresetId> {
142		vec![PresetId::from(sp_genesis_builder::DEV_RUNTIME_PRESET)]
143	}
144}
145
146/// The runtime version.
147#[runtime_version]
148pub const VERSION: RuntimeVersion = RuntimeVersion {
149	spec_name: alloc::borrow::Cow::Borrowed("revive-dev-runtime"),
150	impl_name: alloc::borrow::Cow::Borrowed("revive-dev-runtime"),
151	authoring_version: 1,
152	spec_version: 0,
153	impl_version: 1,
154	apis: RUNTIME_API_VERSIONS,
155	transaction_version: 1,
156	system_version: 1,
157};
158
159/// The version information used to identify this runtime when compiled natively.
160#[cfg(feature = "std")]
161pub fn native_version() -> NativeVersion {
162	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
163}
164
165/// The address format for describing accounts.
166pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
167/// Block type as expected by this runtime.
168pub type Block = sp_runtime::generic::Block<Header, UncheckedExtrinsic>;
169/// The transaction extensions that are added to the runtime.
170type TxExtension = (
171	// Checks that the sender is not the zero address.
172	frame_system::CheckNonZeroSender<Runtime>,
173	// Checks that the runtime version is correct.
174	frame_system::CheckSpecVersion<Runtime>,
175	// Checks that the transaction version is correct.
176	frame_system::CheckTxVersion<Runtime>,
177	// Checks that the genesis hash is correct.
178	frame_system::CheckGenesis<Runtime>,
179	// Checks that the era is valid.
180	frame_system::CheckEra<Runtime>,
181	// Checks that the nonce is valid.
182	frame_system::CheckNonce<Runtime>,
183	// Checks that the weight is valid.
184	frame_system::CheckWeight<Runtime>,
185	// Ensures that the sender has enough funds to pay for the transaction
186	// and deducts the fee from the sender's account.
187	pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
188	// Needs to be done after all extensions that rely on a signed origin.
189	pallet_revive::evm::tx_extension::SetOrigin<Runtime>,
190	// Reclaim the unused weight from the block using post dispatch information.
191	// It must be last in the pipeline in order to catch the refund in previous transaction
192	// extensions
193	frame_system::WeightReclaim<Runtime>,
194);
195
196/// Default extensions applied to Ethereum transactions.
197#[derive(Clone, PartialEq, Eq, Debug)]
198pub struct EthExtraImpl;
199
200impl EthExtra for EthExtraImpl {
201	type Config = Runtime;
202	type Extension = TxExtension;
203
204	fn get_eth_extension(nonce: u32, tip: Balance) -> Self::Extension {
205		(
206			frame_system::CheckNonZeroSender::<Runtime>::new(),
207			frame_system::CheckSpecVersion::<Runtime>::new(),
208			frame_system::CheckTxVersion::<Runtime>::new(),
209			frame_system::CheckGenesis::<Runtime>::new(),
210			frame_system::CheckMortality::from(sp_runtime::generic::Era::Immortal),
211			frame_system::CheckNonce::<Runtime>::from(nonce),
212			frame_system::CheckWeight::<Runtime>::new(),
213			pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
214			pallet_revive::evm::tx_extension::SetOrigin::<Runtime>::new_from_eth_transaction(),
215			frame_system::WeightReclaim::<Runtime>::new(),
216		)
217	}
218}
219
220pub type UncheckedExtrinsic =
221	pallet_revive::evm::runtime::UncheckedExtrinsic<Address, Signature, EthExtraImpl>;
222
223type Executive = frame_executive::Executive<
224	Runtime,
225	Block,
226	frame_system::ChainContext<Runtime>,
227	Runtime,
228	AllPalletsWithSystem,
229>;
230
231// Composes the runtime by adding all the used pallets and deriving necessary types.
232#[frame_construct_runtime]
233mod runtime {
234	/// The main runtime type.
235	#[runtime::runtime]
236	#[runtime::derive(
237		RuntimeCall,
238		RuntimeEvent,
239		RuntimeError,
240		RuntimeOrigin,
241		RuntimeFreezeReason,
242		RuntimeHoldReason,
243		RuntimeSlashReason,
244		RuntimeLockId,
245		RuntimeTask,
246		RuntimeViewFunction
247	)]
248	pub struct Runtime;
249
250	/// Mandatory system pallet that should always be included in a FRAME runtime.
251	#[runtime::pallet_index(0)]
252	pub type System = frame_system::Pallet<Runtime>;
253
254	/// Provides a way for consensus systems to set and check the onchain time.
255	#[runtime::pallet_index(1)]
256	pub type Timestamp = pallet_timestamp::Pallet<Runtime>;
257
258	/// Provides the ability to keep track of balances.
259	#[runtime::pallet_index(2)]
260	pub type Balances = pallet_balances::Pallet<Runtime>;
261
262	/// Provides a way to execute privileged functions.
263	#[runtime::pallet_index(3)]
264	pub type Sudo = pallet_sudo::Pallet<Runtime>;
265
266	/// Provides the ability to charge for extrinsic execution.
267	#[runtime::pallet_index(4)]
268	pub type TransactionPayment = pallet_transaction_payment::Pallet<Runtime>;
269
270	/// Provides the ability to execute Smart Contracts.
271	#[runtime::pallet_index(5)]
272	pub type Revive = pallet_revive::Pallet<Runtime>;
273}
274
275/// We assume that ~10% of the block weight is consumed by `on_initialize` handlers.
276/// This is used to limit the maximal weight of a single extrinsic.
277const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);
278/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used
279/// by  Operational  extrinsics.
280const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
281/// We allow for 2 seconds of compute with a 6 second average block time, with maximum proof size.
282const MAXIMUM_BLOCK_WEIGHT: Weight =
283	Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), u64::MAX);
284
285parameter_types! {
286	pub const Version: RuntimeVersion = VERSION;
287	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
288		.base_block(BlockExecutionWeight::get())
289		.for_class(DispatchClass::all(), |weights| {
290			weights.base_extrinsic = ExtrinsicBaseWeight::get();
291		})
292		.for_class(DispatchClass::Normal, |weights| {
293			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
294		})
295		.for_class(DispatchClass::Operational, |weights| {
296			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
297			// Operational transactions have some extra reserved space, so that they
298			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
299			weights.reserved = Some(
300				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
301			);
302		})
303		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
304		.build_or_panic();
305}
306
307/// Implements the types required for the system pallet.
308#[derive_impl(frame_system::config_preludes::SolochainDefaultConfig)]
309impl frame_system::Config for Runtime {
310	type Block = Block;
311	type Version = Version;
312	type AccountId = AccountId;
313	type Hash = Hash;
314	type Nonce = Nonce;
315	type AccountData = pallet_balances::AccountData<<Runtime as pallet_balances::Config>::Balance>;
316}
317
318parameter_types! {
319	pub const ExistentialDeposit: Balance = CENTS;
320}
321
322// Implements the types required for the balances pallet.
323#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
324impl pallet_balances::Config for Runtime {
325	type AccountStore = System;
326	type Balance = Balance;
327	type ExistentialDeposit = ExistentialDeposit;
328}
329
330// Implements the types required for the sudo pallet.
331#[derive_impl(pallet_sudo::config_preludes::TestDefaultConfig)]
332impl pallet_sudo::Config for Runtime {}
333
334// Implements the types required for the sudo pallet.
335#[derive_impl(pallet_timestamp::config_preludes::TestDefaultConfig)]
336impl pallet_timestamp::Config for Runtime {}
337
338parameter_types! {
339	pub const TransactionByteFee: Balance = 10 * MILLICENTS;
340	pub FeeMultiplier: Multiplier = Multiplier::one();
341}
342
343// Implements the types required for the transaction payment pallet.
344#[derive_impl(pallet_transaction_payment::config_preludes::TestDefaultConfig)]
345impl pallet_transaction_payment::Config for Runtime {
346	type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, ()>;
347	type WeightToFee = BlockRatioFee<1, 1, Self, Balance>;
348	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
349	type FeeMultiplierUpdate = ConstFeeMultiplier<FeeMultiplier>;
350}
351
352parameter_types! {
353	pub CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(30);
354}
355
356#[derive_impl(pallet_revive::config_preludes::TestDefaultConfig)]
357impl pallet_revive::Config for Runtime {
358	type AddressMapper = AccountId32Mapper<Self>;
359	type ChainId = ConstU64<420_420_420>;
360	type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
361	type Balance = Balance;
362	type Currency = Balances;
363	type NativeToEthRatio = ConstU32<1_000_000>;
364	type UploadOrigin = EnsureSigned<Self::AccountId>;
365	type InstantiateOrigin = EnsureSigned<Self::AccountId>;
366	type Time = Timestamp;
367	type FeeInfo = FeeInfo<Address, Signature, EthExtraImpl>;
368	type DebugEnabled = ConstBool<true>;
369	type GasScale = ConstU32<50000>;
370}
371
372pallet_revive::impl_runtime_apis_plus_revive_traits!(
373	Runtime,
374	Revive,
375	Executive,
376	EthExtraImpl,
377
378	impl apis::Core<Block> for Runtime {
379		fn version() -> RuntimeVersion {
380			VERSION
381		}
382
383		fn execute_block(block: <Block as BlockT>::LazyBlock) {
384			Executive::execute_block(block)
385		}
386
387		fn initialize_block(header: &Header) -> ExtrinsicInclusionMode {
388			Executive::initialize_block(header)
389		}
390	}
391
392	impl apis::Metadata<Block> for Runtime {
393		fn metadata() -> OpaqueMetadata {
394			OpaqueMetadata::new(Runtime::metadata().into())
395		}
396
397		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
398			Runtime::metadata_at_version(version)
399		}
400
401		fn metadata_versions() -> Vec<u32> {
402			Runtime::metadata_versions()
403		}
404	}
405
406	impl apis::BlockBuilder<Block> for Runtime {
407		fn apply_extrinsic(extrinsic: ExtrinsicFor<Runtime>) -> ApplyExtrinsicResult {
408			Executive::apply_extrinsic(extrinsic)
409		}
410
411		fn finalize_block() -> HeaderFor<Runtime> {
412			Executive::finalize_block()
413		}
414
415		fn inherent_extrinsics(data: InherentData) -> Vec<ExtrinsicFor<Runtime>> {
416			data.create_extrinsics()
417		}
418
419		fn check_inherents(
420			block: <Block as BlockT>::LazyBlock,
421			data: InherentData,
422		) -> CheckInherentsResult {
423			data.check_extrinsics(&block)
424		}
425	}
426
427	impl apis::TaggedTransactionQueue<Block> for Runtime {
428		fn validate_transaction(
429			source: TransactionSource,
430			tx: ExtrinsicFor<Runtime>,
431			block_hash: <Runtime as frame_system::Config>::Hash,
432		) -> TransactionValidity {
433			Executive::validate_transaction(source, tx, block_hash)
434		}
435	}
436
437	impl apis::OffchainWorkerApi<Block> for Runtime {
438		fn offchain_worker(header: &HeaderFor<Runtime>) {
439			Executive::offchain_worker(header)
440		}
441	}
442
443	impl apis::SessionKeys<Block> for Runtime {
444		fn generate_session_keys(_owner: Vec<u8>, _seed: Option<Vec<u8>>) -> apis::OpaqueGeneratedSessionKeys {
445		Default::default()
446		}
447
448
449		fn decode_session_keys(
450			_encoded: Vec<u8>,
451		) -> Option<Vec<(Vec<u8>, apis::KeyTypeId)>> {
452			Default::default()
453		}
454	}
455
456	impl apis::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
457		fn account_nonce(account: AccountId) -> Nonce {
458			System::account_nonce(account)
459		}
460	}
461
462	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
463		Block,
464		Balance,
465	> for Runtime {
466		fn query_info(uxt: ExtrinsicFor<Runtime>, len: u32) -> RuntimeDispatchInfo<Balance> {
467			TransactionPayment::query_info(uxt, len)
468		}
469		fn query_fee_details(uxt: ExtrinsicFor<Runtime>, len: u32) -> FeeDetails<Balance> {
470			TransactionPayment::query_fee_details(uxt, len)
471		}
472		fn query_weight_to_fee(weight: Weight) -> Balance {
473			TransactionPayment::weight_to_fee(weight)
474		}
475		fn query_length_to_fee(length: u32) -> Balance {
476			TransactionPayment::length_to_fee(length)
477		}
478	}
479
480	impl apis::GenesisBuilder<Block> for Runtime {
481		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
482			build_state::<RuntimeGenesisConfig>(config)
483		}
484
485		fn get_preset(id: &Option<PresetId>) -> Option<Vec<u8>> {
486			get_preset::<RuntimeGenesisConfig>(id, self::genesis_config_presets::get_preset)
487		}
488
489		fn preset_names() -> Vec<PresetId> {
490			self::genesis_config_presets::preset_names()
491		}
492	}
493);