diff --git a/node/build.rs b/node/build.rs index e3bfe31..f9d839f 100644 --- a/node/build.rs +++ b/node/build.rs @@ -1,7 +1,7 @@ use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; fn main() { - generate_cargo_keys(); + generate_cargo_keys(); - rerun_if_git_head_changed(); + rerun_if_git_head_changed(); } diff --git a/node/src/chain_spec.rs b/node/src/chain_spec.rs index ce9552d..f8d8d99 100644 --- a/node/src/chain_spec.rs +++ b/node/src/chain_spec.rs @@ -1,6 +1,7 @@ use cumulus_primitives_core::ParaId; -use origintrail_parachain_runtime::{AccountId, AuraId, - EVMConfig, EthereumConfig, Signature, EXISTENTIAL_DEPOSIT}; +use origintrail_parachain_runtime::{ + AccountId, AuraId, EVMConfig, EthereumConfig, Signature, EXISTENTIAL_DEPOSIT, +}; use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup}; use sc_service::ChainType; use serde::{Deserialize, Serialize}; @@ -10,33 +11,33 @@ use std::{collections::BTreeMap, str::FromStr}; /// Specialized `ChainSpec` for the normal parachain runtime. pub type ChainSpec = - sc_service::GenericChainSpec; + sc_service::GenericChainSpec; /// The default XCM version to set in genesis config. const SAFE_XCM_VERSION: u32 = xcm::prelude::XCM_VERSION; /// Helper function to generate a crypto pair from seed pub fn get_from_seed(seed: &str) -> ::Public { - TPublic::Pair::from_string(&format!("//{}", seed), None) - .expect("static values are valid; qed") - .public() + TPublic::Pair::from_string(&format!("//{}", seed), None) + .expect("static values are valid; qed") + .public() } /// The extensions for the [`ChainSpec`]. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)] #[serde(deny_unknown_fields)] pub struct Extensions { - /// The relay chain of the Parachain. - pub relay_chain: String, - /// The id of the Parachain. - pub para_id: u32, + /// The relay chain of the Parachain. + pub relay_chain: String, + /// The id of the Parachain. + pub para_id: u32, } impl Extensions { - /// Try to get the extension from the given `ChainSpec`. - pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> { - sc_chain_spec::get_extension(chain_spec.extensions()) - } + /// Try to get the extension from the given `ChainSpec`. + pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> { + sc_chain_spec::get_extension(chain_spec.extensions()) + } } type AccountPublic = ::Signer; @@ -45,224 +46,228 @@ type AccountPublic = ::Signer; /// /// This function's return type must always match the session keys of the chain in tuple format. pub fn get_collator_keys_from_seed(seed: &str) -> AuraId { - get_from_seed::(seed) + get_from_seed::(seed) } /// Helper function to generate an account ID from seed pub fn get_account_id_from_seed(seed: &str) -> AccountId where - AccountPublic: From<::Public>, + AccountPublic: From<::Public>, { - AccountPublic::from(get_from_seed::(seed)).into_account() + AccountPublic::from(get_from_seed::(seed)).into_account() } /// Generate the session keys from individual elements. /// /// The input must be a tuple of individual keys (a single arg for now since we have just one key). pub fn template_session_keys(keys: AuraId) -> origintrail_parachain_runtime::SessionKeys { - origintrail_parachain_runtime::SessionKeys { aura: keys } + origintrail_parachain_runtime::SessionKeys { aura: keys } } pub fn development_config() -> ChainSpec { - let mut properties = sc_chain_spec::Properties::new(); - properties.insert("tokenSymbol".into(), "OTP".into()); - properties.insert("tokenDecimals".into(), 12.into()); - properties.insert("ss58Format".into(), 101.into()); + let mut properties = sc_chain_spec::Properties::new(); + properties.insert("tokenSymbol".into(), "OTP".into()); + properties.insert("tokenDecimals".into(), 12.into()); + properties.insert("ss58Format".into(), 101.into()); - ChainSpec::from_genesis( - // Name - "Development", - // ID - "dev", - ChainType::Development, - move || { - testnet_genesis( - // initial collators. - vec![ - ( - get_account_id_from_seed::("Alice"), - get_collator_keys_from_seed("Alice"), - ), - ( - get_account_id_from_seed::("Bob"), - get_collator_keys_from_seed("Bob"), - ), - ], - get_account_id_from_seed::("Alice"), - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Ferdie"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - get_account_id_from_seed::("Charlie//stash"), - get_account_id_from_seed::("Dave//stash"), - get_account_id_from_seed::("Eve//stash"), - get_account_id_from_seed::("Ferdie//stash"), - ], - 2000.into(), - ) - }, - Vec::new(), - None, - None, - None, - None, - Extensions { - relay_chain: "rococo-local".into(), // You MUST set this to the correct network! - para_id: 2000, - }, - ) + ChainSpec::from_genesis( + // Name + "Development", + // ID + "dev", + ChainType::Development, + move || { + testnet_genesis( + // initial collators. + vec![ + ( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed("Alice"), + ), + ( + get_account_id_from_seed::("Bob"), + get_collator_keys_from_seed("Bob"), + ), + ], + get_account_id_from_seed::("Alice"), + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Charlie"), + get_account_id_from_seed::("Dave"), + get_account_id_from_seed::("Eve"), + get_account_id_from_seed::("Ferdie"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + get_account_id_from_seed::("Charlie//stash"), + get_account_id_from_seed::("Dave//stash"), + get_account_id_from_seed::("Eve//stash"), + get_account_id_from_seed::("Ferdie//stash"), + ], + 2000.into(), + ) + }, + Vec::new(), + None, + None, + None, + None, + Extensions { + relay_chain: "rococo-local".into(), // You MUST set this to the correct network! + para_id: 2000, + }, + ) } pub fn local_testnet_config() -> ChainSpec { - let mut properties = sc_chain_spec::Properties::new(); - properties.insert("tokenSymbol".into(), "OTP".into()); - properties.insert("tokenDecimals".into(), 12.into()); - properties.insert("ss58Format".into(), 101.into()); + let mut properties = sc_chain_spec::Properties::new(); + properties.insert("tokenSymbol".into(), "OTP".into()); + properties.insert("tokenDecimals".into(), 12.into()); + properties.insert("ss58Format".into(), 101.into()); - ChainSpec::from_genesis( - // Name - "OriginTrail Parachain Testnet", - // ID - "origintrail_parachain_testnet", - ChainType::Local, - move || { - testnet_genesis( - // initial collators. - vec![ - ( - get_account_id_from_seed::("Alice"), - get_collator_keys_from_seed("Alice"), - ), - ( - get_account_id_from_seed::("Bob"), - get_collator_keys_from_seed("Bob"), - ), - ], - get_account_id_from_seed::("Alice"), - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Ferdie"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - get_account_id_from_seed::("Charlie//stash"), - get_account_id_from_seed::("Dave//stash"), - get_account_id_from_seed::("Eve//stash"), - get_account_id_from_seed::("Ferdie//stash"), - ], - 2000.into(), - ) - }, - // Bootnodes - Vec::new(), - // Telemetry - None, - // Protocol ID - Some("origintrail-parachain"), - // Fork ID - None, - // Properties - Some(properties), - // Extensions - Extensions { - relay_chain: "rococo-local".into(), // You MUST set this to the correct network! - para_id: 2000, - }, - ) + ChainSpec::from_genesis( + // Name + "OriginTrail Parachain Testnet", + // ID + "origintrail_parachain_testnet", + ChainType::Local, + move || { + testnet_genesis( + // initial collators. + vec![ + ( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed("Alice"), + ), + ( + get_account_id_from_seed::("Bob"), + get_collator_keys_from_seed("Bob"), + ), + ], + get_account_id_from_seed::("Alice"), + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Charlie"), + get_account_id_from_seed::("Dave"), + get_account_id_from_seed::("Eve"), + get_account_id_from_seed::("Ferdie"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + get_account_id_from_seed::("Charlie//stash"), + get_account_id_from_seed::("Dave//stash"), + get_account_id_from_seed::("Eve//stash"), + get_account_id_from_seed::("Ferdie//stash"), + ], + 2000.into(), + ) + }, + // Bootnodes + Vec::new(), + // Telemetry + None, + // Protocol ID + Some("origintrail-parachain"), + // Fork ID + None, + // Properties + Some(properties), + // Extensions + Extensions { + relay_chain: "rococo-local".into(), // You MUST set this to the correct network! + para_id: 2000, + }, + ) } fn testnet_genesis( - invulnerables: Vec<(AccountId, AuraId)>, - _root_key: AccountId, - endowed_accounts: Vec, - id: ParaId, + invulnerables: Vec<(AccountId, AuraId)>, + _root_key: AccountId, + endowed_accounts: Vec, + id: ParaId, ) -> origintrail_parachain_runtime::GenesisConfig { - origintrail_parachain_runtime::GenesisConfig { - system: origintrail_parachain_runtime::SystemConfig { - code: origintrail_parachain_runtime::WASM_BINARY - .expect("WASM binary was not build, please build it!") - .to_vec(), - }, - balances: origintrail_parachain_runtime::BalancesConfig { - balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(), - }, - parachain_info: origintrail_parachain_runtime::ParachainInfoConfig { parachain_id: id }, - collator_selection: origintrail_parachain_runtime::CollatorSelectionConfig { - invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), - candidacy_bond: EXISTENTIAL_DEPOSIT * 16, - ..Default::default() - }, - session: origintrail_parachain_runtime::SessionConfig { - keys: invulnerables - .into_iter() - .map(|(acc, aura)| { - ( - acc.clone(), // account id - acc, // validator id - template_session_keys(aura), // session keys - ) - }) - .collect(), - }, - // no need to pass anything to aura, in fact it will panic if we do. Session will take care - // of this. - aura: Default::default(), - aura_ext: Default::default(), - parachain_system: Default::default(), - polkadot_xcm: origintrail_parachain_runtime::PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - }, - // sudo: SudoConfig { - // // Assign network admin rights. - // key: Some(root_key), - // }, - vesting: Default::default(), - treasury: Default::default(), - evm: EVMConfig { - accounts: { - let mut map = BTreeMap::new(); - map.insert( - // H160 address of Alice dev account - // Derived from SS58 (42 prefix) address - // SS58: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY - // hex: 0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d - // Using the full hex key, truncating to the first 20 bytes (the first 40 hex chars) - H160::from_str("d43593c715fdd31c61141abd04a99fd6822c8558") - .expect("internal H160 is valid; qed"), - fp_evm::GenesisAccount { - balance: U256::from_str("0xffffffffffffffffffffffffffffffff") - .expect("internal U256 is valid; qed"), - code: Default::default(), - nonce: Default::default(), - storage: Default::default(), - }, - ); - map.insert( - // H160 address of CI test runner account - H160::from_str("6be02d1d3665660d22ff9624b7be0551ee1ac91b") - .expect("internal H160 is valid; qed"), - fp_evm::GenesisAccount { - balance: U256::from_str("0xffffffffffffffffffffffffffffffff") - .expect("internal U256 is valid; qed"), - code: Default::default(), - nonce: Default::default(), - storage: Default::default(), - }, - ); - map - }, - }, - ethereum: EthereumConfig {}, - base_fee: Default::default(), - council: Default::default(), - democracy: Default::default(), - } + origintrail_parachain_runtime::GenesisConfig { + system: origintrail_parachain_runtime::SystemConfig { + code: origintrail_parachain_runtime::WASM_BINARY + .expect("WASM binary was not build, please build it!") + .to_vec(), + }, + balances: origintrail_parachain_runtime::BalancesConfig { + balances: endowed_accounts + .iter() + .cloned() + .map(|k| (k, 1 << 60)) + .collect(), + }, + parachain_info: origintrail_parachain_runtime::ParachainInfoConfig { parachain_id: id }, + collator_selection: origintrail_parachain_runtime::CollatorSelectionConfig { + invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), + candidacy_bond: EXISTENTIAL_DEPOSIT * 16, + ..Default::default() + }, + session: origintrail_parachain_runtime::SessionConfig { + keys: invulnerables + .into_iter() + .map(|(acc, aura)| { + ( + acc.clone(), // account id + acc, // validator id + template_session_keys(aura), // session keys + ) + }) + .collect(), + }, + // no need to pass anything to aura, in fact it will panic if we do. Session will take care + // of this. + aura: Default::default(), + aura_ext: Default::default(), + parachain_system: Default::default(), + polkadot_xcm: origintrail_parachain_runtime::PolkadotXcmConfig { + safe_xcm_version: Some(SAFE_XCM_VERSION), + }, + // sudo: SudoConfig { + // // Assign network admin rights. + // key: Some(root_key), + // }, + vesting: Default::default(), + treasury: Default::default(), + evm: EVMConfig { + accounts: { + let mut map = BTreeMap::new(); + map.insert( + // H160 address of Alice dev account + // Derived from SS58 (42 prefix) address + // SS58: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY + // hex: 0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d + // Using the full hex key, truncating to the first 20 bytes (the first 40 hex chars) + H160::from_str("d43593c715fdd31c61141abd04a99fd6822c8558") + .expect("internal H160 is valid; qed"), + fp_evm::GenesisAccount { + balance: U256::from_str("0xffffffffffffffffffffffffffffffff") + .expect("internal U256 is valid; qed"), + code: Default::default(), + nonce: Default::default(), + storage: Default::default(), + }, + ); + map.insert( + // H160 address of CI test runner account + H160::from_str("6be02d1d3665660d22ff9624b7be0551ee1ac91b") + .expect("internal H160 is valid; qed"), + fp_evm::GenesisAccount { + balance: U256::from_str("0xffffffffffffffffffffffffffffffff") + .expect("internal U256 is valid; qed"), + code: Default::default(), + nonce: Default::default(), + storage: Default::default(), + }, + ); + map + }, + }, + ethereum: EthereumConfig {}, + base_fee: Default::default(), + council: Default::default(), + democracy: Default::default(), + } } diff --git a/node/src/cli.rs b/node/src/cli.rs index 1df6cc3..1327bbb 100644 --- a/node/src/cli.rs +++ b/node/src/cli.rs @@ -19,16 +19,16 @@ pub enum Subcommand { ImportBlocks(sc_cli::ImportBlocksCmd), /// Revert the chain to a previous state. - Revert(sc_cli::RevertCmd), + Revert(sc_cli::RevertCmd), /// Remove the whole chain. PurgeChain(cumulus_client_cli::PurgeChainCmd), /// Export the genesis state of the parachain. - ExportGenesisState(cumulus_client_cli::ExportGenesisStateCommand), + ExportGenesisState(cumulus_client_cli::ExportGenesisStateCommand), - /// Export the genesis wasm of the parachain. - ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand), + /// Export the genesis wasm of the parachain. + ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand), /// Sub-commands concerned with benchmarking. /// The pallet benchmarking moved to the `pallet` sub-command. @@ -36,12 +36,12 @@ pub enum Subcommand { Benchmark(frame_benchmarking_cli::BenchmarkCmd), /// Try some testing command against a specified runtime state. - #[cfg(feature = "try-runtime")] - TryRuntime(try_runtime_cli::TryRuntimeCmd), + #[cfg(feature = "try-runtime")] + TryRuntime(try_runtime_cli::TryRuntimeCmd), - /// Errors since the binary was not build with `--features try-runtime`. - #[cfg(not(feature = "try-runtime"))] - TryRuntime, + /// Errors since the binary was not build with `--features try-runtime`. + #[cfg(not(feature = "try-runtime"))] + TryRuntime, } #[derive(Debug, clap::Parser)] @@ -57,15 +57,15 @@ pub struct Cli { #[command(flatten)] pub run: cumulus_client_cli::RunCmd, - /// Disable automatic hardware benchmarks. - /// - /// By default these benchmarks are automatically ran at startup and measure - /// the CPU speed, the memory bandwidth and the disk speed. - /// - /// The results are then printed out in the logs, and also sent as part of - /// telemetry, if telemetry is enabled. - #[arg(long)] - pub no_hardware_benchmarks: bool, + /// Disable automatic hardware benchmarks. + /// + /// By default these benchmarks are automatically ran at startup and measure + /// the CPU speed, the memory bandwidth and the disk speed. + /// + /// The results are then printed out in the logs, and also sent as part of + /// telemetry, if telemetry is enabled. + #[arg(long)] + pub no_hardware_benchmarks: bool, /// Relay chain arguments #[arg(raw = true)] diff --git a/node/src/command.rs b/node/src/command.rs index dfb38fc..f1bd9c8 100644 --- a/node/src/command.rs +++ b/node/src/command.rs @@ -1,4 +1,8 @@ -use std::net::SocketAddr; +use crate::{ + chain_spec, + cli::{Cli, RelayChainCli, Subcommand}, + service::{new_partial, ParachainNativeExecutor}, +}; use codec::Encode; use cumulus_client_cli::generate_genesis_block; use cumulus_primitives_core::ParaId; @@ -12,11 +16,7 @@ use sc_cli::{ use sc_service::config::{BasePath, PrometheusConfig}; use sp_core::hexdisplay::HexDisplay; use sp_runtime::traits::{AccountIdConversion, Block as BlockT}; -use crate::{ - chain_spec, - cli::{Cli, RelayChainCli, Subcommand}, - service::{new_partial, ParachainNativeExecutor}, -}; +use std::net::SocketAddr; fn load_spec(id: &str) -> std::result::Result, String> { Ok(match id { @@ -44,8 +44,8 @@ impl SubstrateCli for Cli { passed to the parachain node, while the arguments provided after -- will be passed \ to the relay chain node.\n\n\ {} -- ", - Self::executable_name() - ) + Self::executable_name() + ) } fn author() -> String { @@ -83,8 +83,9 @@ impl SubstrateCli for RelayChainCli { "OriginTrail Parachain \n\nThe command-line arguments provided first will be \ passed to the parachain node, while the arguments provided after -- will be passed \ to the relay chain node.\n\n\ - {} -- ", Self::executable_name() - ) + {} -- ", + Self::executable_name() + ) } fn author() -> String { @@ -170,25 +171,25 @@ pub fn run() -> Result<()> { }) } Some(Subcommand::Revert(cmd)) => { - construct_async_run!(|components, cli, cmd, config| { - Ok(cmd.run(components.client, components.backend, None)) - }) - }, + construct_async_run!(|components, cli, cmd, config| { + Ok(cmd.run(components.client, components.backend, None)) + }) + } Some(Subcommand::ExportGenesisState(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.sync_run(|_config| { - let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?; - let state_version = Cli::native_runtime_version(&spec).state_version(); - cmd.run::(&*spec, state_version) - }) - }, - Some(Subcommand::ExportGenesisWasm(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.sync_run(|_config| { - let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?; - cmd.run(&*spec) - }) - }, + let runner = cli.create_runner(cmd)?; + runner.sync_run(|_config| { + let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?; + let state_version = Cli::native_runtime_version(&spec).state_version(); + cmd.run::(&*spec, state_version) + }) + } + Some(Subcommand::ExportGenesisWasm(cmd)) => { + let runner = cli.create_runner(cmd)?; + runner.sync_run(|_config| { + let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?; + cmd.run(&*spec) + }) + } Some(Subcommand::Benchmark(cmd)) => { let runner = cli.create_runner(cmd)?; // Switch on the concrete benchmark sub-command- @@ -207,14 +208,15 @@ pub fn run() -> Result<()> { cmd.run(partials.client) }), #[cfg(not(feature = "runtime-benchmarks"))] - BenchmarkCmd::Storage(_) => - return Err(sc_cli::Error::Input( - "Compile with --features=runtime-benchmarks \ + BenchmarkCmd::Storage(_) => { + return Err(sc_cli::Error::Input( + "Compile with --features=runtime-benchmarks \ to enable storage benchmarks." - .into(), - ) - .into()), - #[cfg(feature = "runtime-benchmarks")] + .into(), + ) + .into()) + } + #[cfg(feature = "runtime-benchmarks")] BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| { let partials = new_partial(&config)?; let db = partials.backend.expose_db(); @@ -222,47 +224,52 @@ pub fn run() -> Result<()> { cmd.run(config, partials.client.clone(), db, storage) }), - BenchmarkCmd::Machine(cmd) => - runner.sync_run(|config| cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone())), + BenchmarkCmd::Machine(cmd) => { + runner.sync_run(|config| cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone())) + } // NOTE: this allows the Client to leniently implement - // new benchmark commands without requiring a companion MR. - #[allow(unreachable_patterns)] - _ => Err("Benchmarking sub-command unsupported".into()), + // new benchmark commands without requiring a companion MR. + #[allow(unreachable_patterns)] + _ => Err("Benchmarking sub-command unsupported".into()), } } #[cfg(feature = "try-runtime")] Some(Subcommand::TryRuntime(cmd)) => { use origintrail_parachain_runtime::MILLISECS_PER_BLOCK; - use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch}; - use try_runtime_cli::block_building_info::timestamp_with_aura_info; - - let runner = cli.create_runner(cmd)?; + use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch}; + use try_runtime_cli::block_building_info::timestamp_with_aura_info; - type HostFunctionsOf = ExtendedHostFunctions< - sp_io::SubstrateHostFunctions, - ::ExtendHostFunctions, - >; + let runner = cli.create_runner(cmd)?; - // grab the task manager. - let registry = &runner.config().prometheus_config.as_ref().map(|cfg| &cfg.registry); - let task_manager = - sc_service::TaskManager::new(runner.config().tokio_handle.clone(), *registry) - .map_err(|e| format!("Error: {:?}", e))?; + type HostFunctionsOf = ExtendedHostFunctions< + sp_io::SubstrateHostFunctions, + ::ExtendHostFunctions, + >; + + // grab the task manager. + let registry = &runner + .config() + .prometheus_config + .as_ref() + .map(|cfg| &cfg.registry); + let task_manager = + sc_service::TaskManager::new(runner.config().tokio_handle.clone(), *registry) + .map_err(|e| format!("Error: {:?}", e))?; let info_provider = timestamp_with_aura_info(MILLISECS_PER_BLOCK); - runner.async_run(|_| { - Ok(( - cmd.run::, _>(Some( - info_provider, - )), - task_manager, - )) - }) - }, + runner.async_run(|_| { + Ok(( + cmd.run::, _>(Some( + info_provider, + )), + task_manager, + )) + }) + } #[cfg(not(feature = "try-runtime"))] - Some(Subcommand::TryRuntime) => Err("Try-runtime was not enabled when building the node. \ + Some(Subcommand::TryRuntime) => Err("Try-runtime was not enabled when building the node. \ You can enable it with `--features try-runtime`." - .into()), + .into()), None => { let runner = cli.create_runner(&cli.run.normalize())?; let collator_options = cli.run.collator_options(); diff --git a/node/src/main.rs b/node/src/main.rs index fdd6a8a..00d46c6 100644 --- a/node/src/main.rs +++ b/node/src/main.rs @@ -10,5 +10,5 @@ mod command; mod rpc; fn main() -> sc_cli::Result<()> { - command::run() + command::run() } diff --git a/node/src/rpc.rs b/node/src/rpc.rs index f535c92..adc9c64 100644 --- a/node/src/rpc.rs +++ b/node/src/rpc.rs @@ -9,118 +9,127 @@ use std::sync::Arc; use origintrail_parachain_runtime::{opaque::Block, AccountId, Balance, Hash, Index as Nonce}; -use sc_client_api::{ - AuxStore, Backend, BlockchainEvents, StateBackend, StorageProvider, -}; -pub use sc_rpc::{DenyUnsafe, SubscriptionTaskExecutor}; -use fc_rpc::{ - EthBlockDataCacheTask, OverrideHandle, EthFilter, EthFilterApiServer, -}; -use sp_runtime::traits::BlakeTwo256; +use fc_rpc::{EthBlockDataCacheTask, EthFilter, EthFilterApiServer, OverrideHandle}; use fc_rpc_core::types::{FeeHistoryCache, FilterPool}; +use sc_client_api::{AuxStore, Backend, BlockchainEvents, StateBackend, StorageProvider}; +use sc_network::NetworkService; use sc_network_sync::SyncingService; +pub use sc_rpc::{DenyUnsafe, SubscriptionTaskExecutor}; use sc_transaction_pool::{ChainApi, Pool}; use sc_transaction_pool_api::TransactionPool; use sp_api::{CallApiAt, ProvideRuntimeApi}; use sp_block_builder::BlockBuilder; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; -use sc_network::NetworkService; +use sp_runtime::traits::BlakeTwo256; /// A type representing all RPC extensions. pub type RpcExtension = jsonrpsee::RpcModule<()>; /// Full client dependencies pub struct FullDeps { - /// The client instance to use. - pub client: Arc, - /// Transaction pool instance. - pub pool: Arc

, - /// Graph pool instance. - pub graph: Arc>, - /// Chain syncing service - pub sync: Arc>, - /// Whether to deny unsafe calls - pub deny_unsafe: DenyUnsafe, - /// The Node authority flag + /// The client instance to use. + pub client: Arc, + /// Transaction pool instance. + pub pool: Arc

, + /// Graph pool instance. + pub graph: Arc>, + /// Chain syncing service + pub sync: Arc>, + /// Whether to deny unsafe calls + pub deny_unsafe: DenyUnsafe, + /// The Node authority flag pub is_authority: bool, - /// Network service - pub network: Arc>, - /// Backend. - pub backend: Arc>, - /// EthFilterApi pool. + /// Network service + pub network: Arc>, + /// Backend. + pub backend: Arc>, + /// EthFilterApi pool. pub filter_pool: FilterPool, - /// Maximum fee history cache size. + /// Maximum fee history cache size. pub fee_history_cache_limit: u64, /// Fee history cache. pub fee_history_cache: FeeHistoryCache, - /// Ethereum data access overrides. - pub overrides: Arc>, + /// Ethereum data access overrides. + pub overrides: Arc>, /// Cache for Ethereum block data. - pub block_data_cache: Arc>, + pub block_data_cache: Arc>, } /// Instantiate all RPC extensions. pub fn create_full( - deps: FullDeps, - _subscription_task_executor: SubscriptionTaskExecutor, + deps: FullDeps, + _subscription_task_executor: SubscriptionTaskExecutor, ) -> Result> where - BE: Backend + 'static, - BE::State: StateBackend, - C: ProvideRuntimeApi - + HeaderBackend - + AuxStore - + BlockchainEvents - + CallApiAt - + HeaderMetadata - + Send - + Sync - + 'static, - C: StorageProvider, - C: sc_client_api::BlockBackend, - C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, - C::Api: substrate_frame_rpc_system::AccountNonceApi, - C::Api: BlockBuilder, - C::Api: fp_rpc::EthereumRuntimeRPCApi, - C::Api: fp_rpc::ConvertTransactionRuntimeApi, - P: TransactionPool + Sync + Send + 'static, - A: ChainApi + 'static, + BE: Backend + 'static, + BE::State: StateBackend, + C: ProvideRuntimeApi + + HeaderBackend + + AuxStore + + BlockchainEvents + + CallApiAt + + HeaderMetadata + + Send + + Sync + + 'static, + C: StorageProvider, + C: sc_client_api::BlockBackend, + C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, + C::Api: substrate_frame_rpc_system::AccountNonceApi, + C::Api: BlockBuilder, + C::Api: fp_rpc::EthereumRuntimeRPCApi, + C::Api: fp_rpc::ConvertTransactionRuntimeApi, + P: TransactionPool + Sync + Send + 'static, + A: ChainApi + 'static, { - use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; - use substrate_frame_rpc_system::{System, SystemApiServer}; - use fc_rpc::{Eth, EthApiServer, Net, NetApiServer}; + use fc_rpc::{Eth, EthApiServer, Net, NetApiServer}; + use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; + use substrate_frame_rpc_system::{System, SystemApiServer}; - let mut module = RpcExtension::new(()); - let FullDeps { client, pool, graph, deny_unsafe, network, backend, is_authority, filter_pool, - sync, fee_history_cache, fee_history_cache_limit, overrides, block_data_cache - } = deps; + let mut module = RpcExtension::new(()); + let FullDeps { + client, + pool, + graph, + deny_unsafe, + network, + backend, + is_authority, + filter_pool, + sync, + fee_history_cache, + fee_history_cache_limit, + overrides, + block_data_cache, + } = deps; - module.merge(System::new(client.clone(), pool.clone(), deny_unsafe).into_rpc())?; - module.merge(TransactionPayment::new(client.clone()).into_rpc())?; + module.merge(System::new(client.clone(), pool.clone(), deny_unsafe).into_rpc())?; + module.merge(TransactionPayment::new(client.clone()).into_rpc())?; - let signers = Vec::new(); - let no_tx_converter: Option = None; + let signers = Vec::new(); + let no_tx_converter: Option = None; - module.merge( + module.merge( Eth::<_, _, _, fp_rpc::NoTransactionConverter, _, _, _>::new( client.clone(), - pool.clone(), + pool.clone(), graph, no_tx_converter, sync.clone(), signers, overrides.clone(), - backend.clone(), + backend.clone(), is_authority, block_data_cache.clone(), fee_history_cache, fee_history_cache_limit, - // Allow 10x max allowed weight for non-transactional calls - 10, - ).into_rpc() + // Allow 10x max allowed weight for non-transactional calls + 10, + ) + .into_rpc(), )?; - let max_past_logs: u32 = 10_000; + let max_past_logs: u32 = 10_000; let max_stored_filters: usize = 500; module.merge( EthFilter::new( @@ -134,15 +143,15 @@ where .into_rpc(), )?; - module.merge( - Net::new( - client.clone(), - network.clone(), - // Whether to format the `peer_count` response as Hex (default) or not. - true, - ) - .into_rpc(), - )?; + module.merge( + Net::new( + client.clone(), + network.clone(), + // Whether to format the `peer_count` response as Hex (default) or not. + true, + ) + .into_rpc(), + )?; - Ok(module) + Ok(module) } diff --git a/node/src/service.rs b/node/src/service.rs index 5dacffb..b9532e9 100644 --- a/node/src/service.rs +++ b/node/src/service.rs @@ -1,40 +1,40 @@ //! Service and ServiceFactory implementation. Specialized wrapper over substrate service. // std -use std::{sync::Arc, path::PathBuf, time::Duration, collections::BTreeMap}; +use std::{collections::BTreeMap, path::PathBuf, sync::Arc, time::Duration}; use cumulus_client_cli::CollatorOptions; // Local Runtime Types -use origintrail_parachain_runtime::{ - opaque::Block, RuntimeApi, -}; +use origintrail_parachain_runtime::{opaque::Block, RuntimeApi}; // Cumulus Imports use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion}; use cumulus_client_consensus_common::{ - ParachainBlockImport as TParachainBlockImport, ParachainConsensus + ParachainBlockImport as TParachainBlockImport, ParachainConsensus, }; use cumulus_client_service::{ - build_network, build_relay_chain_interface, prepare_node_config, start_collator, start_full_node, - BuildNetworkParams, StartCollatorParams, StartFullNodeParams, + build_network, build_relay_chain_interface, prepare_node_config, start_collator, + start_full_node, BuildNetworkParams, StartCollatorParams, StartFullNodeParams, }; use cumulus_primitives_core::ParaId; use cumulus_relay_chain_interface::RelayChainInterface; // Substrate Imports +use fc_rpc_core::types::{FeeHistoryCache, FilterPool}; use frame_benchmarking_cli::SUBSTRATE_REFERENCE_HARDWARE; +use futures::StreamExt; +use sc_cli::SubstrateCli; +use sc_client_api::BlockchainEvents; use sc_consensus::ImportQueue; use sc_executor::NativeElseWasmExecutor; use sc_network::NetworkBlock; use sc_network_sync::SyncingService; -use sc_service::{BasePath, Configuration, PartialComponents, TFullBackend, TFullClient, TaskManager}; +use sc_service::{ + BasePath, Configuration, PartialComponents, TFullBackend, TFullClient, TaskManager, +}; use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle}; use sp_keystore::SyncCryptoStorePtr; use substrate_prometheus_endpoint::Registry; -use futures::StreamExt; -use sc_cli::SubstrateCli; -use sc_client_api::BlockchainEvents; -use fc_rpc_core::types::{FeeHistoryCache, FilterPool}; use crate::cli::Cli; @@ -42,15 +42,15 @@ use crate::cli::Cli; pub struct ParachainNativeExecutor; impl sc_executor::NativeExecutionDispatch for ParachainNativeExecutor { - type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; + type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; - fn dispatch(method: &str, data: &[u8]) -> Option> { - origintrail_parachain_runtime::api::dispatch(method, data) - } + fn dispatch(method: &str, data: &[u8]) -> Option> { + origintrail_parachain_runtime::api::dispatch(method, data) + } - fn native_version() -> sc_executor::NativeVersion { - origintrail_parachain_runtime::native_version() - } + fn native_version() -> sc_executor::NativeVersion { + origintrail_parachain_runtime::native_version() + } } type ParachainExecutor = NativeElseWasmExecutor; @@ -62,14 +62,14 @@ type ParachainBackend = TFullBackend; type ParachainBlockImport = TParachainBlockImport, ParachainBackend>; pub(crate) fn db_config_dir(config: &Configuration) -> PathBuf { - config - .base_path - .as_ref() - .map(|base_path| base_path.config_dir(config.chain_spec.id())) - .unwrap_or_else(|| { - BasePath::from_project("", "", &Cli::executable_name()) - .config_dir(config.chain_spec.id()) - }) + config + .base_path + .as_ref() + .map(|base_path| base_path.config_dir(config.chain_spec.id())) + .unwrap_or_else(|| { + BasePath::from_project("", "", &Cli::executable_name()) + .config_dir(config.chain_spec.id()) + }) } /// Starts a `ServiceBuilder` for a full service. @@ -77,96 +77,97 @@ pub(crate) fn db_config_dir(config: &Configuration) -> PathBuf { /// Use this macro if you don't actually need the full service, but just the builder in order to /// be able to perform chain operations. pub fn new_partial( - config: &Configuration, + config: &Configuration, ) -> Result< - PartialComponents< - ParachainClient, - ParachainBackend, - (), - sc_consensus::DefaultImportQueue< - Block, - ParachainClient, - >, - sc_transaction_pool::FullPool< - Block, - ParachainClient, - >, - ( - ParachainBlockImport, - Option, - Option, - Arc>, - ), - >, - sc_service::Error, + PartialComponents< + ParachainClient, + ParachainBackend, + (), + sc_consensus::DefaultImportQueue, + sc_transaction_pool::FullPool, + ( + ParachainBlockImport, + Option, + Option, + Arc>, + ), + >, + sc_service::Error, > { - let telemetry = config - .telemetry_endpoints - .clone() - .filter(|x| !x.is_empty()) - .map(|endpoints| -> Result<_, sc_telemetry::Error> { - let worker = TelemetryWorker::new(16)?; - let telemetry = worker.handle().new_telemetry(endpoints); - Ok((worker, telemetry)) - }) - .transpose()?; - - let executor = ParachainExecutor::new( - config.wasm_method, - config.default_heap_pages, - config.max_runtime_instances, - config.runtime_cache_size, - ); - - let (client, backend, keystore_container, task_manager) = - sc_service::new_full_parts::( - config, - telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), - executor, - )?; - let client = Arc::new(client); - - let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle()); - - let telemetry = telemetry.map(|(worker, telemetry)| { - task_manager.spawn_handle().spawn("telemetry", None, worker.run()); - telemetry - }); - - let transaction_pool = sc_transaction_pool::BasicPool::new_full( - config.transaction_pool.clone(), - config.role.is_authority().into(), - config.prometheus_registry(), - task_manager.spawn_essential_handle(), - client.clone(), - ); - - let frontier_backend = Arc::new(fc_db::Backend::open( - Arc::clone(&client), - &config.database, - &db_config_dir(config), - )?); - - let block_import = ParachainBlockImport::new(client.clone(), backend.clone()); - - let import_queue = build_import_queue( - client.clone(), - block_import.clone(), - config, - telemetry.as_ref().map(|telemetry| telemetry.handle()), - &task_manager, - )?; - - Ok(PartialComponents { - backend, - client, - import_queue, - keystore_container, - task_manager, - transaction_pool, - select_chain: (), - other: (block_import, telemetry, telemetry_worker_handle, frontier_backend), - }) + let telemetry = config + .telemetry_endpoints + .clone() + .filter(|x| !x.is_empty()) + .map(|endpoints| -> Result<_, sc_telemetry::Error> { + let worker = TelemetryWorker::new(16)?; + let telemetry = worker.handle().new_telemetry(endpoints); + Ok((worker, telemetry)) + }) + .transpose()?; + + let executor = ParachainExecutor::new( + config.wasm_method, + config.default_heap_pages, + config.max_runtime_instances, + config.runtime_cache_size, + ); + + let (client, backend, keystore_container, task_manager) = + sc_service::new_full_parts::( + config, + telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), + executor, + )?; + let client = Arc::new(client); + + let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle()); + + let telemetry = telemetry.map(|(worker, telemetry)| { + task_manager + .spawn_handle() + .spawn("telemetry", None, worker.run()); + telemetry + }); + + let transaction_pool = sc_transaction_pool::BasicPool::new_full( + config.transaction_pool.clone(), + config.role.is_authority().into(), + config.prometheus_registry(), + task_manager.spawn_essential_handle(), + client.clone(), + ); + + let frontier_backend = Arc::new(fc_db::Backend::open( + Arc::clone(&client), + &config.database, + &db_config_dir(config), + )?); + + let block_import = ParachainBlockImport::new(client.clone(), backend.clone()); + + let import_queue = build_import_queue( + client.clone(), + block_import.clone(), + config, + telemetry.as_ref().map(|telemetry| telemetry.handle()), + &task_manager, + )?; + + Ok(PartialComponents { + backend, + client, + import_queue, + keystore_container, + task_manager, + transaction_pool, + select_chain: (), + other: ( + block_import, + telemetry, + telemetry_worker_handle, + frontier_backend, + ), + }) } /// Start a node with the given parachain `Configuration` and relay chain `Configuration`. @@ -174,66 +175,62 @@ pub fn new_partial( /// This is the actual implementation that is abstract over the executor and the runtime api. #[sc_tracing::logging::prefix_logs_with("Parachain")] async fn start_node_impl( - parachain_config: Configuration, - polkadot_config: Configuration, - collator_options: CollatorOptions, - para_id: ParaId, - hwbench: Option, -) -> sc_service::error::Result<( - TaskManager, - Arc, -)> { - - let parachain_config = prepare_node_config(parachain_config); - - let params = new_partial(¶chain_config)?; - let (block_import, mut telemetry, telemetry_worker_handle, frontier_backend) = params.other; - - let client = params.client.clone(); - let backend = params.backend.clone(); - let mut task_manager = params.task_manager; - - let (relay_chain_interface, collator_key) = build_relay_chain_interface( - polkadot_config, - ¶chain_config, - telemetry_worker_handle, - &mut task_manager, - collator_options.clone(), - hwbench.clone(), - ) - .await - .map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?; - - let force_authoring = parachain_config.force_authoring; - let validator = parachain_config.role.is_authority(); - let prometheus_registry = parachain_config.prometheus_registry().cloned(); - let is_authority = parachain_config.role.is_authority(); - let transaction_pool = params.transaction_pool.clone(); - let import_queue_service = params.import_queue.service(); - let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) = - build_network(BuildNetworkParams { - parachain_config: ¶chain_config, - client: client.clone(), - transaction_pool: transaction_pool.clone(), - para_id, - spawn_handle: task_manager.spawn_handle(), - relay_chain_interface: relay_chain_interface.clone(), - import_queue: params.import_queue, - } - ).await?; - - if parachain_config.offchain_worker.enabled { - sc_service::build_offchain_workers( - ¶chain_config, - task_manager.spawn_handle(), - client.clone(), - network.clone(), - ); - } - - let filter_pool: FilterPool = Arc::new(std::sync::Mutex::new(BTreeMap::new())); - let fee_history_cache: FeeHistoryCache = Arc::new(std::sync::Mutex::new(BTreeMap::new())); - let overrides = fc_storage::overrides_handle(client.clone()); + parachain_config: Configuration, + polkadot_config: Configuration, + collator_options: CollatorOptions, + para_id: ParaId, + hwbench: Option, +) -> sc_service::error::Result<(TaskManager, Arc)> { + let parachain_config = prepare_node_config(parachain_config); + + let params = new_partial(¶chain_config)?; + let (block_import, mut telemetry, telemetry_worker_handle, frontier_backend) = params.other; + + let client = params.client.clone(); + let backend = params.backend.clone(); + let mut task_manager = params.task_manager; + + let (relay_chain_interface, collator_key) = build_relay_chain_interface( + polkadot_config, + ¶chain_config, + telemetry_worker_handle, + &mut task_manager, + collator_options.clone(), + hwbench.clone(), + ) + .await + .map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?; + + let force_authoring = parachain_config.force_authoring; + let validator = parachain_config.role.is_authority(); + let prometheus_registry = parachain_config.prometheus_registry().cloned(); + let is_authority = parachain_config.role.is_authority(); + let transaction_pool = params.transaction_pool.clone(); + let import_queue_service = params.import_queue.service(); + let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) = + build_network(BuildNetworkParams { + parachain_config: ¶chain_config, + client: client.clone(), + transaction_pool: transaction_pool.clone(), + para_id, + spawn_handle: task_manager.spawn_handle(), + relay_chain_interface: relay_chain_interface.clone(), + import_queue: params.import_queue, + }) + .await?; + + if parachain_config.offchain_worker.enabled { + sc_service::build_offchain_workers( + ¶chain_config, + task_manager.spawn_handle(), + client.clone(), + network.clone(), + ); + } + + let filter_pool: FilterPool = Arc::new(std::sync::Mutex::new(BTreeMap::new())); + let fee_history_cache: FeeHistoryCache = Arc::new(std::sync::Mutex::new(BTreeMap::new())); + let overrides = fc_storage::overrides_handle(client.clone()); // Sinks for pubsub notifications. // Everytime a new subscription is created, a new mpsc channel is added to the sink pool. @@ -244,7 +241,7 @@ async fn start_node_impl( > = Default::default(); let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks); - // Frontier offchain DB task. Essential. + // Frontier offchain DB task. Essential. // Maps emulated ethereum data to substrate native data. task_manager.spawn_essential_handle().spawn( "frontier-mapping-sync-worker", @@ -254,18 +251,18 @@ async fn start_node_impl( Duration::new(6, 0), client.clone(), backend.clone(), - overrides.clone(), + overrides.clone(), frontier_backend.clone(), 3, 0, fc_mapping_sync::SyncStrategy::Parachain, - sync_service.clone(), + sync_service.clone(), pubsub_notification_sinks.clone(), ) .for_each(|()| futures::future::ready(())), ); - // Frontier `EthFilterApi` maintenance. Manages the pool of user-created Filters. + // Frontier `EthFilterApi` maintenance. Manages the pool of user-created Filters. // Each filter is allowed to stay in the pool for 100 blocks. const FILTER_RETAIN_THRESHOLD: u64 = 100; task_manager.spawn_essential_handle().spawn( @@ -278,8 +275,8 @@ async fn start_node_impl( ), ); - const FEE_HISTORY_LIMIT: u64 = 2048; - task_manager.spawn_essential_handle().spawn( + const FEE_HISTORY_LIMIT: u64 = 2048; + task_manager.spawn_essential_handle().spawn( "frontier-fee-history", Some("frontier"), fc_rpc::EthTask::fee_history_task( @@ -290,7 +287,7 @@ async fn start_node_impl( ), ); - let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new( + let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new( task_manager.spawn_handle(), overrides.clone(), 50, @@ -298,253 +295,262 @@ async fn start_node_impl( prometheus_registry.clone(), )); - let rpc_builder = { - let client = client.clone(); - let transaction_pool = transaction_pool.clone(); - let sync = sync_service.clone(); - let network = network.clone(); - let frontier_backend = frontier_backend.clone(); - - Box::new(move |deny_unsafe, subscription_task_executor| { - let deps = crate::rpc::FullDeps { - client: client.clone(), - pool: transaction_pool.clone(), - graph: transaction_pool.pool().clone(), - sync: sync.clone(), - deny_unsafe, - is_authority, - network: network.clone(), - backend: frontier_backend.clone(), - filter_pool: filter_pool.clone(), - fee_history_cache_limit: FEE_HISTORY_LIMIT, + let rpc_builder = { + let client = client.clone(); + let transaction_pool = transaction_pool.clone(); + let sync = sync_service.clone(); + let network = network.clone(); + let frontier_backend = frontier_backend.clone(); + + Box::new(move |deny_unsafe, subscription_task_executor| { + let deps = crate::rpc::FullDeps { + client: client.clone(), + pool: transaction_pool.clone(), + graph: transaction_pool.pool().clone(), + sync: sync.clone(), + deny_unsafe, + is_authority, + network: network.clone(), + backend: frontier_backend.clone(), + filter_pool: filter_pool.clone(), + fee_history_cache_limit: FEE_HISTORY_LIMIT, fee_history_cache: fee_history_cache.clone(), - overrides: overrides.clone(), - block_data_cache: block_data_cache.clone(), - }; - - crate::rpc::create_full(deps, subscription_task_executor).map_err(Into::into) - }) - }; - - sc_service::spawn_tasks(sc_service::SpawnTasksParams { - rpc_builder, - client: client.clone(), - transaction_pool: transaction_pool.clone(), - task_manager: &mut task_manager, - config: parachain_config, - keystore: params.keystore_container.sync_keystore(), - backend, - network: network.clone(), - sync_service: sync_service.clone(), - system_rpc_tx, - tx_handler_controller, - telemetry: telemetry.as_mut(), - })?; - - if let Some(hwbench) = hwbench { - sc_sysinfo::print_hwbench(&hwbench); - // Here you can check whether the hardware meets your chains' requirements. Putting a link - // in there and swapping out the requirements for your own are probably a good idea. The - // requirements for a para-chain are dictated by its relay-chain. - if !SUBSTRATE_REFERENCE_HARDWARE.check_hardware(&hwbench) && validator { - log::warn!( - "⚠️ The hardware does not meet the minimal requirements for role 'Authority'." - ); - } - if let Some(ref mut telemetry) = telemetry { - let telemetry_handle = telemetry.handle(); - task_manager.spawn_handle().spawn( - "telemetry_hwbench", - None, - sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench), - ); - } - } - - let announce_block = { - let sync_service = sync_service.clone(); - Arc::new(move |hash, data| sync_service.announce_block(hash, data)) - }; - - let relay_chain_slot_duration = Duration::from_secs(6); - - let overseer_handle = relay_chain_interface - .overseer_handle() - .map_err(|e| sc_service::Error::Application(Box::new(e)))?; - - if validator { - let parachain_consensus = build_consensus( - client.clone(), - block_import, - prometheus_registry.as_ref(), - telemetry.as_ref().map(|t| t.handle()), - &task_manager, - relay_chain_interface.clone(), - transaction_pool, - sync_service, - params.keystore_container.sync_keystore(), - force_authoring, - para_id, - )?; - - let spawner = task_manager.spawn_handle(); - - let params = StartCollatorParams { - para_id, - block_status: client.clone(), - announce_block, - client: client.clone(), - task_manager: &mut task_manager, - relay_chain_interface, - spawner, - parachain_consensus, - import_queue: import_queue_service, - collator_key: collator_key.expect("Command line arguments do not allow this. qed"), - relay_chain_slot_duration, - recovery_handle: Box::new(overseer_handle), - }; - - start_collator(params).await?; - } else { - let params = StartFullNodeParams { - client: client.clone(), - announce_block, - task_manager: &mut task_manager, - para_id, - relay_chain_interface, - relay_chain_slot_duration, - import_queue: import_queue_service, - recovery_handle: Box::new(overseer_handle), - }; - - start_full_node(params)?; - } - - start_network.start_network(); - - Ok((task_manager, client)) + overrides: overrides.clone(), + block_data_cache: block_data_cache.clone(), + }; + + crate::rpc::create_full(deps, subscription_task_executor).map_err(Into::into) + }) + }; + + sc_service::spawn_tasks(sc_service::SpawnTasksParams { + rpc_builder, + client: client.clone(), + transaction_pool: transaction_pool.clone(), + task_manager: &mut task_manager, + config: parachain_config, + keystore: params.keystore_container.sync_keystore(), + backend, + network: network.clone(), + sync_service: sync_service.clone(), + system_rpc_tx, + tx_handler_controller, + telemetry: telemetry.as_mut(), + })?; + + if let Some(hwbench) = hwbench { + sc_sysinfo::print_hwbench(&hwbench); + // Here you can check whether the hardware meets your chains' requirements. Putting a link + // in there and swapping out the requirements for your own are probably a good idea. The + // requirements for a para-chain are dictated by its relay-chain. + if !SUBSTRATE_REFERENCE_HARDWARE.check_hardware(&hwbench) && validator { + log::warn!( + "⚠️ The hardware does not meet the minimal requirements for role 'Authority'." + ); + } + if let Some(ref mut telemetry) = telemetry { + let telemetry_handle = telemetry.handle(); + task_manager.spawn_handle().spawn( + "telemetry_hwbench", + None, + sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench), + ); + } + } + + let announce_block = { + let sync_service = sync_service.clone(); + Arc::new(move |hash, data| sync_service.announce_block(hash, data)) + }; + + let relay_chain_slot_duration = Duration::from_secs(6); + + let overseer_handle = relay_chain_interface + .overseer_handle() + .map_err(|e| sc_service::Error::Application(Box::new(e)))?; + + if validator { + let parachain_consensus = build_consensus( + client.clone(), + block_import, + prometheus_registry.as_ref(), + telemetry.as_ref().map(|t| t.handle()), + &task_manager, + relay_chain_interface.clone(), + transaction_pool, + sync_service, + params.keystore_container.sync_keystore(), + force_authoring, + para_id, + )?; + + let spawner = task_manager.spawn_handle(); + + let params = StartCollatorParams { + para_id, + block_status: client.clone(), + announce_block, + client: client.clone(), + task_manager: &mut task_manager, + relay_chain_interface, + spawner, + parachain_consensus, + import_queue: import_queue_service, + collator_key: collator_key.expect("Command line arguments do not allow this. qed"), + relay_chain_slot_duration, + recovery_handle: Box::new(overseer_handle), + }; + + start_collator(params).await?; + } else { + let params = StartFullNodeParams { + client: client.clone(), + announce_block, + task_manager: &mut task_manager, + para_id, + relay_chain_interface, + relay_chain_slot_duration, + import_queue: import_queue_service, + recovery_handle: Box::new(overseer_handle), + }; + + start_full_node(params)?; + } + + start_network.start_network(); + + Ok((task_manager, client)) } /// Build the import queue for the parachain runtime. pub fn build_import_queue( - client: Arc, - block_import: ParachainBlockImport, - config: &Configuration, - telemetry: Option, - task_manager: &TaskManager, -) -> Result< - sc_consensus::DefaultImportQueue< Block, ParachainClient>, - sc_service::Error, -> { - let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?; - - cumulus_client_consensus_aura::import_queue::< - sp_consensus_aura::sr25519::AuthorityPair, - _, - _, - _, - _, - _, - >(cumulus_client_consensus_aura::ImportQueueParams { - block_import, - client, - create_inherent_data_providers: move |_, _| async move { - let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); - - let slot = + client: Arc, + block_import: ParachainBlockImport, + config: &Configuration, + telemetry: Option, + task_manager: &TaskManager, +) -> Result, sc_service::Error> { + let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?; + + cumulus_client_consensus_aura::import_queue::< + sp_consensus_aura::sr25519::AuthorityPair, + _, + _, + _, + _, + _, + >(cumulus_client_consensus_aura::ImportQueueParams { + block_import, + client, + create_inherent_data_providers: move |_, _| async move { + let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); + + let slot = sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration( *timestamp, slot_duration, ); - Ok((slot, timestamp)) - }, - registry: config.prometheus_registry(), - spawner: &task_manager.spawn_essential_handle(), - telemetry, - }) - .map_err(Into::into) + Ok((slot, timestamp)) + }, + registry: config.prometheus_registry(), + spawner: &task_manager.spawn_essential_handle(), + telemetry, + }) + .map_err(Into::into) } fn build_consensus( - client: Arc, - block_import: ParachainBlockImport, - prometheus_registry: Option<&Registry>, - telemetry: Option, - task_manager: &TaskManager, - relay_chain_interface: Arc, - transaction_pool: Arc>, - sync_oracle: Arc>, - keystore: SyncCryptoStorePtr, - force_authoring: bool, - para_id: ParaId, + client: Arc, + block_import: ParachainBlockImport, + prometheus_registry: Option<&Registry>, + telemetry: Option, + task_manager: &TaskManager, + relay_chain_interface: Arc, + transaction_pool: Arc>, + sync_oracle: Arc>, + keystore: SyncCryptoStorePtr, + force_authoring: bool, + para_id: ParaId, ) -> Result>, sc_service::Error> { - let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?; - - let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording( - task_manager.spawn_handle(), - client.clone(), - transaction_pool, - prometheus_registry, - telemetry.clone(), - ); - - let params = BuildAuraConsensusParams { - proposer_factory, - create_inherent_data_providers: move |_, (relay_parent, validation_data)| { - let relay_chain_interface = relay_chain_interface.clone(); - async move { - let parachain_inherent = - cumulus_primitives_parachain_inherent::ParachainInherentData::create_at( - relay_parent, - &relay_chain_interface, - &validation_data, - para_id, - ) - .await; - let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); - - let slot = + let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?; + + let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording( + task_manager.spawn_handle(), + client.clone(), + transaction_pool, + prometheus_registry, + telemetry.clone(), + ); + + let params = BuildAuraConsensusParams { + proposer_factory, + create_inherent_data_providers: move |_, (relay_parent, validation_data)| { + let relay_chain_interface = relay_chain_interface.clone(); + async move { + let parachain_inherent = + cumulus_primitives_parachain_inherent::ParachainInherentData::create_at( + relay_parent, + &relay_chain_interface, + &validation_data, + para_id, + ) + .await; + let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); + + let slot = sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration( *timestamp, slot_duration, ); - let parachain_inherent = parachain_inherent.ok_or_else(|| { - Box::::from( - "Failed to create parachain inherent", - ) - })?; - Ok((slot, timestamp, parachain_inherent)) - } - }, - block_import, - para_client: client, - backoff_authoring_blocks: Option::<()>::None, - sync_oracle, - keystore, - force_authoring, - slot_duration, - // We got around 500ms for proposing - block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32), - // And a maximum of 750ms if slots are skipped - max_block_proposal_slot_portion: Some(SlotProportion::new(1f32 / 16f32)), - telemetry, - }; - - Ok(AuraConsensus::build::(params)) + let parachain_inherent = parachain_inherent.ok_or_else(|| { + Box::::from( + "Failed to create parachain inherent", + ) + })?; + Ok((slot, timestamp, parachain_inherent)) + } + }, + block_import, + para_client: client, + backoff_authoring_blocks: Option::<()>::None, + sync_oracle, + keystore, + force_authoring, + slot_duration, + // We got around 500ms for proposing + block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32), + // And a maximum of 750ms if slots are skipped + max_block_proposal_slot_portion: Some(SlotProportion::new(1f32 / 16f32)), + telemetry, + }; + + Ok(AuraConsensus::build::< + sp_consensus_aura::sr25519::AuthorityPair, + _, + _, + _, + _, + _, + _, + >(params)) } /// Start a parachain node. pub async fn start_parachain_node( - parachain_config: Configuration, - polkadot_config: Configuration, - collator_options: CollatorOptions, - para_id: ParaId, - hwbench: Option, -) -> sc_service::error::Result<( - TaskManager, - Arc, -)> { - start_node_impl(parachain_config, polkadot_config, collator_options, para_id, hwbench).await + parachain_config: Configuration, + polkadot_config: Configuration, + collator_options: CollatorOptions, + para_id: ParaId, + hwbench: Option, +) -> sc_service::error::Result<(TaskManager, Arc)> { + start_node_impl( + parachain_config, + polkadot_config, + collator_options, + para_id, + hwbench, + ) + .await } diff --git a/pallets/evm-accounts/src/lib.rs b/pallets/evm-accounts/src/lib.rs index 86c84a1..574e0db 100644 --- a/pallets/evm-accounts/src/lib.rs +++ b/pallets/evm-accounts/src/lib.rs @@ -23,28 +23,28 @@ use codec::Encode; use frame_support::{ - ensure, - pallet_prelude::*, - traits::{Currency, IsType, OnKilledAccount}, - transactional, - storage::{with_transaction, TransactionOutcome}, + ensure, + pallet_prelude::*, + storage::{with_transaction, TransactionOutcome}, + traits::{Currency, IsType, OnKilledAccount}, + transactional, }; use frame_system::{ensure_signed, pallet_prelude::*}; +use pallet_evm::AddressMapping as EvmPalletAddressMappingTrait; use pallet_evm_utility_macro::keccak256; -use pallet_evm::{AddressMapping as EvmPalletAddressMappingTrait}; +use impl_trait_for_tuples::impl_for_tuples; use sp_core::crypto::AccountId32; use sp_core::{H160, H256, U256}; use sp_io::{ - crypto::secp256k1_ecdsa_recover, - hashing::{blake2_256, keccak_256}, + crypto::secp256k1_ecdsa_recover, + hashing::{blake2_256, keccak_256}, }; use sp_runtime::{ - traits::{LookupError, StaticLookup, Zero}, - MultiAddress, + traits::{LookupError, StaticLookup, Zero}, + MultiAddress, }; use sp_std::{marker::PhantomData, vec::Vec}; -use impl_trait_for_tuples::impl_for_tuples; pub use pallet::*; @@ -66,406 +66,420 @@ pub type EvmAddress = sp_core::H160; /// A mapping between `AccountId` and `EvmAddress`. pub trait AddressMapping { - /// Returns the AccountId used go generate the given EvmAddress. - fn get_account_id(evm: &EvmAddress) -> AccountId32; - /// Returns the EvmAddress associated with a given AccountId or the - /// underlying EvmAddress of the AccountId. - /// Returns None if there is no EvmAddress associated with the AccountId - /// and there is no underlying EvmAddress in the AccountId. - fn get_evm_address(account_id: &AccountId32) -> Option; - /// Returns the EVM address associated with an account ID and generates an - /// account mapping if no association exists. - fn get_or_create_evm_address(account_id: &AccountId32) -> EvmAddress; - /// Returns the default EVM address associated with an account ID. - fn get_default_evm_address(account_id: &AccountId32) -> EvmAddress; - /// Returns true if a given AccountId is associated with a given EvmAddress - /// and false if is not. - fn is_linked(account_id: &AccountId32, evm: &EvmAddress) -> bool; + /// Returns the AccountId used go generate the given EvmAddress. + fn get_account_id(evm: &EvmAddress) -> AccountId32; + /// Returns the EvmAddress associated with a given AccountId or the + /// underlying EvmAddress of the AccountId. + /// Returns None if there is no EvmAddress associated with the AccountId + /// and there is no underlying EvmAddress in the AccountId. + fn get_evm_address(account_id: &AccountId32) -> Option; + /// Returns the EVM address associated with an account ID and generates an + /// account mapping if no association exists. + fn get_or_create_evm_address(account_id: &AccountId32) -> EvmAddress; + /// Returns the default EVM address associated with an account ID. + fn get_default_evm_address(account_id: &AccountId32) -> EvmAddress; + /// Returns true if a given AccountId is associated with a given EvmAddress + /// and false if is not. + fn is_linked(account_id: &AccountId32, evm: &EvmAddress) -> bool; } pub trait EVMAccountsManager { - /// Returns the AccountId used to generate the given EvmAddress. - fn get_account_id(address: &EvmAddress) -> AccountId; - /// Returns the EvmAddress associated with a given AccountId or the underlying EvmAddress of the - /// AccountId. - fn get_evm_address(account_id: &AccountId) -> Option; - /// Claim account mapping between AccountId and a generated EvmAddress based off of the - /// AccountId. - fn claim_default_evm_address(account_id: &AccountId) -> Result; + /// Returns the AccountId used to generate the given EvmAddress. + fn get_account_id(address: &EvmAddress) -> AccountId; + /// Returns the EvmAddress associated with a given AccountId or the underlying EvmAddress of the + /// AccountId. + fn get_evm_address(account_id: &AccountId) -> Option; + /// Claim account mapping between AccountId and a generated EvmAddress based off of the + /// AccountId. + fn claim_default_evm_address(account_id: &AccountId) -> Result; } /// Convert any type that implements Into into byte representation ([u8, 32]) pub fn to_bytes>(value: T) -> [u8; 32] { - Into::<[u8; 32]>::into(value.into()) + Into::<[u8; 32]>::into(value.into()) } pub fn with_transaction_result( - f: impl FnOnce() -> Result, + f: impl FnOnce() -> Result, ) -> Result { - with_transaction(|| { - let res = f(); - if res.is_ok() { - TransactionOutcome::Commit(res) - } else { - TransactionOutcome::Rollback(res) - } - }) + with_transaction(|| { + let res = f(); + if res.is_ok() { + TransactionOutcome::Commit(res) + } else { + TransactionOutcome::Rollback(res) + } + }) } pub trait MergeAccount { - fn merge_account(source: &AccountId, dest: &AccountId) -> DispatchResult; + fn merge_account(source: &AccountId, dest: &AccountId) -> DispatchResult; } #[impl_for_tuples(5)] impl MergeAccount for Tuple { - fn merge_account(source: &AccountId, dest: &AccountId) -> DispatchResult { - with_transaction_result(|| { - for_tuples!( #( { + fn merge_account(source: &AccountId, dest: &AccountId) -> DispatchResult { + with_transaction_result(|| { + for_tuples!( #( { Tuple::merge_account(source, dest)?; } )* ); - Ok(()) - }) - } + Ok(()) + }) + } } #[frame_support::pallet] pub mod pallet { - use super::*; - - #[pallet::config] - pub trait Config: frame_system::Config { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; - - /// The Currency for managing Evm account assets. - type Currency: Currency; - - /// Mapping from address to account id. - type AddressMapping: AddressMapping; - - /// Chain ID of EVM. - #[pallet::constant] - type ChainId: Get; - - /// Merge free balance from source to dest. - type MergeAccount: MergeAccount; - - /// Weight information for the extrinsics in this pallet. - type WeightInfo: WeightInfo; - } - - #[pallet::event] - #[pallet::generate_deposit(pub(crate) fn deposit_event)] - pub enum Event { - /// Mapping between Substrate accounts and EVM accounts - /// claim account. - ClaimAccount { - account_id: T::AccountId, - evm_address: EvmAddress, - }, - } - - /// Error for evm accounts pallet. - #[pallet::error] - pub enum Error { - /// AccountId has mapped - AccountIdHasMapped, - /// Eth address has mapped - EthAddressHasMapped, - /// Bad signature - BadSignature, - /// Invalid signature - InvalidSignature, - /// Account ref count is not zero - NonZeroRefCount, - } - - /// The Substrate Account for EvmAddresses - /// - /// Accounts: map EvmAddress => Option - #[pallet::storage] - #[pallet::getter(fn accounts)] - pub type Accounts = StorageMap<_, Twox64Concat, EvmAddress, T::AccountId, OptionQuery>; - - /// The EvmAddress for Substrate Accounts - /// - /// EvmAddresses: map AccountId => Option - #[pallet::storage] - #[pallet::getter(fn evm_addresses)] - pub type EvmAddresses = StorageMap<_, Twox64Concat, T::AccountId, EvmAddress, OptionQuery>; - - #[pallet::pallet] - pub struct Pallet(_); - - #[pallet::hooks] - impl Hooks for Pallet {} - - #[pallet::call] - impl Pallet { - /// Claim account mapping between Substrate accounts and EVM accounts. - /// Ensure eth_address has not been mapped. - /// - /// - `eth_address`: The address to bind to the caller's account - /// - `eth_signature`: A signature generated by the address to prove ownership - #[pallet::call_index(0)] - #[pallet::weight(T::WeightInfo::claim_account())] - #[transactional] - pub fn claim_account( - origin: OriginFor, - eth_address: EvmAddress, - eth_signature: Eip712Signature, - ) -> DispatchResult { - let who = ensure_signed(origin)?; - - // ensure account_id and eth_address has not been mapped - ensure!(!EvmAddresses::::contains_key(&who), Error::::AccountIdHasMapped); - ensure!( - !Accounts::::contains_key(eth_address), - Error::::EthAddressHasMapped - ); - - // recover evm address from signature - let address = Self::verify_eip712_signature(&who, ð_signature).ok_or(Error::::BadSignature)?; - ensure!(eth_address == address, Error::::InvalidSignature); - - // check if the evm padded address already exists - let account_id = T::AddressMapping::get_account_id(ð_address); - if frame_system::Pallet::::account_exists(&account_id) { - // merge balance from `evm padded address` to `origin` - T::MergeAccount::merge_account(&account_id, &who)?; - } - - Accounts::::insert(eth_address, &who); - EvmAddresses::::insert(&who, eth_address); - - Self::deposit_event(Event::ClaimAccount { - account_id: who, - evm_address: eth_address, - }); - - Ok(()) - } - - /// Claim account mapping between Substrate accounts and a generated EVM - /// address based off of those accounts. - /// Ensure eth_address has not been mapped - #[pallet::call_index(1)] - #[pallet::weight(T::WeightInfo::claim_default_account())] - pub fn claim_default_account(origin: OriginFor) -> DispatchResult { - let who = ensure_signed(origin)?; - let _ = Self::do_claim_default_evm_address(who)?; - Ok(()) - } - } + use super::*; + + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + + /// The Currency for managing Evm account assets. + type Currency: Currency; + + /// Mapping from address to account id. + type AddressMapping: AddressMapping; + + /// Chain ID of EVM. + #[pallet::constant] + type ChainId: Get; + + /// Merge free balance from source to dest. + type MergeAccount: MergeAccount; + + /// Weight information for the extrinsics in this pallet. + type WeightInfo: WeightInfo; + } + + #[pallet::event] + #[pallet::generate_deposit(pub(crate) fn deposit_event)] + pub enum Event { + /// Mapping between Substrate accounts and EVM accounts + /// claim account. + ClaimAccount { + account_id: T::AccountId, + evm_address: EvmAddress, + }, + } + + /// Error for evm accounts pallet. + #[pallet::error] + pub enum Error { + /// AccountId has mapped + AccountIdHasMapped, + /// Eth address has mapped + EthAddressHasMapped, + /// Bad signature + BadSignature, + /// Invalid signature + InvalidSignature, + /// Account ref count is not zero + NonZeroRefCount, + } + + /// The Substrate Account for EvmAddresses + /// + /// Accounts: map EvmAddress => Option + #[pallet::storage] + #[pallet::getter(fn accounts)] + pub type Accounts = + StorageMap<_, Twox64Concat, EvmAddress, T::AccountId, OptionQuery>; + + /// The EvmAddress for Substrate Accounts + /// + /// EvmAddresses: map AccountId => Option + #[pallet::storage] + #[pallet::getter(fn evm_addresses)] + pub type EvmAddresses = + StorageMap<_, Twox64Concat, T::AccountId, EvmAddress, OptionQuery>; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::hooks] + impl Hooks for Pallet {} + + #[pallet::call] + impl Pallet { + /// Claim account mapping between Substrate accounts and EVM accounts. + /// Ensure eth_address has not been mapped. + /// + /// - `eth_address`: The address to bind to the caller's account + /// - `eth_signature`: A signature generated by the address to prove ownership + #[pallet::call_index(0)] + #[pallet::weight(T::WeightInfo::claim_account())] + #[transactional] + pub fn claim_account( + origin: OriginFor, + eth_address: EvmAddress, + eth_signature: Eip712Signature, + ) -> DispatchResult { + let who = ensure_signed(origin)?; + + // ensure account_id and eth_address has not been mapped + ensure!( + !EvmAddresses::::contains_key(&who), + Error::::AccountIdHasMapped + ); + ensure!( + !Accounts::::contains_key(eth_address), + Error::::EthAddressHasMapped + ); + + // recover evm address from signature + let address = Self::verify_eip712_signature(&who, ð_signature) + .ok_or(Error::::BadSignature)?; + ensure!(eth_address == address, Error::::InvalidSignature); + + // check if the evm padded address already exists + let account_id = T::AddressMapping::get_account_id(ð_address); + if frame_system::Pallet::::account_exists(&account_id) { + // merge balance from `evm padded address` to `origin` + T::MergeAccount::merge_account(&account_id, &who)?; + } + + Accounts::::insert(eth_address, &who); + EvmAddresses::::insert(&who, eth_address); + + Self::deposit_event(Event::ClaimAccount { + account_id: who, + evm_address: eth_address, + }); + + Ok(()) + } + + /// Claim account mapping between Substrate accounts and a generated EVM + /// address based off of those accounts. + /// Ensure eth_address has not been mapped + #[pallet::call_index(1)] + #[pallet::weight(T::WeightInfo::claim_default_account())] + pub fn claim_default_account(origin: OriginFor) -> DispatchResult { + let who = ensure_signed(origin)?; + let _ = Self::do_claim_default_evm_address(who)?; + Ok(()) + } + } } impl Pallet { - #[cfg(any(feature = "runtime-benchmarks", feature = "std"))] - // Returns an Etherum public key derived from an Ethereum secret key. - pub fn eth_public(secret: &libsecp256k1::SecretKey) -> libsecp256k1::PublicKey { - libsecp256k1::PublicKey::from_secret_key(secret) - } - - #[cfg(any(feature = "runtime-benchmarks", feature = "std"))] - // Returns an Etherum address derived from an Ethereum secret key. - // Only for tests - pub fn eth_address(secret: &libsecp256k1::SecretKey) -> EvmAddress { - EvmAddress::from_slice(&keccak_256(&Self::eth_public(secret).serialize()[1..65])[12..]) - } - - #[cfg(any(feature = "runtime-benchmarks", feature = "std"))] - // Constructs a message and signs it. - pub fn eth_sign(secret: &libsecp256k1::SecretKey, who: &T::AccountId) -> Eip712Signature { - let msg = keccak_256(&Self::eip712_signable_message(who)); - let (sig, recovery_id) = libsecp256k1::sign(&libsecp256k1::Message::parse(&msg), secret); - let mut r = [0u8; 65]; - r[0..64].copy_from_slice(&sig.serialize()[..]); - r[64] = recovery_id.serialize(); - r - } - - fn verify_eip712_signature(who: &T::AccountId, sig: &[u8; 65]) -> Option { - let msg = Self::eip712_signable_message(who); - let msg_hash = keccak_256(msg.as_slice()); - - recover_signer(sig, &msg_hash) - } - - // Eip-712 message to be signed - fn eip712_signable_message(who: &T::AccountId) -> Vec { - let domain_separator = Self::evm_account_domain_separator(); - let payload_hash = Self::evm_account_payload_hash(who); - - let mut msg = b"\x19\x01".to_vec(); - msg.extend_from_slice(&domain_separator); - msg.extend_from_slice(&payload_hash); - msg - } - - fn evm_account_payload_hash(who: &T::AccountId) -> [u8; 32] { - let tx_type_hash = keccak256!("Transaction(bytes substrateAddress)"); - let mut tx_msg = tx_type_hash.to_vec(); - tx_msg.extend_from_slice(&keccak_256(&who.encode())); - keccak_256(tx_msg.as_slice()) - } - - fn evm_account_domain_separator() -> [u8; 32] { - let domain_hash = keccak256!("EIP712Domain(string name,string version,uint256 chainId,bytes32 salt)"); - let mut domain_seperator_msg = domain_hash.to_vec(); - domain_seperator_msg.extend_from_slice(keccak256!("OTP EVM claim")); // name - domain_seperator_msg.extend_from_slice(keccak256!("1")); // version - domain_seperator_msg.extend_from_slice(&to_bytes(T::ChainId::get())); // chain id - domain_seperator_msg.extend_from_slice(frame_system::Pallet::::block_hash(T::BlockNumber::zero()).as_ref()); // genesis block hash - keccak_256(domain_seperator_msg.as_slice()) - } - - fn do_claim_default_evm_address(who: T::AccountId) -> Result { - // ensure account_id has not been mapped - ensure!(!EvmAddresses::::contains_key(&who), Error::::AccountIdHasMapped); - - let eth_address = T::AddressMapping::get_or_create_evm_address(&who); - - Ok(eth_address) - } + #[cfg(any(feature = "runtime-benchmarks", feature = "std"))] + // Returns an Etherum public key derived from an Ethereum secret key. + pub fn eth_public(secret: &libsecp256k1::SecretKey) -> libsecp256k1::PublicKey { + libsecp256k1::PublicKey::from_secret_key(secret) + } + + #[cfg(any(feature = "runtime-benchmarks", feature = "std"))] + // Returns an Etherum address derived from an Ethereum secret key. + // Only for tests + pub fn eth_address(secret: &libsecp256k1::SecretKey) -> EvmAddress { + EvmAddress::from_slice(&keccak_256(&Self::eth_public(secret).serialize()[1..65])[12..]) + } + + #[cfg(any(feature = "runtime-benchmarks", feature = "std"))] + // Constructs a message and signs it. + pub fn eth_sign(secret: &libsecp256k1::SecretKey, who: &T::AccountId) -> Eip712Signature { + let msg = keccak_256(&Self::eip712_signable_message(who)); + let (sig, recovery_id) = libsecp256k1::sign(&libsecp256k1::Message::parse(&msg), secret); + let mut r = [0u8; 65]; + r[0..64].copy_from_slice(&sig.serialize()[..]); + r[64] = recovery_id.serialize(); + r + } + + fn verify_eip712_signature(who: &T::AccountId, sig: &[u8; 65]) -> Option { + let msg = Self::eip712_signable_message(who); + let msg_hash = keccak_256(msg.as_slice()); + + recover_signer(sig, &msg_hash) + } + + // Eip-712 message to be signed + fn eip712_signable_message(who: &T::AccountId) -> Vec { + let domain_separator = Self::evm_account_domain_separator(); + let payload_hash = Self::evm_account_payload_hash(who); + + let mut msg = b"\x19\x01".to_vec(); + msg.extend_from_slice(&domain_separator); + msg.extend_from_slice(&payload_hash); + msg + } + + fn evm_account_payload_hash(who: &T::AccountId) -> [u8; 32] { + let tx_type_hash = keccak256!("Transaction(bytes substrateAddress)"); + let mut tx_msg = tx_type_hash.to_vec(); + tx_msg.extend_from_slice(&keccak_256(&who.encode())); + keccak_256(tx_msg.as_slice()) + } + + fn evm_account_domain_separator() -> [u8; 32] { + let domain_hash = + keccak256!("EIP712Domain(string name,string version,uint256 chainId,bytes32 salt)"); + let mut domain_seperator_msg = domain_hash.to_vec(); + domain_seperator_msg.extend_from_slice(keccak256!("OTP EVM claim")); // name + domain_seperator_msg.extend_from_slice(keccak256!("1")); // version + domain_seperator_msg.extend_from_slice(&to_bytes(T::ChainId::get())); // chain id + domain_seperator_msg.extend_from_slice( + frame_system::Pallet::::block_hash(T::BlockNumber::zero()).as_ref(), + ); // genesis block hash + keccak_256(domain_seperator_msg.as_slice()) + } + + fn do_claim_default_evm_address(who: T::AccountId) -> Result { + // ensure account_id has not been mapped + ensure!( + !EvmAddresses::::contains_key(&who), + Error::::AccountIdHasMapped + ); + + let eth_address = T::AddressMapping::get_or_create_evm_address(&who); + + Ok(eth_address) + } } fn recover_signer(sig: &[u8; 65], msg_hash: &[u8; 32]) -> Option { - secp256k1_ecdsa_recover(sig, msg_hash) - .map(|pubkey| H160::from(H256::from_slice(&keccak_256(&pubkey)))) - .ok() + secp256k1_ecdsa_recover(sig, msg_hash) + .map(|pubkey| H160::from(H256::from_slice(&keccak_256(&pubkey)))) + .ok() } // Creates a an EvmAddress from an AccountId by appending the bytes "evm:" to // the account_id and hashing it. fn account_to_default_evm_address(account_id: &impl Encode) -> EvmAddress { - let payload = (b"evm:", account_id); - EvmAddress::from_slice(&payload.using_encoded(blake2_256)[0..20]) + let payload = (b"evm:", account_id); + EvmAddress::from_slice(&payload.using_encoded(blake2_256)[0..20]) } pub struct EvmAddressMapping(sp_std::marker::PhantomData); impl AddressMapping for EvmAddressMapping where - T::AccountId: IsType, + T::AccountId: IsType, { - // Returns the AccountId used to generate the given EvmAddress. - fn get_account_id(address: &EvmAddress) -> T::AccountId { - if let Some(acc) = Accounts::::get(address) { - acc - } else { - let mut data: [u8; 32] = [0u8; 32]; - data[0..4].copy_from_slice(b"evm:"); - data[4..24].copy_from_slice(&address[..]); - AccountId32::from(data).into() - } - } - - // Returns the EvmAddress associated with a given AccountId or the - // underlying EvmAddress of the AccountId. - // Returns None if there is no EvmAddress associated with the AccountId - // and there is no underlying EvmAddress in the AccountId. - fn get_evm_address(account_id: &T::AccountId) -> Option { - // Return the EvmAddress if a mapping to account_id exists - EvmAddresses::::get(account_id).or_else(|| { - let data: &[u8] = account_id.into_ref().as_ref(); - // Return the underlying EVM address if it exists otherwise return None - if data.starts_with(b"evm:") { - Some(EvmAddress::from_slice(&data[4..24])) - } else { - None - } - }) - } - - // Returns the EVM address associated with an account ID and generates an - // account mapping if no association exists. - fn get_or_create_evm_address(account_id: &T::AccountId) -> EvmAddress { - Self::get_evm_address(account_id).unwrap_or_else(|| { - let addr = account_to_default_evm_address(account_id); - - // create reverse mapping - Accounts::::insert(addr, account_id); - EvmAddresses::::insert(account_id, addr); - - Pallet::::deposit_event(Event::ClaimAccount { - account_id: account_id.clone(), - evm_address: addr, - }); - - addr - }) - } - - // Returns the default EVM address associated with an account ID. - fn get_default_evm_address(account_id: &T::AccountId) -> EvmAddress { - account_to_default_evm_address(account_id) - } - - // Returns true if a given AccountId is associated with a given EvmAddress - // and false if is not. - fn is_linked(account_id: &T::AccountId, evm: &EvmAddress) -> bool { - Self::get_evm_address(account_id).as_ref() == Some(evm) - || &account_to_default_evm_address(account_id.into_ref()) == evm - } + // Returns the AccountId used to generate the given EvmAddress. + fn get_account_id(address: &EvmAddress) -> T::AccountId { + if let Some(acc) = Accounts::::get(address) { + acc + } else { + let mut data: [u8; 32] = [0u8; 32]; + data[0..4].copy_from_slice(b"evm:"); + data[4..24].copy_from_slice(&address[..]); + AccountId32::from(data).into() + } + } + + // Returns the EvmAddress associated with a given AccountId or the + // underlying EvmAddress of the AccountId. + // Returns None if there is no EvmAddress associated with the AccountId + // and there is no underlying EvmAddress in the AccountId. + fn get_evm_address(account_id: &T::AccountId) -> Option { + // Return the EvmAddress if a mapping to account_id exists + EvmAddresses::::get(account_id).or_else(|| { + let data: &[u8] = account_id.into_ref().as_ref(); + // Return the underlying EVM address if it exists otherwise return None + if data.starts_with(b"evm:") { + Some(EvmAddress::from_slice(&data[4..24])) + } else { + None + } + }) + } + + // Returns the EVM address associated with an account ID and generates an + // account mapping if no association exists. + fn get_or_create_evm_address(account_id: &T::AccountId) -> EvmAddress { + Self::get_evm_address(account_id).unwrap_or_else(|| { + let addr = account_to_default_evm_address(account_id); + + // create reverse mapping + Accounts::::insert(addr, account_id); + EvmAddresses::::insert(account_id, addr); + + Pallet::::deposit_event(Event::ClaimAccount { + account_id: account_id.clone(), + evm_address: addr, + }); + + addr + }) + } + + // Returns the default EVM address associated with an account ID. + fn get_default_evm_address(account_id: &T::AccountId) -> EvmAddress { + account_to_default_evm_address(account_id) + } + + // Returns true if a given AccountId is associated with a given EvmAddress + // and false if is not. + fn is_linked(account_id: &T::AccountId, evm: &EvmAddress) -> bool { + Self::get_evm_address(account_id).as_ref() == Some(evm) + || &account_to_default_evm_address(account_id.into_ref()) == evm + } } pub struct CallKillAccount(PhantomData); impl OnKilledAccount for CallKillAccount { - fn on_killed_account(who: &T::AccountId) { - // remove mapping created by `claim_account` or `get_or_create_evm_address` - if let Some(evm_addr) = Pallet::::evm_addresses(who) { - Accounts::::remove(evm_addr); - EvmAddresses::::remove(who); - } - } + fn on_killed_account(who: &T::AccountId) { + // remove mapping created by `claim_account` or `get_or_create_evm_address` + if let Some(evm_addr) = Pallet::::evm_addresses(who) { + Accounts::::remove(evm_addr); + EvmAddresses::::remove(who); + } + } } impl StaticLookup for Pallet { - type Source = MultiAddress; - type Target = T::AccountId; - - fn lookup(a: Self::Source) -> Result { - match a { - MultiAddress::Address20(i) => Ok(T::AddressMapping::get_account_id(&EvmAddress::from_slice(&i))), - _ => Err(LookupError), - } - } - - fn unlookup(a: Self::Target) -> Self::Source { - MultiAddress::Id(a) - } + type Source = MultiAddress; + type Target = T::AccountId; + + fn lookup(a: Self::Source) -> Result { + match a { + MultiAddress::Address20(i) => Ok(T::AddressMapping::get_account_id( + &EvmAddress::from_slice(&i), + )), + _ => Err(LookupError), + } + } + + fn unlookup(a: Self::Target) -> Self::Source { + MultiAddress::Id(a) + } } impl EVMAccountsManager for Pallet { - /// Returns the AccountId used to generate the given EvmAddress. - fn get_account_id(address: &EvmAddress) -> T::AccountId { - T::AddressMapping::get_account_id(address) - } - - /// Returns the EvmAddress associated with a given AccountId or the underlying EvmAddress of the - /// AccountId. - fn get_evm_address(account_id: &T::AccountId) -> Option { - T::AddressMapping::get_evm_address(account_id) - } - - /// Claim account mapping between AccountId and a generated EvmAddress based off of the - /// AccountId. - fn claim_default_evm_address(account_id: &T::AccountId) -> Result { - Self::do_claim_default_evm_address(account_id.clone()) - } + /// Returns the AccountId used to generate the given EvmAddress. + fn get_account_id(address: &EvmAddress) -> T::AccountId { + T::AddressMapping::get_account_id(address) + } + + /// Returns the EvmAddress associated with a given AccountId or the underlying EvmAddress of the + /// AccountId. + fn get_evm_address(account_id: &T::AccountId) -> Option { + T::AddressMapping::get_evm_address(account_id) + } + + /// Claim account mapping between AccountId and a generated EvmAddress based off of the + /// AccountId. + fn claim_default_evm_address(account_id: &T::AccountId) -> Result { + Self::do_claim_default_evm_address(account_id.clone()) + } } impl EvmPalletAddressMappingTrait for EvmAddressMapping where - T::AccountId: From + Into, + T::AccountId: From + Into, { - fn into_account_id(address: H160) -> T::AccountId { - if let Some(acc) = Accounts::::get(address) { - acc - } else { - let mut data: [u8; 32] = [0u8; 32]; - data[0..4].copy_from_slice(b"evm:"); - data[4..24].copy_from_slice(&address[..]); - AccountId32::from(data).into() + fn into_account_id(address: H160) -> T::AccountId { + if let Some(acc) = Accounts::::get(address) { + acc + } else { + let mut data: [u8; 32] = [0u8; 32]; + data[0..4].copy_from_slice(b"evm:"); + data[4..24].copy_from_slice(&address[..]); + AccountId32::from(data).into() + } } - } -} \ No newline at end of file +} diff --git a/pallets/evm-accounts/src/mock.rs b/pallets/evm-accounts/src/mock.rs index 82a3922..cd9a612 100644 --- a/pallets/evm-accounts/src/mock.rs +++ b/pallets/evm-accounts/src/mock.rs @@ -17,8 +17,8 @@ use super::*; use frame_support::{ - construct_runtime, - traits::{ConstU128, ConstU64, Everything}, + construct_runtime, + traits::{ConstU128, ConstU64, Everything}, }; use sp_core::{crypto::AccountId32, H256}; use sp_io::hashing::keccak_256; @@ -32,109 +32,109 @@ pub const ALICE: AccountId = AccountId32::new([0u8; 32]); pub const BOB: AccountId = AccountId32::new([1u8; 32]); mod evm_accounts { - pub use super::super::*; + pub use super::super::*; } impl frame_system::Config for Runtime { - type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = BlockNumber; - type RuntimeCall = RuntimeCall; - type Hash = H256; - type Hashing = ::sp_runtime::traits::BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; - type Header = Header; - type RuntimeEvent = RuntimeEvent; - type BlockHashCount = ConstU64<250>; - type BlockWeights = (); - type BlockLength = (); - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type DbWeight = (); - type BaseCallFilter = Everything; - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); - type MaxConsumers = ConstU32<16>; + type RuntimeOrigin = RuntimeOrigin; + type Index = u64; + type BlockNumber = BlockNumber; + type RuntimeCall = RuntimeCall; + type Hash = H256; + type Hashing = ::sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Header = Header; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = ConstU64<250>; + type BlockWeights = (); + type BlockLength = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type DbWeight = (); + type BaseCallFilter = Everything; + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = ConstU32<16>; } impl pallet_balances::Config for Runtime { - type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU128<1>; - type AccountStore = frame_system::Pallet; - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); + type Balance = Balance; + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ConstU128<1>; + type AccountStore = frame_system::Pallet; + type MaxLocks = (); + type MaxReserves = (); + type ReserveIdentifier = [u8; 8]; + type WeightInfo = (); } impl Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type Currency = Balances; - type ChainId = (); + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type ChainId = (); type MergeAccount = (); - type AddressMapping = EvmAddressMapping; - type WeightInfo = (); + type AddressMapping = EvmAddressMapping; + type WeightInfo = (); } type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system::{Pallet, Call, Storage, Config, Event}, - EvmAccountsModule: evm_accounts::{Pallet, Call, Storage, Event}, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - } + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Storage, Config, Event}, + EvmAccountsModule: evm_accounts::{Pallet, Call, Storage, Event}, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, + } ); pub struct ExtBuilder(); impl Default for ExtBuilder { - fn default() -> Self { - Self() - } + fn default() -> Self { + Self() + } } impl ExtBuilder { - pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); - - pallet_balances::GenesisConfig:: { - balances: vec![(bob_account_id(), 100000)], - } - .assimilate_storage(&mut t) - .unwrap(); - - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| System::set_block_number(1)); - ext - } + pub fn build(self) -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![(bob_account_id(), 100000)], + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext + } } pub fn alice() -> libsecp256k1::SecretKey { - libsecp256k1::SecretKey::parse(&keccak_256(b"Alice")).unwrap() + libsecp256k1::SecretKey::parse(&keccak_256(b"Alice")).unwrap() } pub fn bob() -> libsecp256k1::SecretKey { - libsecp256k1::SecretKey::parse(&keccak_256(b"Bob")).unwrap() + libsecp256k1::SecretKey::parse(&keccak_256(b"Bob")).unwrap() } pub fn bob_account_id() -> AccountId { - let address = EvmAccountsModule::eth_address(&bob()); - let mut data = [0u8; 32]; - data[0..4].copy_from_slice(b"evm:"); - data[4..24].copy_from_slice(&address[..]); - AccountId32::from(Into::<[u8; 32]>::into(data)) + let address = EvmAccountsModule::eth_address(&bob()); + let mut data = [0u8; 32]; + data[0..4].copy_from_slice(b"evm:"); + data[4..24].copy_from_slice(&address[..]); + AccountId32::from(Into::<[u8; 32]>::into(data)) } diff --git a/pallets/evm-accounts/src/tests.rs b/pallets/evm-accounts/src/tests.rs index e411394..b508f46 100644 --- a/pallets/evm-accounts/src/tests.rs +++ b/pallets/evm-accounts/src/tests.rs @@ -17,168 +17,195 @@ use super::*; use frame_support::{assert_noop, assert_ok}; -use mock::{alice, bob, RuntimeEvent, EvmAccountsModule, ExtBuilder, RuntimeOrigin, Runtime, System, ALICE, BOB}; +use mock::{ + alice, bob, EvmAccountsModule, ExtBuilder, Runtime, RuntimeEvent, RuntimeOrigin, System, ALICE, + BOB, +}; use std::str::FromStr; #[test] fn claim_account_work() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(EvmAccountsModule::claim_account( - RuntimeOrigin::signed(ALICE), - EvmAccountsModule::eth_address(&alice()), - EvmAccountsModule::eth_sign(&alice(), &ALICE) - )); - System::assert_last_event(RuntimeEvent::EvmAccountsModule(crate::Event::ClaimAccount { - account_id: ALICE, - evm_address: EvmAccountsModule::eth_address(&alice()), - })); - assert!( - Accounts::::contains_key(EvmAccountsModule::eth_address(&alice())) - && EvmAddresses::::contains_key(ALICE) - ); - }); + ExtBuilder::default().build().execute_with(|| { + assert_ok!(EvmAccountsModule::claim_account( + RuntimeOrigin::signed(ALICE), + EvmAccountsModule::eth_address(&alice()), + EvmAccountsModule::eth_sign(&alice(), &ALICE) + )); + System::assert_last_event(RuntimeEvent::EvmAccountsModule( + crate::Event::ClaimAccount { + account_id: ALICE, + evm_address: EvmAccountsModule::eth_address(&alice()), + }, + )); + assert!( + Accounts::::contains_key(EvmAccountsModule::eth_address(&alice())) + && EvmAddresses::::contains_key(ALICE) + ); + }); } #[test] fn claim_account_should_not_work() { - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - EvmAccountsModule::claim_account( - RuntimeOrigin::signed(ALICE), - EvmAccountsModule::eth_address(&bob()), - EvmAccountsModule::eth_sign(&bob(), &BOB) - ), - Error::::InvalidSignature - ); - assert_noop!( - EvmAccountsModule::claim_account( - RuntimeOrigin::signed(ALICE), - EvmAccountsModule::eth_address(&bob()), - EvmAccountsModule::eth_sign(&alice(), &ALICE) - ), - Error::::InvalidSignature - ); - assert_ok!(EvmAccountsModule::claim_account( - RuntimeOrigin::signed(ALICE), - EvmAccountsModule::eth_address(&alice()), - EvmAccountsModule::eth_sign(&alice(), &ALICE) - )); - assert_noop!( - EvmAccountsModule::claim_account( - RuntimeOrigin::signed(ALICE), - EvmAccountsModule::eth_address(&alice()), - EvmAccountsModule::eth_sign(&alice(), &ALICE) - ), - Error::::AccountIdHasMapped - ); - assert_noop!( - EvmAccountsModule::claim_account( - RuntimeOrigin::signed(BOB), - EvmAccountsModule::eth_address(&alice()), - EvmAccountsModule::eth_sign(&alice(), &BOB) - ), - Error::::EthAddressHasMapped - ); - }); + ExtBuilder::default().build().execute_with(|| { + assert_noop!( + EvmAccountsModule::claim_account( + RuntimeOrigin::signed(ALICE), + EvmAccountsModule::eth_address(&bob()), + EvmAccountsModule::eth_sign(&bob(), &BOB) + ), + Error::::InvalidSignature + ); + assert_noop!( + EvmAccountsModule::claim_account( + RuntimeOrigin::signed(ALICE), + EvmAccountsModule::eth_address(&bob()), + EvmAccountsModule::eth_sign(&alice(), &ALICE) + ), + Error::::InvalidSignature + ); + assert_ok!(EvmAccountsModule::claim_account( + RuntimeOrigin::signed(ALICE), + EvmAccountsModule::eth_address(&alice()), + EvmAccountsModule::eth_sign(&alice(), &ALICE) + )); + assert_noop!( + EvmAccountsModule::claim_account( + RuntimeOrigin::signed(ALICE), + EvmAccountsModule::eth_address(&alice()), + EvmAccountsModule::eth_sign(&alice(), &ALICE) + ), + Error::::AccountIdHasMapped + ); + assert_noop!( + EvmAccountsModule::claim_account( + RuntimeOrigin::signed(BOB), + EvmAccountsModule::eth_address(&alice()), + EvmAccountsModule::eth_sign(&alice(), &BOB) + ), + Error::::EthAddressHasMapped + ); + }); } #[test] fn evm_get_account_id() { - ExtBuilder::default().build().execute_with(|| { - let evm_account = EvmAccountsModule::eth_address(&alice()); - let evm_account_to_default = { - let mut bytes = *b"evm:aaaaaaaaaaaaaaaaaaaa\0\0\0\0\0\0\0\0"; - bytes[4..24].copy_from_slice(&evm_account[..]); - AccountId32::from(bytes) - }; - assert_eq!( - EvmAddressMapping::::get_account_id(&evm_account), - evm_account_to_default - ); - - assert_ok!(EvmAccountsModule::claim_account( - RuntimeOrigin::signed(ALICE), - EvmAccountsModule::eth_address(&alice()), - EvmAccountsModule::eth_sign(&alice(), &ALICE) - )); - - assert_eq!(EvmAddressMapping::::get_account_id(&evm_account), ALICE); - assert_eq!( - EvmAddressMapping::::get_evm_address(&ALICE).unwrap(), - evm_account - ); - - assert!(EvmAddressMapping::::is_linked( - &evm_account_to_default, - &evm_account - )); - assert!(EvmAddressMapping::::is_linked(&ALICE, &evm_account)); - }); + ExtBuilder::default().build().execute_with(|| { + let evm_account = EvmAccountsModule::eth_address(&alice()); + let evm_account_to_default = { + let mut bytes = *b"evm:aaaaaaaaaaaaaaaaaaaa\0\0\0\0\0\0\0\0"; + bytes[4..24].copy_from_slice(&evm_account[..]); + AccountId32::from(bytes) + }; + assert_eq!( + EvmAddressMapping::::get_account_id(&evm_account), + evm_account_to_default + ); + + assert_ok!(EvmAccountsModule::claim_account( + RuntimeOrigin::signed(ALICE), + EvmAccountsModule::eth_address(&alice()), + EvmAccountsModule::eth_sign(&alice(), &ALICE) + )); + + assert_eq!( + EvmAddressMapping::::get_account_id(&evm_account), + ALICE + ); + assert_eq!( + EvmAddressMapping::::get_evm_address(&ALICE).unwrap(), + evm_account + ); + + assert!(EvmAddressMapping::::is_linked( + &evm_account_to_default, + &evm_account + )); + assert!(EvmAddressMapping::::is_linked( + &ALICE, + &evm_account + )); + }); } #[test] fn account_to_evm() { - ExtBuilder::default().build().execute_with(|| { - let default_evm_account = EvmAddress::from_str("f0bd9ffde7f9f4394d8cc1d86bf24d87e5d5a9a9").unwrap(); - assert_eq!(EvmAddressMapping::::get_evm_address(&ALICE), None); - - let alice_evm_account = EvmAccountsModule::eth_address(&alice()); - - assert_ok!(EvmAccountsModule::claim_account( - RuntimeOrigin::signed(ALICE), - alice_evm_account, - EvmAccountsModule::eth_sign(&alice(), &ALICE) - )); - - assert_eq!(EvmAddressMapping::::get_account_id(&alice_evm_account), ALICE); - assert_eq!( - EvmAddressMapping::::get_evm_address(&ALICE).unwrap(), - alice_evm_account - ); - - assert_eq!( - EvmAddressMapping::::get_or_create_evm_address(&ALICE), - alice_evm_account - ); - - assert!(EvmAddressMapping::::is_linked(&ALICE, &alice_evm_account)); - assert!(EvmAddressMapping::::is_linked(&ALICE, &default_evm_account)); - }); + ExtBuilder::default().build().execute_with(|| { + let default_evm_account = + EvmAddress::from_str("f0bd9ffde7f9f4394d8cc1d86bf24d87e5d5a9a9").unwrap(); + assert_eq!(EvmAddressMapping::::get_evm_address(&ALICE), None); + + let alice_evm_account = EvmAccountsModule::eth_address(&alice()); + + assert_ok!(EvmAccountsModule::claim_account( + RuntimeOrigin::signed(ALICE), + alice_evm_account, + EvmAccountsModule::eth_sign(&alice(), &ALICE) + )); + + assert_eq!( + EvmAddressMapping::::get_account_id(&alice_evm_account), + ALICE + ); + assert_eq!( + EvmAddressMapping::::get_evm_address(&ALICE).unwrap(), + alice_evm_account + ); + + assert_eq!( + EvmAddressMapping::::get_or_create_evm_address(&ALICE), + alice_evm_account + ); + + assert!(EvmAddressMapping::::is_linked( + &ALICE, + &alice_evm_account + )); + assert!(EvmAddressMapping::::is_linked( + &ALICE, + &default_evm_account + )); + }); } #[test] fn account_to_evm_with_create_default() { - ExtBuilder::default().build().execute_with(|| { - let default_evm_account = EvmAddress::from_str("f0bd9ffde7f9f4394d8cc1d86bf24d87e5d5a9a9").unwrap(); - assert_eq!( - EvmAddressMapping::::get_or_create_evm_address(&ALICE), - default_evm_account - ); - System::assert_last_event(RuntimeEvent::EvmAccountsModule(crate::Event::ClaimAccount { - account_id: ALICE, - evm_address: default_evm_account, - })); - assert_eq!( - EvmAddressMapping::::get_evm_address(&ALICE), - Some(default_evm_account) - ); - - assert_eq!( - EvmAddressMapping::::get_account_id(&default_evm_account), - ALICE - ); - - assert!(EvmAddressMapping::::is_linked(&ALICE, &default_evm_account)); - - let alice_evm_account = EvmAccountsModule::eth_address(&alice()); - - assert_noop!( - EvmAccountsModule::claim_account( - RuntimeOrigin::signed(ALICE), - alice_evm_account, - EvmAccountsModule::eth_sign(&alice(), &ALICE) - ), - Error::::AccountIdHasMapped - ); - }); + ExtBuilder::default().build().execute_with(|| { + let default_evm_account = + EvmAddress::from_str("f0bd9ffde7f9f4394d8cc1d86bf24d87e5d5a9a9").unwrap(); + assert_eq!( + EvmAddressMapping::::get_or_create_evm_address(&ALICE), + default_evm_account + ); + System::assert_last_event(RuntimeEvent::EvmAccountsModule( + crate::Event::ClaimAccount { + account_id: ALICE, + evm_address: default_evm_account, + }, + )); + assert_eq!( + EvmAddressMapping::::get_evm_address(&ALICE), + Some(default_evm_account) + ); + + assert_eq!( + EvmAddressMapping::::get_account_id(&default_evm_account), + ALICE + ); + + assert!(EvmAddressMapping::::is_linked( + &ALICE, + &default_evm_account + )); + + let alice_evm_account = EvmAccountsModule::eth_address(&alice()); + + assert_noop!( + EvmAccountsModule::claim_account( + RuntimeOrigin::signed(ALICE), + alice_evm_account, + EvmAccountsModule::eth_sign(&alice(), &ALICE) + ), + Error::::AccountIdHasMapped + ); + }); } diff --git a/pallets/evm-utility/macro/src/lib.rs b/pallets/evm-utility/macro/src/lib.rs index 644adf3..719e3f8 100644 --- a/pallets/evm-utility/macro/src/lib.rs +++ b/pallets/evm-utility/macro/src/lib.rs @@ -18,55 +18,58 @@ use syn::{parse_macro_input, Expr, ExprLit, Ident, ItemEnum, Lit, LitByteStr, Li #[proc_macro_attribute] pub fn generate_function_selector(_: TokenStream, input: TokenStream) -> TokenStream { - let item = parse_macro_input!(input as ItemEnum); + let item = parse_macro_input!(input as ItemEnum); - let ItemEnum { - attrs, - vis, - enum_token, - ident, - variants, - .. - } = item; + let ItemEnum { + attrs, + vis, + enum_token, + ident, + variants, + .. + } = item; - let mut ident_expressions: Vec = vec![]; - let mut variant_expressions: Vec = vec![]; - for variant in variants { - if let Some((_, Expr::Lit(ExprLit { lit, .. }))) = variant.discriminant { - if let Lit::Str(token) = lit { - let selector = pallet_evm_utility::get_function_selector(&token.value()); - // println!("method: {:?}, selector: {:?}", token.value(), selector); - ident_expressions.push(variant.ident); - variant_expressions.push(Expr::Lit(ExprLit { - lit: Lit::Verbatim(Literal::u32_suffixed(selector)), - attrs: Default::default(), - })); - } else { - panic!("Not method string: `{:?}`", lit); - } - } else { - panic!("Not enum: `{:?}`", variant); - } - } + let mut ident_expressions: Vec = vec![]; + let mut variant_expressions: Vec = vec![]; + for variant in variants { + if let Some((_, Expr::Lit(ExprLit { lit, .. }))) = variant.discriminant { + if let Lit::Str(token) = lit { + let selector = pallet_evm_utility::get_function_selector(&token.value()); + // println!("method: {:?}, selector: {:?}", token.value(), selector); + ident_expressions.push(variant.ident); + variant_expressions.push(Expr::Lit(ExprLit { + lit: Lit::Verbatim(Literal::u32_suffixed(selector)), + attrs: Default::default(), + })); + } else { + panic!("Not method string: `{:?}`", lit); + } + } else { + panic!("Not enum: `{:?}`", variant); + } + } - (quote! { - #(#attrs)* - #vis #enum_token #ident { - #( - #ident_expressions = #variant_expressions, - )* - } - }) - .into() + (quote! { + #(#attrs)* + #vis #enum_token #ident { + #( + #ident_expressions = #variant_expressions, + )* + } + }) + .into() } #[proc_macro] pub fn keccak256(input: TokenStream) -> TokenStream { - let lit_str = parse_macro_input!(input as LitStr); + let lit_str = parse_macro_input!(input as LitStr); - let result = pallet_evm_utility::sha3_256(&lit_str.value()); + let result = pallet_evm_utility::sha3_256(&lit_str.value()); - let eval = Lit::ByteStr(LitByteStr::new(result.as_ref(), proc_macro2::Span::call_site())); + let eval = Lit::ByteStr(LitByteStr::new( + result.as_ref(), + proc_macro2::Span::call_site(), + )); - quote!(#eval).into() -} \ No newline at end of file + quote!(#eval).into() +} diff --git a/pallets/evm-utility/src/lib.rs b/pallets/evm-utility/src/lib.rs index ba1c14e..eb8551c 100644 --- a/pallets/evm-utility/src/lib.rs +++ b/pallets/evm-utility/src/lib.rs @@ -25,19 +25,19 @@ pub use evm_gasometer; pub use evm_runtime; pub fn sha3_256(s: &str) -> [u8; 32] { - let mut result = [0u8; 32]; + let mut result = [0u8; 32]; - // create a SHA3-256 object - let mut hasher = Keccak256::new(); - // write input message - hasher.update(s); - // read hash digest - result.copy_from_slice(&hasher.finalize()[..32]); + // create a SHA3-256 object + let mut hasher = Keccak256::new(); + // write input message + hasher.update(s); + // read hash digest + result.copy_from_slice(&hasher.finalize()[..32]); - result + result } pub fn get_function_selector(s: &str) -> u32 { - let result = sha3_256(s); - u32::from_be_bytes(result[..4].try_into().unwrap()) -} \ No newline at end of file + let result = sha3_256(s); + u32::from_be_bytes(result[..4].try_into().unwrap()) +} diff --git a/pallets/template/src/benchmarking.rs b/pallets/template/src/benchmarking.rs index fea9e65..26cf63d 100644 --- a/pallets/template/src/benchmarking.rs +++ b/pallets/template/src/benchmarking.rs @@ -8,13 +8,13 @@ use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_call use frame_system::RawOrigin; benchmarks! { - do_something { - let s in 0 .. 100; - let caller: T::AccountId = whitelisted_caller(); - }: _(RawOrigin::Signed(caller), s) - verify { - assert_eq!(Something::::get(), Some(s)); - } + do_something { + let s in 0 .. 100; + let caller: T::AccountId = whitelisted_caller(); + }: _(RawOrigin::Signed(caller), s) + verify { + assert_eq!(Something::::get(), Some(s)); + } } impl_benchmark_test_suite!(Template, crate::mock::new_test_ext(), crate::mock::Test,); diff --git a/pallets/template/src/lib.rs b/pallets/template/src/lib.rs index 5f3252b..db43001 100644 --- a/pallets/template/src/lib.rs +++ b/pallets/template/src/lib.rs @@ -16,91 +16,91 @@ mod benchmarking; #[frame_support::pallet] pub mod pallet { - use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*}; - use frame_system::pallet_prelude::*; - - /// Configure the pallet by specifying the parameters and types on which it depends. - #[pallet::config] - pub trait Config: frame_system::Config { - /// Because this pallet emits events, it depends on the runtime's definition of an event. - type RuntimeEvent: From> + IsType<::RuntimeEvent>; - } - - #[pallet::pallet] - pub struct Pallet(_); - - // The pallet's runtime storage items. - // https://docs.substrate.io/v3/runtime/storage - #[pallet::storage] - #[pallet::getter(fn something)] - // Learn more about declaring storage items: - // https://docs.substrate.io/v3/runtime/storage#declaring-storage-items - pub type Something = StorageValue<_, u32>; - - // Pallets use events to inform users when important changes are made. - // https://docs.substrate.io/v3/runtime/events-and-errors - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { - /// Event documentation should end with an array that provides descriptive names for event - /// parameters. [something, who] - SomethingStored(u32, T::AccountId), - } - - // Errors inform users that something went wrong. - #[pallet::error] - pub enum Error { - /// Error names should be descriptive. - NoneValue, - /// Errors should have helpful documentation associated with them. - StorageOverflow, - } - - #[pallet::hooks] - impl Hooks> for Pallet {} - - // Dispatchable functions allows users to interact with the pallet and invoke state changes. - // These functions materialize as "extrinsics", which are often compared to transactions. - // Dispatchable functions must be annotated with a weight and must return a DispatchResult. - #[pallet::call] - impl Pallet { - /// An example dispatchable that takes a singles value as a parameter, writes the value to - /// storage and emits an event. This function must be dispatched by a signed extrinsic. - #[pallet::call_index(0)] - #[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))] - pub fn do_something(origin: OriginFor, something: u32) -> DispatchResultWithPostInfo { - // Check that the extrinsic was signed and get the signer. - // This function will return an error if the extrinsic is not signed. - // https://docs.substrate.io/v3/runtime/origins - let who = ensure_signed(origin)?; - - // Update storage. - >::put(something); - - // Emit an event. - Self::deposit_event(Event::SomethingStored(something, who)); - // Return a successful DispatchResultWithPostInfo - Ok(().into()) - } - - /// An example dispatchable that may throw a custom error. - #[pallet::call_index(1)] - #[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().reads_writes(1,1))] - pub fn cause_error(origin: OriginFor) -> DispatchResultWithPostInfo { - let _who = ensure_signed(origin)?; - - // Read a value from storage. - match >::get() { - // Return an error if the value has not been set. - None => Err(Error::::NoneValue)?, - Some(old) => { - // Increment the value read from storage; will error in the event of overflow. - let new = old.checked_add(1).ok_or(Error::::StorageOverflow)?; - // Update the value in storage with the incremented result. - >::put(new); - Ok(().into()) - }, - } - } - } + use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*}; + use frame_system::pallet_prelude::*; + + /// Configure the pallet by specifying the parameters and types on which it depends. + #[pallet::config] + pub trait Config: frame_system::Config { + /// Because this pallet emits events, it depends on the runtime's definition of an event. + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + } + + #[pallet::pallet] + pub struct Pallet(_); + + // The pallet's runtime storage items. + // https://docs.substrate.io/v3/runtime/storage + #[pallet::storage] + #[pallet::getter(fn something)] + // Learn more about declaring storage items: + // https://docs.substrate.io/v3/runtime/storage#declaring-storage-items + pub type Something = StorageValue<_, u32>; + + // Pallets use events to inform users when important changes are made. + // https://docs.substrate.io/v3/runtime/events-and-errors + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + /// Event documentation should end with an array that provides descriptive names for event + /// parameters. [something, who] + SomethingStored(u32, T::AccountId), + } + + // Errors inform users that something went wrong. + #[pallet::error] + pub enum Error { + /// Error names should be descriptive. + NoneValue, + /// Errors should have helpful documentation associated with them. + StorageOverflow, + } + + #[pallet::hooks] + impl Hooks> for Pallet {} + + // Dispatchable functions allows users to interact with the pallet and invoke state changes. + // These functions materialize as "extrinsics", which are often compared to transactions. + // Dispatchable functions must be annotated with a weight and must return a DispatchResult. + #[pallet::call] + impl Pallet { + /// An example dispatchable that takes a singles value as a parameter, writes the value to + /// storage and emits an event. This function must be dispatched by a signed extrinsic. + #[pallet::call_index(0)] + #[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))] + pub fn do_something(origin: OriginFor, something: u32) -> DispatchResultWithPostInfo { + // Check that the extrinsic was signed and get the signer. + // This function will return an error if the extrinsic is not signed. + // https://docs.substrate.io/v3/runtime/origins + let who = ensure_signed(origin)?; + + // Update storage. + >::put(something); + + // Emit an event. + Self::deposit_event(Event::SomethingStored(something, who)); + // Return a successful DispatchResultWithPostInfo + Ok(().into()) + } + + /// An example dispatchable that may throw a custom error. + #[pallet::call_index(1)] + #[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().reads_writes(1,1))] + pub fn cause_error(origin: OriginFor) -> DispatchResultWithPostInfo { + let _who = ensure_signed(origin)?; + + // Read a value from storage. + match >::get() { + // Return an error if the value has not been set. + None => Err(Error::::NoneValue)?, + Some(old) => { + // Increment the value read from storage; will error in the event of overflow. + let new = old.checked_add(1).ok_or(Error::::StorageOverflow)?; + // Update the value in storage with the incremented result. + >::put(new); + Ok(().into()) + } + } + } + } } diff --git a/pallets/template/src/mock.rs b/pallets/template/src/mock.rs index 3c7fc4b..ec43c20 100644 --- a/pallets/template/src/mock.rs +++ b/pallets/template/src/mock.rs @@ -3,8 +3,8 @@ use frame_support::{parameter_types, traits::Everything}; use frame_system as system; use sp_core::H256; use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -12,53 +12,56 @@ type Block = frame_system::mocking::MockBlock; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - TemplateModule: pallet_template::{Pallet, Call, Storage, Event}, - } + pub enum Test where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event}, + TemplateModule: pallet_template::{Pallet, Call, Storage, Event}, + } ); parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const SS58Prefix: u8 = 101; + pub const BlockHashCount: u64 = 250; + pub const SS58Prefix: u8 = 101; } impl system::Config for Test { - type BaseCallFilter = Everything; - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = u64; - type Lookup = IdentityLookup; - type Header = Header; - type RuntimeEvent = RuntimeEvent; - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = SS58Prefix; - type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; + type BaseCallFilter = Everything; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = u64; + type Lookup = IdentityLookup; + type Header = Header; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = BlockHashCount; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = SS58Prefix; + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; } impl pallet_template::Config for Test { - type RuntimeEvent = RuntimeEvent; + type RuntimeEvent = RuntimeEvent; } // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - system::GenesisConfig::default().build_storage::().unwrap().into() + system::GenesisConfig::default() + .build_storage::() + .unwrap() + .into() } diff --git a/pallets/template/src/tests.rs b/pallets/template/src/tests.rs index 6a9a0ca..24fee68 100644 --- a/pallets/template/src/tests.rs +++ b/pallets/template/src/tests.rs @@ -3,18 +3,21 @@ use frame_support::{assert_noop, assert_ok}; #[test] fn it_works_for_default_value() { - new_test_ext().execute_with(|| { - // Dispatch a signed extrinsic. - assert_ok!(TemplateModule::do_something(RuntimeOrigin::signed(1), 42)); - // Read pallet storage and assert an expected result. - assert_eq!(TemplateModule::something(), Some(42)); - }); + new_test_ext().execute_with(|| { + // Dispatch a signed extrinsic. + assert_ok!(TemplateModule::do_something(RuntimeOrigin::signed(1), 42)); + // Read pallet storage and assert an expected result. + assert_eq!(TemplateModule::something(), Some(42)); + }); } #[test] fn correct_error_for_none_value() { - new_test_ext().execute_with(|| { - // Ensure the expected error is thrown when no value is present. - assert_noop!(TemplateModule::cause_error(RuntimeOrigin::signed(1)), Error::::NoneValue); - }); + new_test_ext().execute_with(|| { + // Ensure the expected error is thrown when no value is present. + assert_noop!( + TemplateModule::cause_error(RuntimeOrigin::signed(1)), + Error::::NoneValue + ); + }); } diff --git a/pallets/xc-asset-config/src/benchmarking.rs b/pallets/xc-asset-config/src/benchmarking.rs index 87ce29b..a3a3dd2 100644 --- a/pallets/xc-asset-config/src/benchmarking.rs +++ b/pallets/xc-asset-config/src/benchmarking.rs @@ -92,4 +92,4 @@ impl_benchmark_test_suite!( XcAssetConfig, crate::benchmarking::tests::new_test_ext(), crate::mock::Test -); \ No newline at end of file +); diff --git a/pallets/xc-asset-config/src/migrations.rs b/pallets/xc-asset-config/src/migrations.rs index 120ead3..49603ac 100644 --- a/pallets/xc-asset-config/src/migrations.rs +++ b/pallets/xc-asset-config/src/migrations.rs @@ -103,4 +103,4 @@ impl OnRuntimeUpgrade for MigrationXcmV3 { Ok(()) } -} \ No newline at end of file +} diff --git a/pallets/xc-asset-config/src/mock.rs b/pallets/xc-asset-config/src/mock.rs index 75fad6e..b4105a5 100644 --- a/pallets/xc-asset-config/src/mock.rs +++ b/pallets/xc-asset-config/src/mock.rs @@ -103,4 +103,4 @@ impl ExternalityBuilder { ext.execute_with(|| System::set_block_number(1)); ext } -} \ No newline at end of file +} diff --git a/pallets/xc-asset-config/src/tests.rs b/pallets/xc-asset-config/src/tests.rs index 7e58c4d..ee8170a 100644 --- a/pallets/xc-asset-config/src/tests.rs +++ b/pallets/xc-asset-config/src/tests.rs @@ -95,10 +95,12 @@ fn register_asset_location_and_units_per_sec_is_ok() { Box::new(asset_location.clone().into_versioned()), units )); - System::assert_last_event(mock::RuntimeEvent::XcAssetConfig(Event::UnitsPerSecondChanged { - asset_location: asset_location.clone().into_versioned(), - units_per_second: units, - })); + System::assert_last_event(mock::RuntimeEvent::XcAssetConfig( + Event::UnitsPerSecondChanged { + asset_location: asset_location.clone().into_versioned(), + units_per_second: units, + }, + )); assert_eq!( AssetLocationUnitsPerSecond::::get(&asset_location.clone().into_versioned()) .unwrap(), @@ -165,11 +167,13 @@ fn change_asset_location_is_ok() { Box::new(new_asset_location.clone().into_versioned()), asset_id )); - System::assert_last_event(mock::RuntimeEvent::XcAssetConfig(Event::AssetLocationChanged { - previous_asset_location: asset_location.clone().into_versioned(), - asset_id: asset_id, - new_asset_location: new_asset_location.clone().into_versioned(), - })); + System::assert_last_event(mock::RuntimeEvent::XcAssetConfig( + Event::AssetLocationChanged { + previous_asset_location: asset_location.clone().into_versioned(), + asset_id: asset_id, + new_asset_location: new_asset_location.clone().into_versioned(), + }, + )); // Assert storage state assert_eq!( @@ -218,9 +222,11 @@ fn remove_payment_asset_is_ok() { RuntimeOrigin::root(), Box::new(asset_location.clone().into_versioned()), )); - System::assert_last_event(mock::RuntimeEvent::XcAssetConfig(Event::SupportedAssetRemoved { - asset_location: asset_location.clone().into_versioned(), - })); + System::assert_last_event(mock::RuntimeEvent::XcAssetConfig( + Event::SupportedAssetRemoved { + asset_location: asset_location.clone().into_versioned(), + }, + )); assert!(!AssetLocationUnitsPerSecond::::contains_key( asset_location.clone().into_versioned() )); @@ -424,4 +430,4 @@ fn incompatible_versioned_multilocations_are_not_ok() { Error::::MultiLocationNotSupported ); }) -} \ No newline at end of file +} diff --git a/precompiles/assets-erc20/src/lib.rs b/precompiles/assets-erc20/src/lib.rs index c75f204..e937cfe 100644 --- a/precompiles/assets-erc20/src/lib.rs +++ b/precompiles/assets-erc20/src/lib.rs @@ -297,7 +297,12 @@ where pallet_assets::Pallet::::allowance(asset_id, &owner, &spender).into() }; - Self::_approve(handle, asset_id, spender, amount.saturating_add(added_value)) + Self::_approve( + handle, + asset_id, + spender, + amount.saturating_add(added_value), + ) } fn decrease_allowance( @@ -320,10 +325,20 @@ where pallet_assets::Pallet::::allowance(asset_id, &owner, &spender).into() }; - Self::_approve(handle, asset_id, spender, amount.saturating_sub(subtracted_value)) + Self::_approve( + handle, + asset_id, + spender, + amount.saturating_sub(subtracted_value), + ) } - fn _approve(handle: &mut impl PrecompileHandle, asset_id: AssetIdOf, spender: H160, amount: U256) -> EvmResult { + fn _approve( + handle: &mut impl PrecompileHandle, + asset_id: AssetIdOf, + spender: H160, + amount: U256, + ) -> EvmResult { { let origin = Runtime::AddressMapping::into_account_id(handle.context().caller); let spender: Runtime::AccountId = Runtime::AddressMapping::into_account_id(spender); diff --git a/precompiles/assets-erc20/src/mock.rs b/precompiles/assets-erc20/src/mock.rs index f785ded..88b70b2 100644 --- a/precompiles/assets-erc20/src/mock.rs +++ b/precompiles/assets-erc20/src/mock.rs @@ -21,7 +21,11 @@ use super::*; use codec::{Decode, Encode, MaxEncodedLen}; -use frame_support::{construct_runtime, parameter_types, traits::{Everything, AsEnsureOriginWithArg}, weights::Weight}; +use frame_support::{ + construct_runtime, parameter_types, + traits::{AsEnsureOriginWithArg, Everything}, + weights::Weight, +}; use frame_system::{EnsureRoot, EnsureSigned}; use pallet_evm::{AddressMapping, EnsureAddressNever, EnsureAddressRoot}; @@ -30,7 +34,7 @@ use serde::{Deserialize, Serialize}; use sp_core::{H160, H256}; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, IdentityLookup, ConstU32}, + traits::{BlakeTwo256, ConstU32, IdentityLookup}, }; pub type AccountId = Account; @@ -209,7 +213,7 @@ parameter_types! { impl pallet_evm::Config for Runtime { type FeeCalculator = (); type GasWeightMapping = pallet_evm::FixedGasWeightMapping; - type WeightPerGas = WeightPerGas; + type WeightPerGas = WeightPerGas; type CallOrigin = EnsureAddressRoot; type WithdrawOrigin = EnsureAddressNever; type AddressMapping = AccountId; @@ -242,7 +246,7 @@ parameter_types! { impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; - type AssetId = AssetId; + type AssetId = AssetId; type AssetIdParameter = AssetId; type Currency = Balances; type CreateOrigin = AsEnsureOriginWithArg>; diff --git a/precompiles/assets-erc20/src/tests.rs b/precompiles/assets-erc20/src/tests.rs index 6983153..467aa9a 100644 --- a/precompiles/assets-erc20/src/tests.rs +++ b/precompiles/assets-erc20/src/tests.rs @@ -91,7 +91,6 @@ fn selectors() { crate::SELECTOR_LOG_APPROVAL, &Keccak256::digest(b"Approval(address,address,uint256)")[..] ); - } #[test] @@ -391,7 +390,7 @@ fn increase_allowance() { )) .execute_returns(EvmDataWriter::new().write(true).build()); - precompiles() + precompiles() .prepare_test( Account::Alice, Account::AssetId(0u128), @@ -439,14 +438,18 @@ fn increase_allowance_saturating() { .write(U256::from(u128::MAX) - 1) .build(), ) - .expect_log(LogsBuilder::new(Account::AssetId(0u128).into()).log3( - SELECTOR_LOG_APPROVAL, - Account::Alice, - Account::Bob, - EvmDataWriter::new().write(U256::from(u128::MAX) - 1).build(), - )) + .expect_log( + LogsBuilder::new(Account::AssetId(0u128).into()).log3( + SELECTOR_LOG_APPROVAL, + Account::Alice, + Account::Bob, + EvmDataWriter::new() + .write(U256::from(u128::MAX) - 1) + .build(), + ), + ) .execute_returns(EvmDataWriter::new().write(true).build()); - + precompiles() .prepare_test( Account::Alice, @@ -456,12 +459,16 @@ fn increase_allowance_saturating() { .write(U256::from(5)) .build(), ) - .expect_log(LogsBuilder::new(Account::AssetId(0u128).into()).log3( - SELECTOR_LOG_APPROVAL, - Account::Alice, - Account::Bob, - EvmDataWriter::new().write(U256::from(u128::MAX) + 4).build(), - )) + .expect_log( + LogsBuilder::new(Account::AssetId(0u128).into()).log3( + SELECTOR_LOG_APPROVAL, + Account::Alice, + Account::Bob, + EvmDataWriter::new() + .write(U256::from(u128::MAX) + 4) + .build(), + ), + ) .execute_returns(EvmDataWriter::new().write(true).build()); precompiles() @@ -477,22 +484,22 @@ fn increase_allowance_saturating() { .expect_no_logs() .execute_returns(EvmDataWriter::new().write(U256::from(u128::MAX)).build()); - // precompiles() - // .prepare_test( - // Account::Alice, - // Account::AssetId(0u128), - // EvmDataWriter::new_with_selector(Action::IncreaseAllowance) - // .write(Address(Account::Bob.into())) - // .write(U256::from(2)) - // .build(), - // ) - // .expect_log(LogsBuilder::new(Account::AssetId(0u128).into()).log3( - // SELECTOR_LOG_APPROVAL, - // Account::Alice, - // Account::Bob, - // EvmDataWriter::new().write(U256::MAX).build(), - // )) - // .execute_returns(EvmDataWriter::new().write(true).build()); + // precompiles() + // .prepare_test( + // Account::Alice, + // Account::AssetId(0u128), + // EvmDataWriter::new_with_selector(Action::IncreaseAllowance) + // .write(Address(Account::Bob.into())) + // .write(U256::from(2)) + // .build(), + // ) + // .expect_log(LogsBuilder::new(Account::AssetId(0u128).into()).log3( + // SELECTOR_LOG_APPROVAL, + // Account::Alice, + // Account::Bob, + // EvmDataWriter::new().write(U256::MAX).build(), + // )) + // .execute_returns(EvmDataWriter::new().write(true).build()); }); } @@ -533,7 +540,7 @@ fn decrease_allowance() { )) .execute_returns(EvmDataWriter::new().write(true).build()); - precompiles() + precompiles() .prepare_test( Account::Alice, Account::AssetId(0u128), @@ -552,7 +559,6 @@ fn decrease_allowance() { }); } - #[test] fn decrease_allowance_saturating() { ExtBuilder::default() @@ -590,7 +596,7 @@ fn decrease_allowance_saturating() { )) .execute_returns(EvmDataWriter::new().write(true).build()); - precompiles() + precompiles() .prepare_test( Account::Alice, Account::AssetId(0u128), @@ -609,7 +615,6 @@ fn decrease_allowance_saturating() { }); } - #[test] fn transfer() { ExtBuilder::default() diff --git a/precompiles/utils/src/data.rs b/precompiles/utils/src/data.rs index bbf03c2..6275ac8 100644 --- a/precompiles/utils/src/data.rs +++ b/precompiles/utils/src/data.rs @@ -600,4 +600,4 @@ impl EvmData for Bytes { fn has_static_size() -> bool { false } -} \ No newline at end of file +} diff --git a/precompiles/utils/src/lib.rs b/precompiles/utils/src/lib.rs index e20bee6..927adfe 100644 --- a/precompiles/utils/src/lib.rs +++ b/precompiles/utils/src/lib.rs @@ -373,4 +373,4 @@ fn check_function_modifier( } Ok(()) -} \ No newline at end of file +} diff --git a/precompiles/utils/src/testing.rs b/precompiles/utils/src/testing.rs index 8a05bfd..2e76e34 100644 --- a/precompiles/utils/src/testing.rs +++ b/precompiles/utils/src/testing.rs @@ -427,4 +427,4 @@ impl core::fmt::Debug for PrettyLog { .field("data_utf8", &message) .finish() } -} \ No newline at end of file +} diff --git a/precompiles/utils/src/tests.rs b/precompiles/utils/src/tests.rs index 071a7a8..6544244 100644 --- a/precompiles/utils/src/tests.rs +++ b/precompiles/utils/src/tests.rs @@ -721,4 +721,4 @@ fn read_complex_solidity_function() { // weight assert_eq!(reader.read::().unwrap(), 100u32.into()); -} \ No newline at end of file +} diff --git a/runtime/build.rs b/runtime/build.rs index 9b53d24..18a76f7 100644 --- a/runtime/build.rs +++ b/runtime/build.rs @@ -1,9 +1,9 @@ use substrate_wasm_builder::WasmBuilder; fn main() { - WasmBuilder::new() - .with_current_project() - .export_heap_base() - .import_memory() - .build() + WasmBuilder::new() + .with_current_project() + .export_heap_base() + .import_memory() + .build() } diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 8183e37..22cba14 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -14,16 +14,14 @@ use smallvec::smallvec; use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H160, H256, U256}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, DispatchResult, + create_runtime_str, generic, impl_opaque_keys, traits::{ - AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, - ConvertInto, DispatchInfoOf, Dispatchable, IdentifyAccount, - PostDispatchInfoOf, UniqueSaturatedInto, Verify, + AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, + DispatchInfoOf, Dispatchable, IdentifyAccount, PostDispatchInfoOf, UniqueSaturatedInto, + Verify, }, - transaction_validity::{ - TransactionSource, TransactionValidity, TransactionValidityError - }, - ApplyExtrinsicResult, MultiSignature, + transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError}, + ApplyExtrinsicResult, DispatchResult, MultiSignature, }; use sp_std::prelude::*; @@ -31,20 +29,21 @@ use sp_std::prelude::*; use sp_version::NativeVersion; use sp_version::RuntimeVersion; -use codec::{Encode}; +use codec::Encode; pub use frame_support::traits::EqualPrivilegeOnly; use frame_support::{ - construct_runtime, parameter_types, transactional, + construct_runtime, + dispatch::DispatchClass, + parameter_types, traits::{ - AsEnsureOriginWithArg, Currency as PalletCurrency, EitherOfDiverse, Everything, FindAuthor, - ReservableCurrency, Imbalance, OnUnbalanced, ConstU128, ConstU32, ConstU64, ConstU8, - WithdrawReasons + AsEnsureOriginWithArg, ConstU128, ConstU32, ConstU64, ConstU8, Currency as PalletCurrency, + EitherOfDiverse, Everything, FindAuthor, Imbalance, OnUnbalanced, ReservableCurrency, + WithdrawReasons, }, - dispatch::DispatchClass, + transactional, weights::{ - constants::WEIGHT_REF_TIME_PER_SECOND, - ConstantMultiplier, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients, - WeightToFeePolynomial, + constants::WEIGHT_REF_TIME_PER_SECOND, ConstantMultiplier, Weight, WeightToFeeCoefficient, + WeightToFeeCoefficients, WeightToFeePolynomial, }, ConsensusEngineId, PalletId, }; @@ -68,12 +67,14 @@ use xcm::latest::prelude::BodyId; use xcm_executor::XcmExecutor; // Frontier +use fp_rpc::TransactionStatus; +use pallet_ethereum::{ + Call::transact, EthereumBlockHashMapping, PostLogContent, Transaction as EthereumTransaction, +}; use pallet_evm::{ - EnsureAddressRoot, EnsureAddressNever, Account as EVMAccount, EVMCurrencyAdapter, - FeeCalculator, OnChargeEVMTransaction as OnChargeEVMTransactionT, Runner + Account as EVMAccount, EVMCurrencyAdapter, EnsureAddressNever, EnsureAddressRoot, + FeeCalculator, OnChargeEVMTransaction as OnChargeEVMTransactionT, Runner, }; -use pallet_ethereum::{Call::transact, PostLogContent, EthereumBlockHashMapping, Transaction as EthereumTransaction}; -use fp_rpc::TransactionStatus; use pallet_evm_accounts::{EvmAddressMapping, MergeAccount}; use pallet_evm_precompile_assets_erc20::AddressToAssetId; @@ -127,7 +128,8 @@ pub type SignedExtra = ( ); /// Unchecked extrinsic type as expected by this runtime. -pub type UncheckedExtrinsic = fp_self_contained::UncheckedExtrinsic; +pub type UncheckedExtrinsic = + fp_self_contained::UncheckedExtrinsic; /// Extrinsic type that has already been checked. pub type CheckedExtrinsic = generic::CheckedExtrinsic; @@ -142,57 +144,61 @@ pub type Executive = frame_executive::Executive< >; impl fp_self_contained::SelfContainedCall for RuntimeCall { - type SignedInfo = H160; - - fn is_self_contained(&self) -> bool { - match self { - RuntimeCall::Ethereum(call) => call.is_self_contained(), - _ => false, - } - } - - fn check_self_contained(&self) -> Option> { - match self { - RuntimeCall::Ethereum(call) => call.check_self_contained(), - _ => None, - } - } - - fn validate_self_contained( - &self, - info: &Self::SignedInfo, - dispatch_info: &DispatchInfoOf, - len: usize, - ) -> Option { - match self { - RuntimeCall::Ethereum(call) => call.validate_self_contained(info, dispatch_info, len), - _ => None, - } - } - - fn pre_dispatch_self_contained( - &self, - info: &Self::SignedInfo, + type SignedInfo = H160; + + fn is_self_contained(&self) -> bool { + match self { + RuntimeCall::Ethereum(call) => call.is_self_contained(), + _ => false, + } + } + + fn check_self_contained(&self) -> Option> { + match self { + RuntimeCall::Ethereum(call) => call.check_self_contained(), + _ => None, + } + } + + fn validate_self_contained( + &self, + info: &Self::SignedInfo, dispatch_info: &DispatchInfoOf, len: usize, - ) -> Option> { - match self { - RuntimeCall::Ethereum(call) => call.pre_dispatch_self_contained(info, dispatch_info, len), - _ => None, - } - } - - fn apply_self_contained( - self, - info: Self::SignedInfo, - ) -> Option>> { - match self { - call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch( - RuntimeOrigin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)), - )), - _ => None, - } - } + ) -> Option { + match self { + RuntimeCall::Ethereum(call) => call.validate_self_contained(info, dispatch_info, len), + _ => None, + } + } + + fn pre_dispatch_self_contained( + &self, + info: &Self::SignedInfo, + dispatch_info: &DispatchInfoOf, + len: usize, + ) -> Option> { + match self { + RuntimeCall::Ethereum(call) => { + call.pre_dispatch_self_contained(info, dispatch_info, len) + } + _ => None, + } + } + + fn apply_self_contained( + self, + info: Self::SignedInfo, + ) -> Option>> { + match self { + call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { + Some(call.dispatch(RuntimeOrigin::from( + pallet_ethereum::RawOrigin::EthereumTransaction(info), + ))) + } + _ => None, + } + } } /// Handles converting a weight scalar to a fee value, based on the scale and granularity of the @@ -292,8 +298,8 @@ const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); /// We allow for 0.5 of a second of compute with a 12 second average block time. const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts( - WEIGHT_REF_TIME_PER_SECOND.saturating_div(2), - cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64, + WEIGHT_REF_TIME_PER_SECOND.saturating_div(2), + cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64, ); pub const fn deposit(items: u32, bytes: u32) -> Balance { @@ -623,7 +629,7 @@ impl pallet_scheduler::Config for Runtime { parameter_types! { pub const MinVestedTransfer: Balance = 15 * OTP; pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons = - WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE); + WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE); } impl pallet_vesting::Config for Runtime { @@ -667,95 +673,101 @@ impl pallet_treasury::Config for Runtime { pub struct MergeAccountEvm; impl MergeAccount for MergeAccountEvm { -#[transactional] -fn merge_account(source: &AccountId, dest: &AccountId) -> DispatchResult { - // unreserve all reserved currency - >::unreserve(source, Balances::reserved_balance(source)); - - // transfer all free to dest - match Balances::transfer(Some(source.clone()).into(), dest.clone().into(), Balances::free_balance(source)) { - Ok(_) => Ok(()), - Err(e) => Err(e.error), - } - } + #[transactional] + fn merge_account(source: &AccountId, dest: &AccountId) -> DispatchResult { + // unreserve all reserved currency + >::unreserve(source, Balances::reserved_balance(source)); + + // transfer all free to dest + match Balances::transfer( + Some(source.clone()).into(), + dest.clone().into(), + Balances::free_balance(source), + ) { + Ok(_) => Ok(()), + Err(e) => Err(e.error), + } + } } impl pallet_evm_accounts::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type Currency = Balances; + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; type ChainId = ChainId; - type AddressMapping = EvmAddressMapping; - type MergeAccount = MergeAccountEvm; - type WeightInfo = weights::evm_accounts_weights::WeightInfo; + type AddressMapping = EvmAddressMapping; + type MergeAccount = MergeAccountEvm; + type WeightInfo = weights::evm_accounts_weights::WeightInfo; } parameter_types! { - pub DefaultBaseFeePerGas: U256 = U256::from(1_000_000_000); + pub DefaultBaseFeePerGas: U256 = U256::from(1_000_000_000); pub DefaultElasticity: Permill = Permill::from_parts(125_000); } pub struct BaseFeeThreshold; impl pallet_base_fee::BaseFeeThreshold for BaseFeeThreshold { - fn lower() -> Permill { - Permill::zero() - } - fn ideal() -> Permill { - Permill::from_parts(500_000) - } - fn upper() -> Permill { - Permill::from_parts(1_000_000) - } + fn lower() -> Permill { + Permill::zero() + } + fn ideal() -> Permill { + Permill::from_parts(500_000) + } + fn upper() -> Permill { + Permill::from_parts(1_000_000) + } } impl pallet_base_fee::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type Threshold = BaseFeeThreshold; - type DefaultBaseFeePerGas = DefaultBaseFeePerGas; + type RuntimeEvent = RuntimeEvent; + type Threshold = BaseFeeThreshold; + type DefaultBaseFeePerGas = DefaultBaseFeePerGas; type DefaultElasticity = DefaultElasticity; } type CurrencyAccountId = ::AccountId; type BalanceFor = - <::Currency as PalletCurrency>>::Balance; + <::Currency as PalletCurrency>>::Balance; -type PositiveImbalanceFor = - <::Currency as PalletCurrency>>::PositiveImbalance; +type PositiveImbalanceFor = <::Currency as PalletCurrency< + CurrencyAccountId, +>>::PositiveImbalance; -type NegativeImbalanceFor = - <::Currency as PalletCurrency>>::NegativeImbalance; +type NegativeImbalanceFor = <::Currency as PalletCurrency< + CurrencyAccountId, +>>::NegativeImbalance; pub struct OnChargeEVMTransaction(sp_std::marker::PhantomData); impl OnChargeEVMTransactionT for OnChargeEVMTransaction where - T: pallet_evm::Config, - PositiveImbalanceFor: Imbalance, Opposite = NegativeImbalanceFor>, - NegativeImbalanceFor: Imbalance, Opposite = PositiveImbalanceFor>, - OU: OnUnbalanced>, - U256: UniqueSaturatedInto> + T: pallet_evm::Config, + PositiveImbalanceFor: Imbalance, Opposite = NegativeImbalanceFor>, + NegativeImbalanceFor: Imbalance, Opposite = PositiveImbalanceFor>, + OU: OnUnbalanced>, + U256: UniqueSaturatedInto>, { - type LiquidityInfo = Option>; - - fn withdraw_fee(who: &H160, fee: U256) -> Result> { - EVMCurrencyAdapter::<::Currency, ()>::withdraw_fee(who, fee) - } - - fn correct_and_deposit_fee( - who: &H160, - corrected_fee: U256, - base_fee: U256, - already_withdrawn: Self::LiquidityInfo, - ) -> Self::LiquidityInfo { - ::Currency, OU> as OnChargeEVMTransactionT< - T, - >>::correct_and_deposit_fee(who, corrected_fee, base_fee, already_withdrawn) - } - - fn pay_priority_fee(tip: Self::LiquidityInfo) { - if let Some(tip) = tip { - OU::on_unbalanced(tip); - } - } + type LiquidityInfo = Option>; + + fn withdraw_fee(who: &H160, fee: U256) -> Result> { + EVMCurrencyAdapter::<::Currency, ()>::withdraw_fee(who, fee) + } + + fn correct_and_deposit_fee( + who: &H160, + corrected_fee: U256, + base_fee: U256, + already_withdrawn: Self::LiquidityInfo, + ) -> Self::LiquidityInfo { + ::Currency, OU> as OnChargeEVMTransactionT< + T, + >>::correct_and_deposit_fee(who, corrected_fee, base_fee, already_withdrawn) + } + + fn pay_priority_fee(tip: Self::LiquidityInfo) { + if let Some(tip) = tip { + OU::on_unbalanced(tip); + } + } } /// Current approximation of the gas/s consumption considering @@ -791,37 +803,37 @@ parameter_types! { } impl pallet_evm::Config for Runtime { - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type RuntimeEvent = RuntimeEvent; - type BlockGasLimit = BlockGasLimit; - type ChainId = ChainId; - type BlockHashMapping = EthereumBlockHashMapping; - type Runner = pallet_evm::runner::stack::Runner; + type BlockGasLimit = BlockGasLimit; + type ChainId = ChainId; + type BlockHashMapping = EthereumBlockHashMapping; + type Runner = pallet_evm::runner::stack::Runner; type CallOrigin = EnsureAddressRoot; - type WithdrawOrigin = EnsureAddressNever; - type AddressMapping = EvmAddressMapping; + type WithdrawOrigin = EnsureAddressNever; + type AddressMapping = EvmAddressMapping; - type FeeCalculator = BaseFee; - type GasWeightMapping = pallet_evm::FixedGasWeightMapping; + type FeeCalculator = BaseFee; + type GasWeightMapping = pallet_evm::FixedGasWeightMapping; type WeightPerGas = WeightPerGas; - type OnChargeTransaction = OnChargeEVMTransaction; + type OnChargeTransaction = OnChargeEVMTransaction; type OnCreate = (); - type FindAuthor = FindAuthorTruncated; - type PrecompilesType = FrontierPrecompiles; - type PrecompilesValue = PrecompilesValue; + type FindAuthor = FindAuthorTruncated; + type PrecompilesType = FrontierPrecompiles; + type PrecompilesValue = PrecompilesValue; type Timestamp = Timestamp; type WeightInfo = pallet_evm::weights::SubstrateWeight; } parameter_types! { - pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes; + pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes; } impl pallet_ethereum::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type StateRoot = pallet_ethereum::IntermediateStateRoot; + type RuntimeEvent = RuntimeEvent; + type StateRoot = pallet_ethereum::IntermediateStateRoot; type PostLogContent = PostBlockAndTxnHashes; type ExtraDataLength = ConstU32<30>; } @@ -856,31 +868,31 @@ impl AddressToAssetId for Runtime { } parameter_types! { - pub const AssetDeposit: Balance = 100 * OTP; - pub const ApprovalDeposit: Balance = 0; - pub const StringLimit: u32 = 50; - pub const MetadataDepositBase: Balance = 10 * OTP; - pub const MetadataDepositPerByte: Balance = 1 * OTP; + pub const AssetDeposit: Balance = 100 * OTP; + pub const ApprovalDeposit: Balance = 0; + pub const StringLimit: u32 = 50; + pub const MetadataDepositBase: Balance = 10 * OTP; + pub const MetadataDepositPerByte: Balance = 1 * OTP; } impl pallet_assets::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type Balance = u128; - type AssetId = AssetId; + type RuntimeEvent = RuntimeEvent; + type Balance = u128; + type AssetId = AssetId; type AssetIdParameter = codec::Compact; - type Currency = Balances; + type Currency = Balances; type CreateOrigin = AsEnsureOriginWithArg>; - type ForceOrigin = EnsureRoot; - type AssetDeposit = AssetDeposit; - type AssetAccountDeposit = ConstU128; - type MetadataDepositBase = MetadataDepositBase; - type MetadataDepositPerByte = MetadataDepositPerByte; - type ApprovalDeposit = ApprovalDeposit; - type StringLimit = StringLimit; - type Freezer = (); - type Extra = (); + type ForceOrigin = EnsureRoot; + type AssetDeposit = AssetDeposit; + type AssetAccountDeposit = ConstU128; + type MetadataDepositBase = MetadataDepositBase; + type MetadataDepositPerByte = MetadataDepositPerByte; + type ApprovalDeposit = ApprovalDeposit; + type StringLimit = StringLimit; + type Freezer = (); + type Extra = (); type CallbackHandle = (); - type WeightInfo = pallet_assets::weights::SubstrateWeight; + type WeightInfo = pallet_assets::weights::SubstrateWeight; type RemoveItemsLimit = ConstU32<656>; } @@ -906,135 +918,135 @@ impl pallet_xc_asset_config::Config for Runtime { } parameter_types! { - pub const PreimageMaxSize: u32 = 4096 * 1024; - pub const PreimageBaseDeposit: Balance = deposit(2, 64); - pub const PreimageByteDeposit: Balance = 1 * MILLIOTP; + pub const PreimageMaxSize: u32 = 4096 * 1024; + pub const PreimageBaseDeposit: Balance = deposit(2, 64); + pub const PreimageByteDeposit: Balance = 1 * MILLIOTP; } impl pallet_preimage::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type Currency = Balances; - type ManagerOrigin = EnsureRoot; - type BaseDeposit = PreimageBaseDeposit; - type ByteDeposit = PreimageByteDeposit; + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type ManagerOrigin = EnsureRoot; + type BaseDeposit = PreimageBaseDeposit; + type ByteDeposit = PreimageByteDeposit; type WeightInfo = pallet_preimage::weights::SubstrateWeight; } impl pallet_utility::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type RuntimeCall = RuntimeCall; - type PalletsOrigin = OriginCaller; - type WeightInfo = pallet_utility::weights::SubstrateWeight; + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type PalletsOrigin = OriginCaller; + type WeightInfo = pallet_utility::weights::SubstrateWeight; } parameter_types! { - pub const CouncilMotionDuration: BlockNumber = 3 * DAYS; - pub const CouncilMaxProposals: u32 = 100; - pub const CouncilMaxMembers: u32 = 5; + pub const CouncilMotionDuration: BlockNumber = 3 * DAYS; + pub const CouncilMaxProposals: u32 = 100; + pub const CouncilMaxMembers: u32 = 5; } type CouncilCollective = pallet_collective::Instance1; impl pallet_collective::Config for Runtime { - type RuntimeOrigin = RuntimeOrigin; - type Proposal = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type MotionDuration = CouncilMotionDuration; - type MaxProposals = CouncilMaxProposals; - type MaxMembers = CouncilMaxMembers; - type DefaultVote = pallet_collective::MoreThanMajorityThenPrimeDefaultVote; + type RuntimeOrigin = RuntimeOrigin; + type Proposal = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type MotionDuration = CouncilMotionDuration; + type MaxProposals = CouncilMaxProposals; + type MaxMembers = CouncilMaxMembers; + type DefaultVote = pallet_collective::MoreThanMajorityThenPrimeDefaultVote; type SetMembersOrigin = EnsureRoot; type WeightInfo = pallet_collective::weights::SubstrateWeight; } parameter_types! { - pub const LaunchPeriod: BlockNumber = 5 * DAYS; - pub const VotingPeriod: BlockNumber = 5 * DAYS; + pub const LaunchPeriod: BlockNumber = 5 * DAYS; + pub const VotingPeriod: BlockNumber = 5 * DAYS; pub const VotingLockingPeriod: BlockNumber = 1 * DAYS; - pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS; - pub const MinimumDeposit: Balance = 1000 * OTP; - pub const EnactmentPeriod: BlockNumber = 2 * DAYS; - pub const CooloffPeriod: BlockNumber = 7 * DAYS; - pub const MaxProposals: u32 = 100; + pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS; + pub const MinimumDeposit: Balance = 1000 * OTP; + pub const EnactmentPeriod: BlockNumber = 2 * DAYS; + pub const CooloffPeriod: BlockNumber = 7 * DAYS; + pub const MaxProposals: u32 = 100; } type EnsureRootOrTwoFiftsOfCouncil = EitherOfDiverse< - EnsureRoot, - pallet_collective::EnsureProportionAtLeast, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast, >; type EnsureRootOrThreeFiftsOfCouncil = EitherOfDiverse< - EnsureRoot, - pallet_collective::EnsureProportionAtLeast, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast, >; type EnsureRootOrFourFiftsOfCouncil = EitherOfDiverse< - EnsureRoot, - pallet_collective::EnsureProportionAtLeast, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast, >; impl pallet_democracy::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type Currency = Balances; - type EnactmentPeriod = EnactmentPeriod; - type LaunchPeriod = LaunchPeriod; - type VotingPeriod = VotingPeriod; - type VoteLockingPeriod = VotingLockingPeriod; // Same as EnactmentPeriod - type MinimumDeposit = MinimumDeposit; - /// A straight majority of the council can decide what their next motion is. - type ExternalOrigin = EnsureRootOrTwoFiftsOfCouncil; - /// A super-majority can have the next scheduled referendum be a straight majority-carries vote. - type ExternalMajorityOrigin = EnsureRootOrThreeFiftsOfCouncil; - /// A unanimous council can have the next scheduled referendum be a straight default-carries - /// (NTB) vote. - type ExternalDefaultOrigin = EnsureRootOrThreeFiftsOfCouncil; - type SubmitOrigin = EnsureSigned; - /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote - /// be tabled immediately and with a shorter voting/enactment period. - type FastTrackOrigin = EnsureRootOrThreeFiftsOfCouncil; - type InstantOrigin = EnsureRootOrFourFiftsOfCouncil; - type InstantAllowed = frame_support::traits::ConstBool; - type FastTrackVotingPeriod = FastTrackVotingPeriod; - // To cancel a proposal which has been passed, 3/5 of the council must agree to it. - type CancellationOrigin = EnsureRootOrThreeFiftsOfCouncil; - // To cancel a proposal before it has been passed, the technical committee must be unanimous or - // Root must agree. - type CancelProposalOrigin = EnsureRootOrThreeFiftsOfCouncil; - type BlacklistOrigin = EnsureRoot; - // Any single technical committee member may veto a coming council proposal, however they can - // only do it once and it lasts only for the cool-off period. - type VetoOrigin = pallet_collective::EnsureMember; - type CooloffPeriod = CooloffPeriod; - type Slash = Treasury; - type Scheduler = Scheduler; - type PalletsOrigin = OriginCaller; - type MaxVotes = ConstU32<100>; - type MaxProposals = MaxProposals; - type Preimages = Preimage; - type MaxDeposits = ConstU32<100>; - type MaxBlacklisted = ConstU32<100>; + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type EnactmentPeriod = EnactmentPeriod; + type LaunchPeriod = LaunchPeriod; + type VotingPeriod = VotingPeriod; + type VoteLockingPeriod = VotingLockingPeriod; // Same as EnactmentPeriod + type MinimumDeposit = MinimumDeposit; + /// A straight majority of the council can decide what their next motion is. + type ExternalOrigin = EnsureRootOrTwoFiftsOfCouncil; + /// A super-majority can have the next scheduled referendum be a straight majority-carries vote. + type ExternalMajorityOrigin = EnsureRootOrThreeFiftsOfCouncil; + /// A unanimous council can have the next scheduled referendum be a straight default-carries + /// (NTB) vote. + type ExternalDefaultOrigin = EnsureRootOrThreeFiftsOfCouncil; + type SubmitOrigin = EnsureSigned; + /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote + /// be tabled immediately and with a shorter voting/enactment period. + type FastTrackOrigin = EnsureRootOrThreeFiftsOfCouncil; + type InstantOrigin = EnsureRootOrFourFiftsOfCouncil; + type InstantAllowed = frame_support::traits::ConstBool; + type FastTrackVotingPeriod = FastTrackVotingPeriod; + // To cancel a proposal which has been passed, 3/5 of the council must agree to it. + type CancellationOrigin = EnsureRootOrThreeFiftsOfCouncil; + // To cancel a proposal before it has been passed, the technical committee must be unanimous or + // Root must agree. + type CancelProposalOrigin = EnsureRootOrThreeFiftsOfCouncil; + type BlacklistOrigin = EnsureRoot; + // Any single technical committee member may veto a coming council proposal, however they can + // only do it once and it lasts only for the cool-off period. + type VetoOrigin = pallet_collective::EnsureMember; + type CooloffPeriod = CooloffPeriod; + type Slash = Treasury; + type Scheduler = Scheduler; + type PalletsOrigin = OriginCaller; + type MaxVotes = ConstU32<100>; + type MaxProposals = MaxProposals; + type Preimages = Preimage; + type MaxDeposits = ConstU32<100>; + type MaxBlacklisted = ConstU32<100>; type WeightInfo = pallet_democracy::weights::SubstrateWeight; } parameter_types! { - pub const BasicDeposit: Balance = deposit(1, 258); // 258 bytes on-chain - pub const FieldDeposit: Balance = deposit(1, 66); // 66 bytes on-chain - pub const SubAccountDeposit: Balance = deposit(1, 53); // 53 bytes on-chain - pub const MaxSubAccounts: u32 = 100; - pub const MaxAdditionalFields: u32 = 100; - pub const MaxRegistrars: u32 = 20; + pub const BasicDeposit: Balance = deposit(1, 258); // 258 bytes on-chain + pub const FieldDeposit: Balance = deposit(1, 66); // 66 bytes on-chain + pub const SubAccountDeposit: Balance = deposit(1, 53); // 53 bytes on-chain + pub const MaxSubAccounts: u32 = 100; + pub const MaxAdditionalFields: u32 = 100; + pub const MaxRegistrars: u32 = 20; } impl pallet_identity::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type Currency = Balances; - type BasicDeposit = BasicDeposit; - type FieldDeposit = FieldDeposit; - type SubAccountDeposit = SubAccountDeposit; - type MaxSubAccounts = MaxSubAccounts; - type MaxAdditionalFields = MaxAdditionalFields; - type MaxRegistrars = MaxRegistrars; - type Slashed = Treasury; - type ForceOrigin = EnsureRootOrThreeFiftsOfCouncil; - type RegistrarOrigin = EnsureRootOrThreeFiftsOfCouncil; - type WeightInfo = pallet_identity::weights::SubstrateWeight; + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type BasicDeposit = BasicDeposit; + type FieldDeposit = FieldDeposit; + type SubAccountDeposit = SubAccountDeposit; + type MaxSubAccounts = MaxSubAccounts; + type MaxAdditionalFields = MaxAdditionalFields; + type MaxRegistrars = MaxRegistrars; + type Slashed = Treasury; + type ForceOrigin = EnsureRootOrThreeFiftsOfCouncil; + type RegistrarOrigin = EnsureRootOrThreeFiftsOfCouncil; + type WeightInfo = pallet_identity::weights::SubstrateWeight; } // Create the runtime by composing the FRAME pallets that were previously configured. @@ -1075,7 +1087,7 @@ construct_runtime!( DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, // Frontier - EVM: pallet_evm::{Pallet, Config, Call, Storage, Event} = 50, + EVM: pallet_evm::{Pallet, Config, Call, Storage, Event} = 50, Ethereum: pallet_ethereum::{Pallet, Call, Storage, Event, Config, Origin} = 51, EvmAccounts: pallet_evm_accounts::{Pallet, Call, Storage, Event} = 52, BaseFee: pallet_base_fee::{Pallet, Call, Storage, Config, Event} = 53, @@ -1179,155 +1191,155 @@ impl_runtime_apis! { } impl fp_rpc::EthereumRuntimeRPCApi for Runtime { - fn chain_id() -> u64 { - ::ChainId::get() - } - - fn account_basic(address: H160) -> EVMAccount { - let (account, _) = EVM::account_basic(&address); - account - } - - fn gas_price() -> U256 { - let (gas_price, _) = ::FeeCalculator::min_gas_price(); - gas_price - } - - fn account_code_at(address: H160) -> Vec { - pallet_evm::AccountCodes::::get(address) - } - - fn author() -> H160 { - >::find_author() - } - - fn storage_at(address: H160, index: U256) -> H256 { - let mut tmp = [0u8; 32]; - index.to_big_endian(&mut tmp); + fn chain_id() -> u64 { + ::ChainId::get() + } + + fn account_basic(address: H160) -> EVMAccount { + let (account, _) = EVM::account_basic(&address); + account + } + + fn gas_price() -> U256 { + let (gas_price, _) = ::FeeCalculator::min_gas_price(); + gas_price + } + + fn account_code_at(address: H160) -> Vec { + pallet_evm::AccountCodes::::get(address) + } + + fn author() -> H160 { + >::find_author() + } + + fn storage_at(address: H160, index: U256) -> H256 { + let mut tmp = [0u8; 32]; + index.to_big_endian(&mut tmp); pallet_evm::AccountStorages::::get(address, H256::from_slice(&tmp[..])) - } - - fn call( - from: H160, - to: H160, - data: Vec, - value: U256, - gas_limit: U256, - max_fee_per_gas: Option, - max_priority_fee_per_gas: Option, - nonce: Option, - estimate: bool, - access_list: Option)>>, - ) -> Result { - let config = if estimate { - let mut config = ::config().clone(); - config.estimate = true; - Some(config) - } else { - None - }; - - let is_transactional = false; + } + + fn call( + from: H160, + to: H160, + data: Vec, + value: U256, + gas_limit: U256, + max_fee_per_gas: Option, + max_priority_fee_per_gas: Option, + nonce: Option, + estimate: bool, + access_list: Option)>>, + ) -> Result { + let config = if estimate { + let mut config = ::config().clone(); + config.estimate = true; + Some(config) + } else { + None + }; + + let is_transactional = false; let validate = true; - ::Runner::call( - from, - to, - data, - value, - gas_limit.unique_saturated_into(), - max_fee_per_gas, - max_priority_fee_per_gas, - nonce, - access_list.unwrap_or_default(), - is_transactional, + ::Runner::call( + from, + to, + data, + value, + gas_limit.unique_saturated_into(), + max_fee_per_gas, + max_priority_fee_per_gas, + nonce, + access_list.unwrap_or_default(), + is_transactional, validate, - config.as_ref().unwrap_or_else(|| ::config()), - ).map_err(|err| err.error.into()) - } - - fn create( - from: H160, - data: Vec, - value: U256, - gas_limit: U256, - max_fee_per_gas: Option, - max_priority_fee_per_gas: Option, - nonce: Option, - estimate: bool, - access_list: Option)>>, - ) -> Result { - let config = if estimate { - let mut config = ::config().clone(); - config.estimate = true; - Some(config) - } else { - None - }; - - let is_transactional = false; + config.as_ref().unwrap_or_else(|| ::config()), + ).map_err(|err| err.error.into()) + } + + fn create( + from: H160, + data: Vec, + value: U256, + gas_limit: U256, + max_fee_per_gas: Option, + max_priority_fee_per_gas: Option, + nonce: Option, + estimate: bool, + access_list: Option)>>, + ) -> Result { + let config = if estimate { + let mut config = ::config().clone(); + config.estimate = true; + Some(config) + } else { + None + }; + + let is_transactional = false; let validate = true; - ::Runner::create( - from, - data, - value, - gas_limit.unique_saturated_into(), - max_fee_per_gas, - max_priority_fee_per_gas, - nonce, - access_list.unwrap_or_default(), - is_transactional, + ::Runner::create( + from, + data, + value, + gas_limit.unique_saturated_into(), + max_fee_per_gas, + max_priority_fee_per_gas, + nonce, + access_list.unwrap_or_default(), + is_transactional, validate, - config.as_ref().unwrap_or_else(|| ::config()), - ).map_err(|err| err.error.into()) - } - - fn current_transaction_statuses() -> Option> { - pallet_ethereum::CurrentTransactionStatuses::::get() - } - - fn current_block() -> Option { - pallet_ethereum::CurrentBlock::::get() - } - - fn current_receipts() -> Option> { - pallet_ethereum::CurrentReceipts::::get() - } - - fn current_all() -> ( - Option, - Option>, - Option> - ) { - ( - pallet_ethereum::CurrentBlock::::get(), - pallet_ethereum::CurrentReceipts::::get(), - pallet_ethereum::CurrentTransactionStatuses::::get() - ) - } - - fn extrinsic_filter( - xts: Vec<::Extrinsic>, - ) -> Vec { - xts.into_iter().filter_map(|xt| match xt.0.function { - RuntimeCall::Ethereum(transact { transaction }) => Some(transaction), - _ => None - }).collect::>() - } - - fn elasticity() -> Option { + config.as_ref().unwrap_or_else(|| ::config()), + ).map_err(|err| err.error.into()) + } + + fn current_transaction_statuses() -> Option> { + pallet_ethereum::CurrentTransactionStatuses::::get() + } + + fn current_block() -> Option { + pallet_ethereum::CurrentBlock::::get() + } + + fn current_receipts() -> Option> { + pallet_ethereum::CurrentReceipts::::get() + } + + fn current_all() -> ( + Option, + Option>, + Option> + ) { + ( + pallet_ethereum::CurrentBlock::::get(), + pallet_ethereum::CurrentReceipts::::get(), + pallet_ethereum::CurrentTransactionStatuses::::get() + ) + } + + fn extrinsic_filter( + xts: Vec<::Extrinsic>, + ) -> Vec { + xts.into_iter().filter_map(|xt| match xt.0.function { + RuntimeCall::Ethereum(transact { transaction }) => Some(transaction), + _ => None + }).collect::>() + } + + fn elasticity() -> Option { Some(pallet_base_fee::Elasticity::::get()) - } + } fn gas_limit_multiplier_support() {} - } + } impl fp_rpc::ConvertTransactionRuntimeApi for Runtime { - fn convert_transaction(transaction: EthereumTransaction) -> ::Extrinsic { - UncheckedExtrinsic::new_unsigned( - pallet_ethereum::Call::::transact { transaction }.into(), - ) - } - } + fn convert_transaction(transaction: EthereumTransaction) -> ::Extrinsic { + UncheckedExtrinsic::new_unsigned( + pallet_ethereum::Call::::transact { transaction }.into(), + ) + } + } impl sp_session::SessionKeys for Runtime { fn generate_session_keys(seed: Option>) -> Vec { @@ -1361,35 +1373,35 @@ impl_runtime_apis! { TransactionPayment::query_fee_details(uxt, len) } fn query_weight_to_fee(weight: Weight) -> Balance { - TransactionPayment::weight_to_fee(weight) - } - fn query_length_to_fee(length: u32) -> Balance { - TransactionPayment::length_to_fee(length) - } + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } } impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi - for Runtime - { - fn query_call_info( - call: RuntimeCall, - len: u32, - ) -> pallet_transaction_payment::RuntimeDispatchInfo { - TransactionPayment::query_call_info(call, len) - } - fn query_call_fee_details( - call: RuntimeCall, - len: u32, - ) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_call_fee_details(call, len) - } + for Runtime + { + fn query_call_info( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::RuntimeDispatchInfo { + TransactionPayment::query_call_info(call, len) + } + fn query_call_fee_details( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_call_fee_details(call, len) + } fn query_weight_to_fee(weight: Weight) -> Balance { - TransactionPayment::weight_to_fee(weight) - } - fn query_length_to_fee(length: u32) -> Balance { - TransactionPayment::length_to_fee(length) - } - } + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } impl cumulus_primitives_core::CollectCollationInfo for Runtime { fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { @@ -1400,20 +1412,20 @@ impl_runtime_apis! { #[cfg(feature = "try-runtime")] impl frame_try_runtime::TryRuntime for Runtime { fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { - let weight = Executive::try_runtime_upgrade(checks).unwrap(); + let weight = Executive::try_runtime_upgrade(checks).unwrap(); (weight, RuntimeBlockWeights::get().max_block) } fn execute_block( - block: Block, - state_root_check: bool, - signature_check: bool, - select: frame_try_runtime::TryStateSelect, - ) -> Weight { - // 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).unwrap() - } + block: Block, + state_root_check: bool, + signature_check: bool, + select: frame_try_runtime::TryStateSelect, + ) -> Weight { + // 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).unwrap() + } } #[cfg(feature = "runtime-benchmarks")] @@ -1446,7 +1458,7 @@ impl_runtime_apis! { impl cumulus_pallet_session_benchmarking::Config for Runtime {} use frame_support::traits::WhitelistedStorageKeys; - let whitelist = AllPalletsWithSystem::whitelisted_storage_keys(); + let whitelist = AllPalletsWithSystem::whitelisted_storage_keys(); let mut batches = Vec::::new(); let params = (&config, &whitelist); diff --git a/runtime/src/precompiles.rs b/runtime/src/precompiles.rs index 081427f..581fb4d 100644 --- a/runtime/src/precompiles.rs +++ b/runtime/src/precompiles.rs @@ -1,4 +1,7 @@ -use pallet_evm::{ExitRevert, IsPrecompileResult, Precompile, PrecompileFailure, PrecompileHandle, PrecompileResult, PrecompileSet}; +use pallet_evm::{ + ExitRevert, IsPrecompileResult, Precompile, PrecompileFailure, PrecompileHandle, + PrecompileResult, PrecompileSet, +}; use sp_core::H160; use sp_std::marker::PhantomData; @@ -15,12 +18,12 @@ pub struct FrontierPrecompiles(PhantomData); impl FrontierPrecompiles where - R: pallet_evm::Config, + R: pallet_evm::Config, { - pub fn new() -> Self { - Self(Default::default()) - } - /// Return all addresses that contain precompiles. This can be used to populate dummy code + pub fn new() -> Self { + Self(Default::default()) + } + /// Return all addresses that contain precompiles. This can be used to populate dummy code /// under the precompile. pub fn used_addresses() -> impl Iterator { sp_std::vec![1, 2, 3, 4, 5, 1024, 1025] @@ -30,14 +33,14 @@ where } impl PrecompileSet for FrontierPrecompiles where - Erc20AssetsPrecompileSet: PrecompileSet, - R: pallet_evm::Config - + pallet_assets::Config + Erc20AssetsPrecompileSet: PrecompileSet, + R: pallet_evm::Config + + pallet_assets::Config + AddressToAssetId<::AssetId>, { - fn execute(&self, handle: &mut impl PrecompileHandle) -> Option { - let address = handle.code_address(); - if let IsPrecompileResult::Answer { is_precompile, .. } = + fn execute(&self, handle: &mut impl PrecompileHandle) -> Option { + let address = handle.code_address(); + if let IsPrecompileResult::Answer { is_precompile, .. } = self.is_precompile(address, u64::MAX) { if is_precompile && address > hash(9) && handle.context().address != address { @@ -47,25 +50,25 @@ where })); } } - match address { - // Ethereum precompiles : - a if a == hash(1) => Some(ECRecover::execute(handle)), - a if a == hash(2) => Some(Sha256::execute(handle)), - a if a == hash(3) => Some(Ripemd160::execute(handle)), - a if a == hash(4) => Some(Identity::execute(handle)), - a if a == hash(5) => Some(Modexp::execute(handle)), - // Non-Frontier specific nor Ethereum precompiles : - a if a == hash(1024) => Some(Sha3FIPS256::execute(handle)), - a if a == hash(1025) => Some(ECRecoverPublicKey::execute(handle)), - // If the address matches asset prefix, the we route through the asset precompile set + match address { + // Ethereum precompiles : + a if a == hash(1) => Some(ECRecover::execute(handle)), + a if a == hash(2) => Some(Sha256::execute(handle)), + a if a == hash(3) => Some(Ripemd160::execute(handle)), + a if a == hash(4) => Some(Identity::execute(handle)), + a if a == hash(5) => Some(Modexp::execute(handle)), + // Non-Frontier specific nor Ethereum precompiles : + a if a == hash(1024) => Some(Sha3FIPS256::execute(handle)), + a if a == hash(1025) => Some(ECRecoverPublicKey::execute(handle)), + // If the address matches asset prefix, the we route through the asset precompile set a if &a.to_fixed_bytes()[0..4] == ASSET_PRECOMPILE_ADDRESS_PREFIX => { Erc20AssetsPrecompileSet::::new().execute(handle) } - _ => None, - } - } + _ => None, + } + } - fn is_precompile(&self, address: H160, gas: u64) -> IsPrecompileResult { + fn is_precompile(&self, address: H160, gas: u64) -> IsPrecompileResult { let assets_precompile = match Erc20AssetsPrecompileSet::::new().is_precompile(address, gas) { IsPrecompileResult::Answer { is_precompile, .. } => is_precompile, @@ -80,5 +83,5 @@ where } fn hash(a: u64) -> H160 { - H160::from_low_u64_be(a) -} \ No newline at end of file + H160::from_low_u64_be(a) +} diff --git a/runtime/src/weights/block_weights.rs b/runtime/src/weights/block_weights.rs index 996ce6c..d468f41 100644 --- a/runtime/src/weights/block_weights.rs +++ b/runtime/src/weights/block_weights.rs @@ -16,32 +16,38 @@ // limitations under the License. pub mod constants { - use frame_support::{ - parameter_types, - weights::{constants, Weight}, - }; + use frame_support::{ + parameter_types, + weights::{constants, Weight}, + }; - parameter_types! { - /// Importing a block with 0 Extrinsics. - pub const BlockExecutionWeight: Weight = - Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0); - } + parameter_types! { + /// Importing a block with 0 Extrinsics. + pub const BlockExecutionWeight: Weight = + Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0); + } - #[cfg(test)] - mod test_weights { - use frame_support::weights::constants; + #[cfg(test)] + mod test_weights { + use frame_support::weights::constants; - /// Checks that the weight exists and is sane. - // NOTE: If this test fails but you are sure that the generated values are fine, - // you can delete it. - #[test] - fn sane() { - let w = super::constants::BlockExecutionWeight::get(); + /// Checks that the weight exists and is sane. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + let w = super::constants::BlockExecutionWeight::get(); - // At least 100 µs. - assert!(w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS, "Weight should be at least 100 µs."); - // At most 50 ms. - assert!(w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS, "Weight should be at most 50 ms."); - } - } + // At least 100 µs. + assert!( + w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS, + "Weight should be at least 100 µs." + ); + // At most 50 ms. + assert!( + w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS, + "Weight should be at most 50 ms." + ); + } + } } diff --git a/runtime/src/weights/extrinsic_weights.rs b/runtime/src/weights/extrinsic_weights.rs index 55b3706..412ca6e 100644 --- a/runtime/src/weights/extrinsic_weights.rs +++ b/runtime/src/weights/extrinsic_weights.rs @@ -16,32 +16,38 @@ // limitations under the License. pub mod constants { - use frame_support::{ - parameter_types, - weights::{constants, Weight}, - }; + use frame_support::{ + parameter_types, + weights::{constants, Weight}, + }; - parameter_types! { - /// Executing a NO-OP `System::remarks` Extrinsic. - pub const ExtrinsicBaseWeight: Weight = - Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0); - } + parameter_types! { + /// Executing a NO-OP `System::remarks` Extrinsic. + pub const ExtrinsicBaseWeight: Weight = + Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0); + } - #[cfg(test)] - mod test_weights { - use frame_support::weights::constants; + #[cfg(test)] + mod test_weights { + use frame_support::weights::constants; - /// Checks that the weight exists and is sane. - // NOTE: If this test fails but you are sure that the generated values are fine, - // you can delete it. - #[test] - fn sane() { - let w = super::constants::ExtrinsicBaseWeight::get(); + /// Checks that the weight exists and is sane. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + let w = super::constants::ExtrinsicBaseWeight::get(); - // At least 10 µs. - assert!(w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS, "Weight should be at least 10 µs."); - // At most 1 ms. - assert!(w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, "Weight should be at most 1 ms."); - } - } + // At least 10 µs. + assert!( + w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS, + "Weight should be at least 10 µs." + ); + // At most 1 ms. + assert!( + w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Weight should be at most 1 ms." + ); + } + } } diff --git a/runtime/src/weights/mod.rs b/runtime/src/weights/mod.rs index 0a83043..70b735d 100644 --- a/runtime/src/weights/mod.rs +++ b/runtime/src/weights/mod.rs @@ -18,14 +18,14 @@ //! Expose the auto generated weight files. pub mod block_weights; -pub mod extrinsic_weights; -pub mod paritydb_weights; -pub mod rocksdb_weights; pub mod evm_accounts_weights; +pub mod extrinsic_weights; pub mod pallet_xc_asset_config; pub mod pallet_xcm; +pub mod paritydb_weights; +pub mod rocksdb_weights; pub use block_weights::constants::BlockExecutionWeight; pub use extrinsic_weights::constants::ExtrinsicBaseWeight; pub use paritydb_weights::constants::ParityDbWeight; -pub use rocksdb_weights::constants::RocksDbWeight; \ No newline at end of file +pub use rocksdb_weights::constants::RocksDbWeight; diff --git a/runtime/src/weights/paritydb_weights.rs b/runtime/src/weights/paritydb_weights.rs index 4338d92..ee5ac12 100644 --- a/runtime/src/weights/paritydb_weights.rs +++ b/runtime/src/weights/paritydb_weights.rs @@ -16,48 +16,48 @@ // limitations under the License. pub mod constants { - use frame_support::{ - parameter_types, - weights::{constants, RuntimeDbWeight}, - }; + use frame_support::{ + parameter_types, + weights::{constants, RuntimeDbWeight}, + }; - parameter_types! { - /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights - /// are available for brave runtime engineers who may want to try this out as default. - pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { - read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS, - write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS, - }; - } + parameter_types! { + /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights + /// are available for brave runtime engineers who may want to try this out as default. + pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + }; + } - #[cfg(test)] - mod test_db_weights { - use super::constants::ParityDbWeight as W; - use frame_support::weights::constants; + #[cfg(test)] + mod test_db_weights { + use super::constants::ParityDbWeight as W; + use frame_support::weights::constants; - /// Checks that all weights exist and have sane values. - // NOTE: If this test fails but you are sure that the generated values are fine, - // you can delete it. - #[test] - fn sane() { - // At least 1 µs. - assert!( - W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, - "Read weight should be at least 1 µs." - ); - assert!( - W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, - "Write weight should be at least 1 µs." - ); - // At most 1 ms. - assert!( - W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, - "Read weight should be at most 1 ms." - ); - assert!( - W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, - "Write weight should be at most 1 ms." - ); - } - } + /// Checks that all weights exist and have sane values. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + // At least 1 µs. + assert!( + W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Read weight should be at least 1 µs." + ); + assert!( + W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Write weight should be at least 1 µs." + ); + // At most 1 ms. + assert!( + W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Read weight should be at most 1 ms." + ); + assert!( + W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Write weight should be at most 1 ms." + ); + } + } } diff --git a/runtime/src/weights/rocksdb_weights.rs b/runtime/src/weights/rocksdb_weights.rs index 1d115d9..b9fb730 100644 --- a/runtime/src/weights/rocksdb_weights.rs +++ b/runtime/src/weights/rocksdb_weights.rs @@ -16,48 +16,48 @@ // limitations under the License. pub mod constants { - use frame_support::{ - parameter_types, - weights::{constants, RuntimeDbWeight}, - }; + use frame_support::{ + parameter_types, + weights::{constants, RuntimeDbWeight}, + }; - parameter_types! { - /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout - /// the runtime. - pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { - read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS, - write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS, - }; - } + parameter_types! { + /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout + /// the runtime. + pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + }; + } - #[cfg(test)] - mod test_db_weights { - use super::constants::RocksDbWeight as W; - use frame_support::weights::constants; + #[cfg(test)] + mod test_db_weights { + use super::constants::RocksDbWeight as W; + use frame_support::weights::constants; - /// Checks that all weights exist and have sane values. - // NOTE: If this test fails but you are sure that the generated values are fine, - // you can delete it. - #[test] - fn sane() { - // At least 1 µs. - assert!( - W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, - "Read weight should be at least 1 µs." - ); - assert!( - W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, - "Write weight should be at least 1 µs." - ); - // At most 1 ms. - assert!( - W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, - "Read weight should be at most 1 ms." - ); - assert!( - W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, - "Write weight should be at most 1 ms." - ); - } - } + /// Checks that all weights exist and have sane values. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + // At least 1 µs. + assert!( + W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Read weight should be at least 1 µs." + ); + assert!( + W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Write weight should be at least 1 µs." + ); + // At most 1 ms. + assert!( + W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Read weight should be at most 1 ms." + ); + assert!( + W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Write weight should be at most 1 ms." + ); + } + } } diff --git a/runtime/src/xcm_config.rs b/runtime/src/xcm_config.rs index 5c56abd..0ebb7f4 100644 --- a/runtime/src/xcm_config.rs +++ b/runtime/src/xcm_config.rs @@ -1,6 +1,6 @@ use super::{ - AccountId, AllPalletsWithSystem, Balances, DealWithFees, Runtime, RuntimeCall, RuntimeEvent, - RuntimeOrigin, ParachainInfo, ParachainSystem, PolkadotXcm, WeightToFee, XcmpQueue, + AccountId, AllPalletsWithSystem, Balances, DealWithFees, ParachainInfo, ParachainSystem, + PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee, XcmpQueue, }; use frame_support::{ match_types, parameter_types, @@ -11,11 +11,11 @@ use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; use xcm::latest::prelude::*; use xcm_builder::{ - AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, - CurrencyAdapter, EnsureXcmOrigin, FixedWeightBounds, IsConcrete, NativeAsset, ParentIsPreset, - RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - UsingComponents, WithComputedOrigin, + AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, CurrencyAdapter, EnsureXcmOrigin, FixedWeightBounds, + IsConcrete, NativeAsset, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, TakeWeightCredit, UsingComponents, WithComputedOrigin, }; use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; @@ -121,44 +121,47 @@ pub type Barrier = ( /// 3. Have a defined proof size weight, e.g. no unbounded vecs in call parameters. pub struct SafeCallFilter; impl Contains for SafeCallFilter { - fn contains(call: &RuntimeCall) -> bool { - #[cfg(feature = "runtime-benchmarks")] - { - if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { - return true - } - } + fn contains(call: &RuntimeCall) -> bool { + #[cfg(feature = "runtime-benchmarks")] + { + if matches!( + call, + RuntimeCall::System(frame_system::Call::remark_with_event { .. }) + ) { + return true; + } + } - match call { - RuntimeCall::System( - frame_system::Call::kill_prefix { .. } | frame_system::Call::set_heap_pages { .. }, - ) | - RuntimeCall::Timestamp(..) | - RuntimeCall::Balances(..) | - RuntimeCall::Session(pallet_session::Call::purge_keys { .. }) | - RuntimeCall::Treasury(..) | - RuntimeCall::Vesting(..) | - RuntimeCall::Utility(pallet_utility::Call::as_derivative { .. }) | - RuntimeCall::Identity( - pallet_identity::Call::add_registrar { .. } | - pallet_identity::Call::set_identity { .. } | - pallet_identity::Call::clear_identity { .. } | - pallet_identity::Call::request_judgement { .. } | - pallet_identity::Call::cancel_request { .. } | - pallet_identity::Call::set_fee { .. } | - pallet_identity::Call::set_account_id { .. } | - pallet_identity::Call::set_fields { .. } | - pallet_identity::Call::provide_judgement { .. } | - pallet_identity::Call::kill_identity { .. } | - pallet_identity::Call::add_sub { .. } | - pallet_identity::Call::rename_sub { .. } | - pallet_identity::Call::remove_sub { .. } | - pallet_identity::Call::quit_sub { .. }, - ) | - RuntimeCall::PolkadotXcm(..) => true, - _ => false, - } - } + match call { + RuntimeCall::System( + frame_system::Call::kill_prefix { .. } | frame_system::Call::set_heap_pages { .. }, + ) + | RuntimeCall::Timestamp(..) + | RuntimeCall::Balances(..) + | RuntimeCall::Session(pallet_session::Call::purge_keys { .. }) + | RuntimeCall::Treasury(..) + | RuntimeCall::Vesting(..) + | RuntimeCall::Utility(pallet_utility::Call::as_derivative { .. }) + | RuntimeCall::Identity( + pallet_identity::Call::add_registrar { .. } + | pallet_identity::Call::set_identity { .. } + | pallet_identity::Call::clear_identity { .. } + | pallet_identity::Call::request_judgement { .. } + | pallet_identity::Call::cancel_request { .. } + | pallet_identity::Call::set_fee { .. } + | pallet_identity::Call::set_account_id { .. } + | pallet_identity::Call::set_fields { .. } + | pallet_identity::Call::provide_judgement { .. } + | pallet_identity::Call::kill_identity { .. } + | pallet_identity::Call::add_sub { .. } + | pallet_identity::Call::rename_sub { .. } + | pallet_identity::Call::remove_sub { .. } + | pallet_identity::Call::quit_sub { .. }, + ) + | RuntimeCall::PolkadotXcm(..) => true, + _ => false, + } + } } pub struct XcmConfig; @@ -173,8 +176,7 @@ impl xcm_executor::Config for XcmConfig { type UniversalLocation = UniversalLocation; type Barrier = Barrier; type Weigher = FixedWeightBounds; - type Trader = - UsingComponents; + type Trader = UsingComponents; type ResponseHandler = PolkadotXcm; type AssetTrap = PolkadotXcm; type AssetClaims = PolkadotXcm; @@ -204,7 +206,7 @@ pub type XcmRouter = ( #[cfg(feature = "runtime-benchmarks")] parameter_types! { - pub ReachableDest: Option = Some(Parent.into()); + pub ReachableDest: Option = Some(Parent.into()); } impl pallet_xcm::Config for Runtime { @@ -232,7 +234,7 @@ impl pallet_xcm::Config for Runtime { type MaxLockers = ConstU32<8>; type WeightInfo = crate::weights::pallet_xcm::WeightInfo; #[cfg(feature = "runtime-benchmarks")] - type ReachableDest = ReachableDest; + type ReachableDest = ReachableDest; } impl cumulus_pallet_xcm::Config for Runtime {