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::AddressMapper;
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| !<Runtime as pallet_revive::Config>::AddressMapper::is_mapped(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 address format for describing accounts.
160pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
161/// Block type as expected by this runtime.
162pub type Block = sp_runtime::generic::Block<Header, UncheckedExtrinsic>;
163/// The transaction extensions that are added to the runtime.
164type TxExtension = (
165	// Checks that the sender is not the zero address.
166	frame_system::CheckNonZeroSender<Runtime>,
167	// Checks that the runtime version is correct.
168	frame_system::CheckSpecVersion<Runtime>,
169	// Checks that the transaction version is correct.
170	frame_system::CheckTxVersion<Runtime>,
171	// Checks that the genesis hash is correct.
172	frame_system::CheckGenesis<Runtime>,
173	// Checks that the era is valid.
174	frame_system::CheckEra<Runtime>,
175	// Checks that the nonce is valid.
176	frame_system::CheckNonce<Runtime>,
177	// Checks that the weight is valid.
178	frame_system::CheckWeight<Runtime>,
179	// Ensures that the sender has enough funds to pay for the transaction
180	// and deducts the fee from the sender's account.
181	pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
182	// Needs to be done after all extensions that rely on a signed origin.
183	pallet_revive::evm::tx_extension::SetOrigin<Runtime>,
184	// Reclaim the unused weight from the block using post dispatch information.
185	// It must be last in the pipeline in order to catch the refund in previous transaction
186	// extensions
187	frame_system::WeightReclaim<Runtime>,
188);
189
190/// Default extensions applied to Ethereum transactions.
191#[derive(Clone, PartialEq, Eq, Debug)]
192pub struct EthExtraImpl;
193
194impl EthExtra for EthExtraImpl {
195	type Config = Runtime;
196	type ExtensionV0 = TxExtension;
197	type ExtensionOtherVersions = sp_runtime::traits::InvalidVersion;
198
199	fn get_eth_extension(nonce: u32, tip: Balance) -> Self::ExtensionV0 {
200		(
201			frame_system::CheckNonZeroSender::<Runtime>::new(),
202			frame_system::CheckSpecVersion::<Runtime>::new(),
203			frame_system::CheckTxVersion::<Runtime>::new(),
204			frame_system::CheckGenesis::<Runtime>::new(),
205			frame_system::CheckMortality::from(sp_runtime::generic::Era::Immortal),
206			frame_system::CheckNonce::<Runtime>::from(nonce),
207			frame_system::CheckWeight::<Runtime>::new(),
208			pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
209			pallet_revive::evm::tx_extension::SetOrigin::<Runtime>::new_from_eth_transaction(),
210			frame_system::WeightReclaim::<Runtime>::new(),
211		)
212	}
213}
214
215pub type UncheckedExtrinsic =
216	pallet_revive::evm::runtime::UncheckedExtrinsic<Address, Signature, EthExtraImpl>;
217
218type Executive = frame_executive::Executive<
219	Runtime,
220	Block,
221	frame_system::ChainContext<Runtime>,
222	Runtime,
223	AllPalletsWithSystem,
224>;
225
226// Composes the runtime by adding all the used pallets and deriving necessary types.
227#[frame_construct_runtime]
228mod runtime {
229	/// The main runtime type.
230	#[runtime::runtime]
231	#[runtime::derive(
232		RuntimeCall,
233		RuntimeEvent,
234		RuntimeError,
235		RuntimeOrigin,
236		RuntimeFreezeReason,
237		RuntimeHoldReason,
238		RuntimeSlashReason,
239		RuntimeLockId,
240		RuntimeTask,
241		RuntimeViewFunction
242	)]
243	pub struct Runtime;
244
245	/// Mandatory system pallet that should always be included in a FRAME runtime.
246	#[runtime::pallet_index(0)]
247	pub type System = frame_system::Pallet<Runtime>;
248
249	/// Provides a way for consensus systems to set and check the onchain time.
250	#[runtime::pallet_index(1)]
251	pub type Timestamp = pallet_timestamp::Pallet<Runtime>;
252
253	/// Provides the ability to keep track of balances.
254	#[runtime::pallet_index(2)]
255	pub type Balances = pallet_balances::Pallet<Runtime>;
256
257	/// Provides a way to execute privileged functions.
258	#[runtime::pallet_index(3)]
259	pub type Sudo = pallet_sudo::Pallet<Runtime>;
260
261	/// Provides the ability to charge for extrinsic execution.
262	#[runtime::pallet_index(4)]
263	pub type TransactionPayment = pallet_transaction_payment::Pallet<Runtime>;
264
265	/// Provides the ability to execute Smart Contracts.
266	#[runtime::pallet_index(5)]
267	pub type Revive = pallet_revive::Pallet<Runtime>;
268}
269
270/// We assume that ~10% of the block weight is consumed by `on_initialize` handlers.
271/// This is used to limit the maximal weight of a single extrinsic.
272const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);
273/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used
274/// by  Operational  extrinsics.
275const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
276/// We allow for 2 seconds of compute with a 6 second average block time, with maximum proof size.
277const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
278	WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
279	polkadot_primitives::MAX_POV_SIZE as u64,
280);
281
282parameter_types! {
283	pub const Version: RuntimeVersion = VERSION;
284	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
285		.base_block(BlockExecutionWeight::get())
286		.for_class(DispatchClass::all(), |weights| {
287			weights.base_extrinsic = ExtrinsicBaseWeight::get();
288		})
289		.for_class(DispatchClass::Normal, |weights| {
290			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
291		})
292		.for_class(DispatchClass::Operational, |weights| {
293			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
294			// Operational transactions have some extra reserved space, so that they
295			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
296			weights.reserved = Some(
297				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
298			);
299		})
300		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
301		.build_or_panic();
302}
303
304/// Implements the types required for the system pallet.
305#[derive_impl(frame_system::config_preludes::SolochainDefaultConfig)]
306impl frame_system::Config for Runtime {
307	type Block = Block;
308	type BlockWeights = RuntimeBlockWeights;
309	type Version = Version;
310	type AccountId = AccountId;
311	type Hash = Hash;
312	type Nonce = Nonce;
313	type AccountData = pallet_balances::AccountData<<Runtime as pallet_balances::Config>::Balance>;
314	type OnNewAccount = pallet_revive::AutoMapper<Runtime>;
315	type OnKilledAccount = pallet_revive::AutoMapper<Runtime>;
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	type RuntimeFreezeReason = RuntimeFreezeReason;
329	type FreezeIdentifier = RuntimeFreezeReason;
330	type MaxFreezes = frame_support::traits::VariantCountOf<RuntimeFreezeReason>;
331}
332
333// Implements the types required for the sudo pallet.
334#[derive_impl(pallet_sudo::config_preludes::TestDefaultConfig)]
335impl pallet_sudo::Config for Runtime {}
336
337// Implements the types required for the sudo pallet.
338#[derive_impl(pallet_timestamp::config_preludes::TestDefaultConfig)]
339impl pallet_timestamp::Config for Runtime {}
340
341parameter_types! {
342	pub const TransactionByteFee: Balance = 10 * MILLICENTS;
343	pub FeeMultiplier: Multiplier = Multiplier::one();
344}
345
346// Implements the types required for the transaction payment pallet.
347#[derive_impl(pallet_transaction_payment::config_preludes::TestDefaultConfig)]
348impl pallet_transaction_payment::Config for Runtime {
349	type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, ()>;
350	type WeightToFee = BlockRatioFee<1, 1, Self, Balance>;
351	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
352	type FeeMultiplierUpdate = ConstFeeMultiplier<FeeMultiplier>;
353}
354
355parameter_types! {
356	pub CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(30);
357}
358
359#[derive_impl(pallet_revive::config_preludes::TestDefaultConfig)]
360impl pallet_revive::Config for Runtime {
361	type AddressMapper = AccountId32Mapper<Self>;
362	type ChainId = ConstU64<420_420_420>;
363	type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
364	type Balance = Balance;
365	type Currency = Balances;
366	type NativeToEthRatio = ConstU32<1_000_000>;
367	type UploadOrigin = EnsureSigned<Self::AccountId>;
368	type InstantiateOrigin = EnsureSigned<Self::AccountId>;
369	type Time = Timestamp;
370	type FeeInfo = FeeInfo<Address, Signature, EthExtraImpl>;
371	type DebugEnabled = ConstBool<true>;
372	type AutoMap = ConstBool<true>;
373	type GasScale = ConstU32<50000>;
374}
375
376pallet_revive::impl_runtime_apis_plus_revive_traits!(
377	Runtime,
378	Revive,
379	Executive,
380	EthExtraImpl,
381
382	impl apis::Core<Block> for Runtime {
383		fn version() -> RuntimeVersion {
384			VERSION
385		}
386
387		fn execute_block(block: <Block as BlockT>::LazyBlock) {
388			Executive::execute_block(block)
389		}
390
391		fn initialize_block(header: &Header) -> ExtrinsicInclusionMode {
392			Executive::initialize_block(header)
393		}
394	}
395
396	impl apis::Metadata<Block> for Runtime {
397		fn metadata() -> OpaqueMetadata {
398			OpaqueMetadata::new(Runtime::metadata().into())
399		}
400
401		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
402			Runtime::metadata_at_version(version)
403		}
404
405		fn metadata_versions() -> Vec<u32> {
406			Runtime::metadata_versions()
407		}
408	}
409
410	impl apis::BlockBuilder<Block> for Runtime {
411		fn apply_extrinsic(extrinsic: ExtrinsicFor<Runtime>) -> ApplyExtrinsicResult {
412			Executive::apply_extrinsic(extrinsic)
413		}
414
415		fn finalize_block() -> HeaderFor<Runtime> {
416			Executive::finalize_block()
417		}
418
419		fn inherent_extrinsics(data: InherentData) -> Vec<ExtrinsicFor<Runtime>> {
420			data.create_extrinsics()
421		}
422
423		fn check_inherents(
424			block: <Block as BlockT>::LazyBlock,
425			data: InherentData,
426		) -> CheckInherentsResult {
427			data.check_extrinsics(&block)
428		}
429	}
430
431	impl apis::TaggedTransactionQueue<Block> for Runtime {
432		fn validate_transaction(
433			source: TransactionSource,
434			tx: ExtrinsicFor<Runtime>,
435			block_hash: <Runtime as frame_system::Config>::Hash,
436		) -> TransactionValidity {
437			Executive::validate_transaction(source, tx, block_hash)
438		}
439	}
440
441	impl apis::OffchainWorkerApi<Block> for Runtime {
442		fn offchain_worker(header: &HeaderFor<Runtime>) {
443			Executive::offchain_worker(header)
444		}
445	}
446
447	impl apis::SessionKeys<Block> for Runtime {
448		fn generate_session_keys(_owner: Vec<u8>, _seed: Option<Vec<u8>>) -> apis::OpaqueGeneratedSessionKeys {
449		Default::default()
450		}
451
452
453		fn decode_session_keys(
454			_encoded: Vec<u8>,
455		) -> Option<Vec<(Vec<u8>, apis::KeyTypeId)>> {
456			Default::default()
457		}
458	}
459
460	impl apis::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
461		fn account_nonce(account: AccountId) -> Nonce {
462			System::account_nonce(account)
463		}
464	}
465
466	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
467		Block,
468		Balance,
469	> for Runtime {
470		fn query_info(uxt: ExtrinsicFor<Runtime>, len: u32) -> RuntimeDispatchInfo<Balance> {
471			TransactionPayment::query_info(uxt, len)
472		}
473		fn query_fee_details(uxt: ExtrinsicFor<Runtime>, len: u32) -> FeeDetails<Balance> {
474			TransactionPayment::query_fee_details(uxt, len)
475		}
476		fn query_weight_to_fee(weight: Weight) -> Balance {
477			TransactionPayment::weight_to_fee(weight)
478		}
479		fn query_length_to_fee(length: u32) -> Balance {
480			TransactionPayment::length_to_fee(length)
481		}
482	}
483
484	impl apis::GenesisBuilder<Block> for Runtime {
485		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
486			build_state::<RuntimeGenesisConfig>(config)
487		}
488
489		fn get_preset(id: &Option<PresetId>) -> Option<Vec<u8>> {
490			get_preset::<RuntimeGenesisConfig>(id, self::genesis_config_presets::get_preset)
491		}
492
493		fn preset_names() -> Vec<PresetId> {
494			self::genesis_config_presets::preset_names()
495		}
496	}
497);