diff --git a/.github/ISSUE_TEMPLATE/release_checklist.md b/.github/ISSUE_TEMPLATE/release_checklist.md index e3c9803fe8..d4375adaf1 100644 --- a/.github/ISSUE_TEMPLATE/release_checklist.md +++ b/.github/ISSUE_TEMPLATE/release_checklist.md @@ -19,7 +19,6 @@ All the preparation specific for this release, for example - `astar-runtime` - `shiden-runtime` - `shibuya-runtime` - - `local-runtime` - `astar-collator` - `xcm-tools` (if needed) - [ ] Check Spec Version bumped for all runtimes diff --git a/.github/workflows/frontier-rpc-tests.yml b/.github/workflows/frontier-rpc-tests.yml index 1ccf2c1dea..44b1825b34 100644 --- a/.github/workflows/frontier-rpc-tests.yml +++ b/.github/workflows/frontier-rpc-tests.yml @@ -25,7 +25,7 @@ jobs: run: rustup target list --installed - name: Build astar-collator - run: cargo build --release --locked --features manual-seal --bin astar-collator + run: cargo build --release --locked --features evm-tracing --bin astar-collator - name: Clone frontier tests run: git clone https://github.com/AstarNetwork/frontier-tests.git --depth 1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8b1fe4ee0c..a23f1d2133 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -45,7 +45,7 @@ Some notes: ### Mandatory PR Labels When submitting a Pull Request (PR), please make sure to include the necessary labels to help us categorize and prioritize your changes. PRs should contain at least one of the following mandatory labels: -- **runtime**: Use this label for changes or additions to the code that relate to runtime **(shiden, astar, shibuya, local)** +- **runtime**: Use this label for changes or additions to the code that relate to runtime **(shiden, astar, shibuya)** - **client**: PRs related to client. - **ci**: PRs related to CI (workflows). - **tests**: PRs related to xcm-simulator tests,rpc-tests or any other kind of test. diff --git a/Cargo.lock b/Cargo.lock index bc4760f7f2..0a94d2f45d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -845,6 +845,7 @@ dependencies = [ "cumulus-client-consensus-proposer", "cumulus-client-consensus-relay-chain", "cumulus-client-network", + "cumulus-client-parachain-inherent", "cumulus-client-service", "cumulus-primitives-aura", "cumulus-primitives-core", @@ -875,7 +876,6 @@ dependencies = [ "frame-try-runtime", "futures 0.3.32", "jsonrpsee", - "local-runtime", "log", "moonbeam-primitives-ext", "moonbeam-rpc-debug", @@ -901,8 +901,6 @@ dependencies = [ "sc-client-db", "sc-consensus", "sc-consensus-aura", - "sc-consensus-babe", - "sc-consensus-grandpa", "sc-consensus-manual-seal", "sc-executor", "sc-network", @@ -7828,97 +7826,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "local-runtime" -version = "5.48.1" -dependencies = [ - "array-bytes 6.2.3", - "astar-primitives", - "dapp-staking-runtime-api", - "ethereum", - "fp-evm", - "fp-rpc", - "fp-self-contained", - "frame-benchmarking", - "frame-executive", - "frame-metadata-hash-extension", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", - "log", - "moonbeam-evm-tracer", - "moonbeam-rpc-primitives-debug", - "moonbeam-rpc-primitives-txpool", - "num_enum 0.5.11", - "pallet-assets", - "pallet-aura", - "pallet-balances", - "pallet-chain-extension-assets", - "pallet-chain-extension-unified-accounts", - "pallet-collective", - "pallet-collective-proxy", - "pallet-contracts", - "pallet-dapp-staking", - "pallet-democracy", - "pallet-dynamic-evm-base-fee", - "pallet-ethereum", - "pallet-ethereum-checked", - "pallet-evm", - "pallet-evm-precompile-assets-erc20", - "pallet-evm-precompile-blake2", - "pallet-evm-precompile-bn128", - "pallet-evm-precompile-dapp-staking", - "pallet-evm-precompile-dispatch", - "pallet-evm-precompile-dispatch-lockdrop", - "pallet-evm-precompile-ed25519", - "pallet-evm-precompile-modexp", - "pallet-evm-precompile-sha3fips", - "pallet-evm-precompile-simple", - "pallet-evm-precompile-sr25519", - "pallet-evm-precompile-substrate-ecdsa", - "pallet-evm-precompile-unified-accounts", - "pallet-grandpa", - "pallet-inflation", - "pallet-insecure-randomness-collective-flip", - "pallet-membership", - "pallet-preimage", - "pallet-proxy", - "pallet-safe-mode", - "pallet-scheduler", - "pallet-static-price-provider", - "pallet-sudo", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-treasury 37.0.0", - "pallet-tx-pause", - "pallet-unified-accounts", - "pallet-utility", - "pallet-vesting", - "parity-scale-codec", - "precompile-utils", - "scale-info", - "serde_json", - "smallvec", - "sp-api", - "sp-arithmetic", - "sp-block-builder", - "sp-consensus-aura", - "sp-core", - "sp-genesis-builder", - "sp-inherents", - "sp-io", - "sp-offchain", - "sp-runtime", - "sp-session", - "sp-std", - "sp-transaction-pool", - "sp-version", - "substrate-wasm-builder", -] - [[package]] name = "lock_api" version = "0.4.14" diff --git a/Cargo.toml b/Cargo.toml index 8eb6d54a13..8770d03cc0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,6 @@ members = [ "bin/collator", "bin/xcm-tools", - "runtime/local", "runtime/astar", "runtime/shiden", "runtime/shibuya", @@ -158,9 +157,7 @@ sc-client-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = " sc-client-db = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } sc-consensus = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } sc-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } -sc-consensus-babe = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } sc-executor = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } -sc-consensus-grandpa = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } sc-consensus-manual-seal = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } sc-network = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } sc-network-sync = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } @@ -209,7 +206,6 @@ frame-system-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk" frame-try-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506", default-features = false } pallet-preimage = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506", default-features = false } pallet-scheduler = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506", default-features = false } -pallet-grandpa = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506", default-features = false } pallet-message-queue = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506", default-features = false } pallet-membership = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506", default-features = false } pallet-collective = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506", default-features = false } @@ -276,6 +272,7 @@ cumulus-client-network = { git = "https://github.com/paritytech/polkadot-sdk", b cumulus-client-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } cumulus-client-collator = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } cumulus-client-consensus-proposer = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } +cumulus-client-parachain-inherent = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } cumulus-primitives-parachain-inherent = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } cumulus-relay-chain-inprocess-interface = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } cumulus-relay-chain-interface = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2506" } @@ -349,7 +346,6 @@ pallet-chain-extension-unified-accounts = { path = "./chain-extensions/unified-a assets-chain-extension-types = { path = "./chain-extensions/types/assets", default-features = false } unified-accounts-chain-extension-types = { path = "./chain-extensions/types/unified-accounts", default-features = false } -local-runtime = { path = "./runtime/local", default-features = false } shibuya-runtime = { path = "./runtime/shibuya", default-features = false } shiden-runtime = { path = "./runtime/shiden", default-features = false } astar-runtime = { path = "./runtime/astar", default-features = false } diff --git a/bin/collator/Cargo.toml b/bin/collator/Cargo.toml index 6bed16c9cd..918cc12abf 100644 --- a/bin/collator/Cargo.toml +++ b/bin/collator/Cargo.toml @@ -62,9 +62,7 @@ sc-client-api = { workspace = true } sc-client-db = { workspace = true } sc-consensus = { workspace = true } sc-consensus-aura = { workspace = true } -sc-consensus-babe = { workspace = true } -sc-consensus-grandpa = { workspace = true } -sc-consensus-manual-seal = { workspace = true, optional = true } +sc-consensus-manual-seal = { workspace = true } sc-executor = { workspace = true } sc-network = { workspace = true } sc-network-sync = { workspace = true } @@ -100,7 +98,6 @@ frame-system-rpc-runtime-api = { workspace = true } # astar-specific dependencies astar-runtime = { workspace = true, features = ["std"] } -local-runtime = { workspace = true, features = ["std"] } shibuya-runtime = { workspace = true, features = ["std"] } shiden-runtime = { workspace = true, features = ["std"] } @@ -126,6 +123,7 @@ cumulus-client-consensus-common = { workspace = true } cumulus-client-consensus-proposer = { workspace = true } cumulus-client-consensus-relay-chain = { workspace = true } cumulus-client-network = { workspace = true } +cumulus-client-parachain-inherent = { workspace = true, default-features = true } cumulus-client-service = { workspace = true } cumulus-primitives-aura = { workspace = true } cumulus-primitives-core = { workspace = true, features = ["std"] } @@ -168,7 +166,6 @@ substrate-build-script-utils = { workspace = true } [features] default = ["sc-cli", "polkadot-cli", "sc-service", "sc-service/rocksdb"] runtime-benchmarks = [ - "local-runtime/runtime-benchmarks", "shibuya-runtime/runtime-benchmarks", "shiden-runtime/runtime-benchmarks", "astar-runtime/runtime-benchmarks", @@ -194,7 +191,6 @@ runtime-benchmarks = [ "pallet-transaction-payment/runtime-benchmarks", ] try-runtime = [ - "local-runtime/try-runtime", "astar-primitives/try-runtime", "astar-runtime/try-runtime", "frame-system/try-runtime", @@ -210,4 +206,3 @@ try-runtime = [ "sp-runtime/try-runtime", "frame-support/try-runtime", ] -manual-seal = ["sc-consensus-manual-seal"] diff --git a/bin/collator/src/command.rs b/bin/collator/src/command.rs index cac73eb8a9..28fd32ae8a 100644 --- a/bin/collator/src/command.rs +++ b/bin/collator/src/command.rs @@ -262,11 +262,7 @@ pub fn run() -> Result<()> { backend, .. } = local::new_partial(&config, &rpc_config)?; - let aux_revert = Box::new(|client, _, blocks| { - sc_consensus_grandpa::revert(client, blocks)?; - Ok(()) - }); - Ok((cmd.run(client, backend, Some(aux_revert)), task_manager)) + Ok((cmd.run(client, backend, None), task_manager)) }) } else { runner.async_run(|config| { @@ -332,7 +328,7 @@ pub fn run() -> Result<()> { }) } else { runner.sync_run(|config| { - cmd.run_with_spec::, local::HostFunctions>( + cmd.run_with_spec::, local::HostFunctions>( Some(config.chain_spec), ) }) diff --git a/bin/collator/src/evm_tracing_types.rs b/bin/collator/src/evm_tracing_types.rs index 7167e99ef5..7cd1eb63ec 100644 --- a/bin/collator/src/evm_tracing_types.rs +++ b/bin/collator/src/evm_tracing_types.rs @@ -98,16 +98,12 @@ pub struct FrontierConfig { #[derive(Debug, Parser)] pub struct EthApiOptions { /// Enable EVM tracing module on a non-authority node. - #[cfg_attr( - not(feature = "manual-seal"), - clap( - long, - conflicts_with = "collator", - conflicts_with = "validator", - value_delimiter = ',' - ) + #[clap( + long, + conflicts_with = "collator", + conflicts_with = "validator", + value_delimiter = ',' )] - #[cfg_attr(feature = "manual-seal", clap(long))] pub ethapi: Vec, /// Number of concurrent tracing tasks. Meant to be shared by both "debug" and "trace" modules. diff --git a/bin/collator/src/local/chain_spec.rs b/bin/collator/src/local/chain_spec.rs index b5c449604f..6248712cfc 100644 --- a/bin/collator/src/local/chain_spec.rs +++ b/bin/collator/src/local/chain_spec.rs @@ -16,25 +16,34 @@ // You should have received a copy of the GNU General Public License // along with Astar. If not, see . -use local_runtime::wasm_binary_unwrap; +use crate::parachain::chain_spec::Extensions; +use astar_primitives::parachain::SHIBUYA_ID; use sc_service::ChainType; +use shibuya_runtime::wasm_binary_unwrap; /// Specialized `ChainSpec` for local network. -pub type ChainSpec = sc_service::GenericChainSpec; +pub type ChainSpec = sc_service::GenericChainSpec; -/// Development config. +/// Development config for local parachain-oriented dev mode. pub fn development_config() -> ChainSpec { let mut properties = serde_json::map::Map::new(); - properties.insert("tokenSymbol".into(), "LOC".into()); + properties.insert("tokenSymbol".into(), "SBY".into()); properties.insert("tokenDecimals".into(), 18.into()); - ChainSpec::builder(wasm_binary_unwrap(), None) - .with_name("Development") - .with_id("dev") - .with_chain_type(ChainType::Development) - .with_properties(properties) - .with_genesis_config(local_runtime::genesis_config::default_config()) - .build() + ChainSpec::builder( + wasm_binary_unwrap(), + Extensions { + relay_chain: "local".into(), + para_id: SHIBUYA_ID, + ..Default::default() + }, + ) + .with_name("Development") + .with_id("dev") + .with_chain_type(ChainType::Development) + .with_properties(properties) + .with_genesis_config_preset_name("development") + .build() } #[cfg(test)] diff --git a/bin/collator/src/local/mod.rs b/bin/collator/src/local/mod.rs index 859723fd15..5ad48cc32b 100644 --- a/bin/collator/src/local/mod.rs +++ b/bin/collator/src/local/mod.rs @@ -25,4 +25,6 @@ mod service; mod chain_spec; pub use chain_spec::*; -pub use service::{new_partial, start_node, HostFunctions, RuntimeApi}; +pub use service::{ + new_partial, start_node, HostFunctions, LocalPendingInherentDataProvider, RuntimeApi, +}; diff --git a/bin/collator/src/local/service.rs b/bin/collator/src/local/service.rs index a1956eb7a2..995b3fe74e 100644 --- a/bin/collator/src/local/service.rs +++ b/bin/collator/src/local/service.rs @@ -22,29 +22,151 @@ use crate::{ evm_tracing_types::{EthApi as EthApiCmd, FrontierConfig}, rpc::tracing, }; +use cumulus_client_parachain_inherent::MockValidationDataInherentDataProvider; +use cumulus_primitives_core::{ + relay_chain::{well_known_keys, AsyncBackingParams, HeadData, UpgradeGoAhead}, + AbridgedHostConfiguration, CollectCollationInfo, ParaId, +}; use fc_consensus::FrontierBlockImport; use fc_rpc_core::types::{FeeHistoryCache, FilterPool}; use fc_storage::StorageOverrideHandler; use futures::{FutureExt, StreamExt}; -use sc_client_api::{Backend, BlockBackend, BlockchainEvents}; -use sc_consensus_grandpa::SharedVoterState; +use parity_scale_codec::Encode; +use sc_client_api::{Backend, BlockchainEvents}; use sc_executor::{HeapAllocStrategy, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY}; use sc_network::NetworkBackend; use sc_service::{error::Error as ServiceError, Configuration, TaskManager}; use sc_telemetry::{Telemetry, TelemetryWorker}; use sc_transaction_pool_api::OffchainTransactionPoolFactory; -#[cfg(not(feature = "manual-seal"))] -use sp_consensus_aura::sr25519::AuthorityPair as AuraPair; -use sp_runtime::traits::Block as BlockT; -use std::{collections::BTreeMap, sync::Arc, time::Duration}; +use sp_api::ProvideRuntimeApi; +use sp_blockchain::HeaderBackend; +use sp_runtime::traits::{Block as BlockT, Header as HeaderT, UniqueSaturatedInto}; +use std::{collections::BTreeMap, marker::PhantomData, ops::Sub, sync::Arc, time::Duration}; -pub use local_runtime::RuntimeApi; +pub use crate::parachain::fake_runtime_api::RuntimeApi; use astar_primitives::*; -/// The minimum period of blocks on which justifications will be -/// imported and generated. -const GRANDPA_JUSTIFICATION_PERIOD: u32 = 512; +/// Local pending inherent provider for ETH pending RPC in dev mode. +pub struct LocalPendingInherentDataProvider { + client: Arc, + para_id: ParaId, + phantom_data: PhantomData, +} + +const RELAY_CHAIN_SLOT_DURATION_MILLIS: u64 = 6000; + +fn build_local_mock_inherent_data( + para_id: ParaId, + current_para_block: u32, + current_para_block_head: Option, + relay_blocks_per_para_block: u32, + relay_slot: u64, + upgrade_go_ahead: Option, +) -> ( + sp_timestamp::InherentDataProvider, + MockValidationDataInherentDataProvider<()>, +) { + let relay_offset = (relay_slot as u32) + .saturating_sub(relay_blocks_per_para_block.saturating_mul(current_para_block)); + + let local_host_config = AbridgedHostConfiguration { + max_code_size: 16 * 1024 * 1024, // 16 MiB (local dev only) + max_head_data_size: 1024 * 1024, + max_upward_queue_count: 8, + max_upward_queue_size: 1024, + max_upward_message_size: 256, + max_upward_message_num_per_candidate: 5, + hrmp_max_message_num_per_candidate: 5, + validation_upgrade_cooldown: 6, + validation_upgrade_delay: 6, + async_backing_params: AsyncBackingParams { + allowed_ancestry_len: 0, + max_candidate_depth: 0, + }, + }; + + let mocked_parachain = MockValidationDataInherentDataProvider::<()> { + current_para_block, + para_id, + current_para_block_head, + relay_blocks_per_para_block, + relay_offset, + para_blocks_per_relay_epoch: 10, + upgrade_go_ahead, + additional_key_values: Some(vec![( + well_known_keys::ACTIVE_CONFIG.to_vec(), + local_host_config.encode(), + )]), + ..Default::default() + }; + + let timestamp = relay_slot.saturating_mul(RELAY_CHAIN_SLOT_DURATION_MILLIS); + let timestamp_provider = sp_timestamp::InherentDataProvider::new(timestamp.into()); + + (timestamp_provider, mocked_parachain) +} + +impl LocalPendingInherentDataProvider { + /// Creates a new instance with the given client and parachain ID. + pub fn new(client: Arc, para_id: ParaId) -> Self { + Self { + client, + para_id, + phantom_data: Default::default(), + } + } +} + +#[async_trait::async_trait] +impl sp_inherents::CreateInherentDataProviders + for LocalPendingInherentDataProvider +where + B: BlockT, + C: HeaderBackend + Send + Sync, +{ + type InherentDataProviders = ( + sp_timestamp::InherentDataProvider, + MockValidationDataInherentDataProvider<()>, + ); + + async fn create_inherent_data_providers( + &self, + _parent: B::Hash, + _extra_args: (), + ) -> Result> { + let relay_slot = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("Current time is always after UNIX_EPOCH; qed") + .as_millis() as u64 + / RELAY_CHAIN_SLOT_DURATION_MILLIS; + + let current_para_block = self + .client + .header(_parent)? + .map(|header| { + UniqueSaturatedInto::::unique_saturated_into(*header.number()) + .saturating_add(1) + }) + .unwrap_or(1); + + let current_para_block_head = self + .client + .header(_parent)? + .map(|header| header.encode().into()); + + let (timestamp_provider, mocked_parachain) = build_local_mock_inherent_data( + self.para_id, + current_para_block, + current_para_block_head, + 1, + relay_slot, + None, + ); + + Ok((timestamp_provider, mocked_parachain)) + } +} /// Parachain host functions #[cfg(feature = "runtime-benchmarks")] @@ -79,17 +201,7 @@ pub fn new_partial( sc_consensus::DefaultImportQueue, sc_transaction_pool::TransactionPoolHandle, ( - FrontierBlockImport< - Block, - sc_consensus_grandpa::GrandpaBlockImport< - FullBackend, - Block, - FullClient, - FullSelectChain, - >, - FullClient, - >, - sc_consensus_grandpa::LinkHalf, + FrontierBlockImport, FullClient>, Option, Arc>, ), @@ -145,54 +257,19 @@ pub fn new_partial( .with_options(config.transaction_pool.clone()) .with_prometheus(config.prometheus_registry()) .build(); - let (grandpa_block_import, grandpa_link) = sc_consensus_grandpa::block_import( - client.clone(), - GRANDPA_JUSTIFICATION_PERIOD, - &(client.clone() as Arc<_>), - select_chain.clone(), - telemetry.as_ref().map(|x| x.handle()), - )?; let frontier_backend = Arc::new(crate::rpc::open_frontier_backend( client.clone(), config, evm_tracing_config, )?); - let frontier_block_import = - FrontierBlockImport::new(grandpa_block_import.clone(), client.clone()); + let frontier_block_import = FrontierBlockImport::new(client.clone(), client.clone()); - #[cfg(feature = "manual-seal")] let import_queue = sc_consensus_manual_seal::import_queue( Box::new(client.clone()), &task_manager.spawn_essential_handle(), config.prometheus_registry(), ); - #[cfg(not(feature = "manual-seal"))] - let import_queue = { - let slot_duration = sc_consensus_aura::slot_duration(&*client)?; - sc_consensus_aura::import_queue::( - sc_consensus_aura::ImportQueueParams { - block_import: frontier_block_import.clone(), - justification_import: Some(Box::new(grandpa_block_import)), - client: client.clone(), - 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)) - }, - spawner: &task_manager.spawn_essential_handle(), - registry: config.prometheus_registry(), - check_for_equivocation: Default::default(), - telemetry: telemetry.as_ref().map(|x| x.handle()), - compatibility_mode: Default::default(), - }, - )? - }; - Ok(sc_service::PartialComponents { client, backend, @@ -201,18 +278,13 @@ pub fn new_partial( keystore_container, select_chain, transaction_pool: transaction_pool.into(), - other: ( - frontier_block_import, - grandpa_link, - telemetry, - frontier_backend, - ), + other: (frontier_block_import, telemetry, frontier_backend), }) } -/// Builds a new service. +/// Builds a new local development service (parachain-oriented). pub fn start_node( - config: Configuration, + mut config: Configuration, evm_tracing_config: FrontierConfig, ) -> Result where @@ -226,18 +298,14 @@ where keystore_container, select_chain, transaction_pool, - other: (block_import, grandpa_link, mut telemetry, frontier_backend), + other: (block_import, mut telemetry, frontier_backend), } = new_partial(&config, &evm_tracing_config)?; - let protocol_name = sc_consensus_grandpa::protocol_standard_name( - &client - .block_hash(0) - .ok() - .flatten() - .expect("Genesis block exists; qed"), - &config.chain_spec, - ); - let mut net_config = sc_network::config::FullNetworkConfiguration::<_, _, N>::new( + // Dev node: no peers + config.network.default_peers_set.in_peers = 0; + config.network.default_peers_set.out_peers = 0; + + let net_config = sc_network::config::FullNetworkConfiguration::<_, _, N>::new( &config.network, config.prometheus_registry().cloned(), ); @@ -245,16 +313,6 @@ where let metrics = N::register_notification_metrics( config.prometheus_config.as_ref().map(|cfg| &cfg.registry), ); - let peer_store_handle = net_config.peer_store_handle(); - - let (grandpa_protocol_config, grandpa_notification_service) = - sc_consensus_grandpa::grandpa_peers_set_config::<_, N>( - protocol_name.clone(), - metrics.clone(), - Arc::clone(&peer_store_handle), - ); - net_config.add_notification_protocol(grandpa_protocol_config); - let (network, system_rpc_tx, tx_handler_controller, sync_service) = sc_service::build_network(sc_service::BuildNetworkParams { config: &config, @@ -394,14 +452,7 @@ where ), ); - #[cfg(not(feature = "manual-seal"))] - let force_authoring = config.force_authoring; - #[cfg(not(feature = "manual-seal"))] - let backoff_authoring_blocks: Option<()> = None; - let role = config.role.clone(); - let name = config.network.node_name.clone(); - let enable_grandpa = !config.disable_grandpa; let prometheus_registry = config.prometheus_registry().cloned(); let is_authority = config.role.is_authority(); @@ -414,8 +465,12 @@ where )); // Channel for the rpc handler to communicate with the authorship task. - #[cfg(feature = "manual-seal")] let (command_sink, commands_stream) = futures::channel::mpsc::channel(1024); + let local_para_id = ParaId::from( + crate::parachain::chain_spec::Extensions::try_get(&*config.chain_spec) + .map(|e| e.para_id) + .unwrap_or(2000), + ); let rpc_extensions_builder = { let client = client.clone(); @@ -442,14 +497,14 @@ where block_data_cache: block_data_cache.clone(), storage_override: storage_override.clone(), enable_evm_rpc: true, // enable EVM RPC for dev node by default - #[cfg(feature = "manual-seal")] command_sink: Some(command_sink.clone()), }; - crate::rpc::create_full( + crate::rpc::create_full_local_dev( deps, subscription, pubsub_notification_sinks.clone(), + local_para_id, crate::rpc::EvmTracingConfig { tracing_requesters: tracing_requesters.clone(), trace_filter_max_count: evm_tracing_config.ethapi_trace_max_count, @@ -486,9 +541,16 @@ where let slot_duration = sc_consensus_aura::slot_duration(&*client)?; - #[cfg(feature = "manual-seal")] - let aura = sc_consensus_manual_seal::run_manual_seal( - sc_consensus_manual_seal::ManualSealParams { + let para_id = local_para_id; + let initial_relay_slot = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("Current time is always after UNIX_EPOCH; qed") + .sub(Duration::from_secs(2 * 60 * 60)) + .as_millis() as u64 + / RELAY_CHAIN_SLOT_DURATION_MILLIS; + + let aura = + sc_consensus_manual_seal::run_manual_seal(sc_consensus_manual_seal::ManualSealParams { block_import, env: proposer_factory, client: client.clone(), @@ -500,104 +562,54 @@ where client.clone(), ), )), - 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.clone(), + create_inherent_data_providers: move |parent_hash, ()| { + let client = client.clone(); + async move { + let current_para_head = client + .header(parent_hash) + .expect("Header lookup should succeed") + .expect("Header passed in as parent should be present in backend."); + + let should_send_go_ahead = client + .runtime_api() + .collect_collation_info(parent_hash, ¤t_para_head) + .map(|info| info.new_validation_code.is_some()) + .unwrap_or_default(); + + let current_para_block = UniqueSaturatedInto::::unique_saturated_into( + *current_para_head.number(), + ) + 1; + + let relay_blocks_per_para_block = + (slot_duration.as_millis() / RELAY_CHAIN_SLOT_DURATION_MILLIS).max(1) + as u32; + let current_para_block_u64 = u64::from(current_para_block); + let relay_blocks_per_para_block_u64 = + u64::from(relay_blocks_per_para_block); + let target_relay_slot = initial_relay_slot.saturating_add( + current_para_block_u64.saturating_mul(relay_blocks_per_para_block_u64), ); - Ok((slot, timestamp)) - }, - }, - ); - #[cfg(not(feature = "manual-seal"))] - let aura = sc_consensus_aura::start_aura::( - sc_consensus_aura::StartAuraParams { - slot_duration, - client, - select_chain, - block_import, - proposer_factory, - 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, + let current_para_block_head = Some(current_para_head.encode().into()); + + let (timestamp_provider, mocked_parachain) = build_local_mock_inherent_data( + para_id, + current_para_block, + current_para_block_head, + relay_blocks_per_para_block, + target_relay_slot, + should_send_go_ahead.then_some(UpgradeGoAhead::GoAhead), ); - Ok((slot, timestamp)) + Ok((timestamp_provider, mocked_parachain)) + } }, - force_authoring, - backoff_authoring_blocks, - keystore: keystore_container.keystore(), - sync_oracle: sync_service.clone(), - justification_sync_link: sync_service.clone(), - block_proposal_slot_portion: sc_consensus_aura::SlotProportion::new(2f32 / 3f32), - max_block_proposal_slot_portion: None, - telemetry: telemetry.as_ref().map(|x| x.handle()), - compatibility_mode: Default::default(), - }, - )?; + }); - // the AURA authoring task is considered essential, i.e. if it - // fails we take down the service with it. task_manager .spawn_essential_handle() .spawn_blocking("aura", Some("block-authoring"), aura); } - // if the node isn't actively participating in consensus then it doesn't - // need a keystore, regardless of which protocol we use below. - let keystore = if role.is_authority() { - Some(keystore_container.keystore()) - } else { - None - }; - - let grandpa_config = sc_consensus_grandpa::Config { - // FIXME #1578 make this available through chainspec - gossip_duration: Duration::from_millis(333), - justification_generation_period: GRANDPA_JUSTIFICATION_PERIOD, - name: Some(name), - observer_enabled: false, - keystore, - local_role: role, - telemetry: telemetry.as_ref().map(|x| x.handle()), - protocol_name, - }; - - if enable_grandpa { - // start the full GRANDPA voter - // NOTE: non-authorities could run the GRANDPA observer protocol, but at - // this point the full voter should provide better guarantees of block - // and vote data availability than the observer. The observer has not - // been tested extensively yet and having most nodes in a network run it - // could lead to finality stalls. - let grandpa_config = sc_consensus_grandpa::GrandpaParams { - config: grandpa_config, - link: grandpa_link, - network, - sync: Arc::new(sync_service), - notification_service: grandpa_notification_service, - voting_rule: sc_consensus_grandpa::VotingRulesBuilder::default().build(), - prometheus_registry, - shared_voter_state: SharedVoterState::empty(), - telemetry: telemetry.as_ref().map(|x| x.handle()), - offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(transaction_pool), - }; - - // the GRANDPA voter task is considered infallible, i.e. - // if it fails we take down the service with it. - task_manager.spawn_essential_handle().spawn_blocking( - "grandpa-voter", - None, - sc_consensus_grandpa::run_grandpa_voter(grandpa_config)?, - ); - } - Ok(task_manager) } diff --git a/bin/collator/src/parachain/service.rs b/bin/collator/src/parachain/service.rs index 4f0427ca39..aaa1c0c3d9 100644 --- a/bin/collator/src/parachain/service.rs +++ b/bin/collator/src/parachain/service.rs @@ -463,7 +463,6 @@ where block_data_cache: block_data_cache.clone(), storage_override: storage_override.clone(), enable_evm_rpc: additional_config.enable_evm_rpc, - #[cfg(feature = "manual-seal")] command_sink: None, }; diff --git a/bin/collator/src/rpc.rs b/bin/collator/src/rpc.rs index 6c2443ae4a..50115b7460 100644 --- a/bin/collator/src/rpc.rs +++ b/bin/collator/src/rpc.rs @@ -28,9 +28,11 @@ use jsonrpsee::RpcModule; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; use std::path::Path; +use cumulus_primitives_core::ParaId; use sc_client_api::{ AuxStore, Backend, BlockchainEvents, StateBackend, StorageProvider, UsageProvider, }; +use sc_consensus_manual_seal::rpc::ManualSealApiServer; use sc_network::service::traits::NetworkService; use sc_network_sync::SyncingService; use sc_rpc::dev::DevApiServer; @@ -42,6 +44,7 @@ use sp_blockchain::{ Backend as BlockchainBackend, Error as BlockChainError, HeaderBackend, HeaderMetadata, }; use sp_consensus_aura::{sr25519::AuthorityId as AuraId, AuraApi}; +use sp_inherents::CreateInherentDataProviders; use sp_runtime::traits::{BlakeTwo256, Block as BlockT}; use std::sync::Arc; use substrate_frame_rpc_system::{System, SystemApiServer}; @@ -178,7 +181,6 @@ pub struct FullDeps { /// Enable EVM RPC servers pub enable_evm_rpc: bool, /// Command sink for manual sealing - #[cfg(feature = "manual-seal")] pub command_sink: Option>>, } @@ -247,6 +249,121 @@ where Ok(io) } +/// Instantiate all RPC extensions and Tracing RPC for local dev mode. +/// +/// This uses local pending inherent providers to align ETH pending/runtime calls +/// with local mocked parachain inherent behavior. +pub fn create_full_local_dev( + deps: FullDeps, + subscription_task_executor: SubscriptionTaskExecutor, + pubsub_notification_sinks: Arc< + fc_mapping_sync::EthereumBlockNotificationSinks< + fc_mapping_sync::EthereumBlockNotification, + >, + >, + local_para_id: ParaId, + tracing_config: EvmTracingConfig, +) -> Result, Box> +where + C: ProvideRuntimeApi + + HeaderBackend + + UsageProvider + + CallApiAt + + AuxStore + + StorageProvider + + HeaderMetadata + + BlockchainEvents + + Send + + Sync + + 'static, + C: sc_client_api::BlockBackend, + C::Api: substrate_frame_rpc_system::AccountNonceApi + + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi + + fp_rpc::ConvertTransactionRuntimeApi + + fp_rpc::EthereumRuntimeRPCApi + + BlockBuilder + + AuraApi + + moonbeam_rpc_primitives_debug::DebugRuntimeApi + + moonbeam_rpc_primitives_txpool::TxPoolRuntimeApi, + P: TransactionPool> + Sync + Send + 'static, + BE: Backend + 'static, + BE::State: StateBackend, + BE::Blockchain: BlockchainBackend, +{ + let client = Arc::clone(&deps.client); + let graph = Arc::clone(&deps.graph); + + let mut io = create_full_rpc_local_dev( + deps, + subscription_task_executor, + pubsub_notification_sinks, + local_para_id, + )?; + + if tracing_config.enable_txpool { + io.merge(TxPool::new(Arc::clone(&client), graph).into_rpc())?; + } + + if let Some(trace_filter_requester) = tracing_config.tracing_requesters.trace { + io.merge( + Trace::new( + client, + trace_filter_requester, + tracing_config.trace_filter_max_count, + ) + .into_rpc(), + )?; + } + + if let Some(debug_requester) = tracing_config.tracing_requesters.debug { + io.merge(Debug::new(debug_requester).into_rpc())?; + } + + Ok(io) +} + +fn create_full_rpc_local_dev( + deps: FullDeps, + subscription_task_executor: SubscriptionTaskExecutor, + pubsub_notification_sinks: Arc< + fc_mapping_sync::EthereumBlockNotificationSinks< + fc_mapping_sync::EthereumBlockNotification, + >, + >, + local_para_id: ParaId, +) -> Result, Box> +where + C: ProvideRuntimeApi + + UsageProvider + + HeaderBackend + + CallApiAt + + AuxStore + + StorageProvider + + HeaderMetadata + + BlockchainEvents + + Send + + Sync + + 'static, + C: sc_client_api::BlockBackend, + C::Api: substrate_frame_rpc_system::AccountNonceApi + + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi + + fp_rpc::ConvertTransactionRuntimeApi + + fp_rpc::EthereumRuntimeRPCApi + + BlockBuilder + + AuraApi, + P: TransactionPool> + Sync + Send + 'static, + BE: Backend + 'static, + BE::State: StateBackend, + BE::Blockchain: BlockchainBackend, +{ + create_full_rpc_with_pending_provider( + deps, + subscription_task_executor, + pubsub_notification_sinks, + |client| crate::local::LocalPendingInherentDataProvider::new(client, local_para_id), + ) +} + fn create_full_rpc( deps: FullDeps, subscription_task_executor: SubscriptionTaskExecutor, @@ -279,6 +396,50 @@ where BE: Backend + 'static, BE::State: StateBackend, BE::Blockchain: BlockchainBackend, +{ + create_full_rpc_with_pending_provider( + deps, + subscription_task_executor, + pubsub_notification_sinks, + crate::parachain::PendingCrateInherentDataProvider::new, + ) +} + +fn create_full_rpc_with_pending_provider( + deps: FullDeps, + subscription_task_executor: SubscriptionTaskExecutor, + pubsub_notification_sinks: Arc< + fc_mapping_sync::EthereumBlockNotificationSinks< + fc_mapping_sync::EthereumBlockNotification, + >, + >, + make_pending_inherent_data_provider: F, +) -> Result, Box> +where + C: ProvideRuntimeApi + + UsageProvider + + HeaderBackend + + CallApiAt + + AuxStore + + StorageProvider + + HeaderMetadata + + BlockchainEvents + + Send + + Sync + + 'static, + C: sc_client_api::BlockBackend, + C::Api: substrate_frame_rpc_system::AccountNonceApi + + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi + + fp_rpc::ConvertTransactionRuntimeApi + + fp_rpc::EthereumRuntimeRPCApi + + BlockBuilder + + AuraApi, + P: TransactionPool> + Sync + Send + 'static, + BE: Backend + 'static, + BE::State: StateBackend, + BE::Blockchain: BlockchainBackend, + CIDP: CreateInherentDataProviders + Send + Sync + 'static, + F: FnOnce(Arc) -> CIDP, { let mut io = RpcModule::new(()); let FullDeps { @@ -295,7 +456,6 @@ where storage_override, block_data_cache, enable_evm_rpc, - #[cfg(feature = "manual-seal")] command_sink, } = deps; @@ -303,9 +463,7 @@ where io.merge(TransactionPayment::new(client.clone()).into_rpc())?; io.merge(sc_rpc::dev::Dev::new(client.clone()).into_rpc())?; - #[cfg(feature = "manual-seal")] if let Some(command_sink) = command_sink { - use sc_consensus_manual_seal::rpc::ManualSealApiServer; io.merge(sc_consensus_manual_seal::rpc::ManualSeal::new(command_sink).into_rpc())?; } @@ -332,7 +490,7 @@ where // Allow 10x max allowed weight for non-transactional calls 10, None, - crate::parachain::PendingCrateInherentDataProvider::new(client.clone()), + make_pending_inherent_data_provider(client.clone()), Some(Box::new( crate::parachain::AuraConsensusDataProviderFallback::new(client.clone()), )), diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index e67d8059b2..f4caab74cd 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -20,7 +20,7 @@ //! Core Astar types. //! -//! These core Astar types are used by the Shiden, Shibuya, Astar and Local runtime. +//! These core Astar types are used by the Shiden, Shibuya and Astar runtimes. pub mod xcm; /// Checked Ethereum transaction primitives. diff --git a/runtime/local/Cargo.toml b/runtime/local/Cargo.toml deleted file mode 100644 index 4e612bc22d..0000000000 --- a/runtime/local/Cargo.toml +++ /dev/null @@ -1,289 +0,0 @@ -[package] -name = "local-runtime" -version = "5.48.1" -build = "build.rs" -authors.workspace = true -edition.workspace = true -homepage.workspace = true -repository.workspace = true - -[lints] -workspace = true - -[dependencies] -ethereum = { workspace = true } -log = { workspace = true, optional = true } -num_enum = { workspace = true } -parity-scale-codec = { workspace = true } -scale-info = { workspace = true } -serde_json = { workspace = true } -smallvec = { workspace = true } - -fp-evm = { workspace = true } -fp-rpc = { workspace = true } -fp-self-contained = { workspace = true } -frame-executive = { workspace = true } -frame-metadata-hash-extension = { workspace = true } -frame-support = { workspace = true } -frame-system = { workspace = true } -pallet-assets = { workspace = true } -pallet-aura = { workspace = true } -pallet-balances = { workspace = true } -pallet-collective = { workspace = true } -pallet-contracts = { workspace = true } -pallet-democracy = { workspace = true } -pallet-ethereum = { workspace = true } -pallet-ethereum-checked = { workspace = true } -pallet-evm = { workspace = true } -pallet-evm-precompile-blake2 = { workspace = true } -pallet-evm-precompile-bn128 = { workspace = true } -pallet-evm-precompile-dispatch = { workspace = true } -pallet-evm-precompile-ed25519 = { workspace = true } -pallet-evm-precompile-modexp = { workspace = true } -pallet-evm-precompile-sha3fips = { workspace = true } -pallet-evm-precompile-simple = { workspace = true } -pallet-grandpa = { workspace = true } -pallet-insecure-randomness-collective-flip = { workspace = true } -pallet-membership = { workspace = true } -pallet-preimage = { workspace = true } -pallet-proxy = { workspace = true } -pallet-safe-mode = { workspace = true } -pallet-scheduler = { workspace = true } -pallet-sudo = { workspace = true } -pallet-timestamp = { workspace = true } -pallet-transaction-payment = { workspace = true } -pallet-treasury = { workspace = true } -pallet-tx-pause = { workspace = true } -pallet-utility = { workspace = true } -pallet-vesting = { workspace = true } -sp-api = { workspace = true } -sp-arithmetic = { workspace = true } -sp-block-builder = { workspace = true } -sp-consensus-aura = { workspace = true } -sp-core = { workspace = true } -sp-genesis-builder = { workspace = true } -sp-inherents = { workspace = true } -sp-io = { workspace = true } -sp-offchain = { workspace = true } -sp-runtime = { workspace = true } -sp-session = { workspace = true } -sp-std = { workspace = true } -sp-transaction-pool = { workspace = true } -sp-version = { workspace = true } - -# Used for the node template's RPCs -frame-system-rpc-runtime-api = { workspace = true } -pallet-transaction-payment-rpc-runtime-api = { workspace = true } - -# Astar pallets -astar-primitives = { workspace = true } -pallet-chain-extension-unified-accounts = { workspace = true } -pallet-collective-proxy = { workspace = true } -pallet-dapp-staking = { workspace = true } -pallet-dynamic-evm-base-fee = { workspace = true } -pallet-evm-precompile-assets-erc20 = { workspace = true } -pallet-evm-precompile-dapp-staking = { workspace = true } -pallet-evm-precompile-dispatch-lockdrop = { workspace = true } -pallet-evm-precompile-sr25519 = { workspace = true } -pallet-evm-precompile-substrate-ecdsa = { workspace = true } -pallet-evm-precompile-unified-accounts = { workspace = true } -pallet-inflation = { workspace = true } -pallet-static-price-provider = { workspace = true } -pallet-unified-accounts = { workspace = true } - -dapp-staking-runtime-api = { workspace = true } - -precompile-utils = { workspace = true } - -# Moonbeam tracing -moonbeam-evm-tracer = { workspace = true, optional = true } -moonbeam-rpc-primitives-debug = { workspace = true, optional = true } -moonbeam-rpc-primitives-txpool = { workspace = true, optional = true } - -# chain-extensions -pallet-chain-extension-assets = { workspace = true } - -# benchmarking -array-bytes = { workspace = true } -frame-benchmarking = { workspace = true, optional = true } -frame-system-benchmarking = { workspace = true, optional = true } - -# try-runtime -frame-try-runtime = { workspace = true, optional = true } - -[build-dependencies] -substrate-wasm-builder = { workspace = true, optional = true } - -[features] -default = ["std"] -std = [ - "parity-scale-codec/std", - "serde_json/std", - "fp-rpc/std", - "fp-evm/std", - "fp-self-contained/std", - "frame-executive/std", - "frame-support/std", - "frame-system-rpc-runtime-api/std", - "pallet-collective-proxy/std", - "frame-system/std", - "pallet-assets/std", - "pallet-aura/std", - "pallet-membership/std", - "pallet-balances/std", - "pallet-contracts/std", - "pallet-chain-extension-unified-accounts/std", - "pallet-dapp-staking/std", - "dapp-staking-runtime-api/std", - "pallet-inflation/std", - "pallet-static-price-provider/std", - "pallet-dynamic-evm-base-fee/std", - "pallet-ethereum/std", - "pallet-evm/std", - "sp-genesis-builder/std", - "pallet-evm-precompile-blake2/std", - "pallet-evm-precompile-simple/std", - "pallet-evm-precompile-bn128/std", - "pallet-evm-precompile-dispatch/std", - "pallet-evm-precompile-ed25519/std", - "pallet-evm-precompile-modexp/std", - "pallet-evm-precompile-sha3fips/std", - "pallet-evm-precompile-dapp-staking/std", - "pallet-evm-precompile-sr25519/std", - "pallet-evm-precompile-substrate-ecdsa/std", - "pallet-evm-precompile-unified-accounts/std", - "pallet-evm-precompile-dispatch-lockdrop/std", - "pallet-grandpa/std", - "pallet-insecure-randomness-collective-flip/std", - "pallet-preimage/std", - "pallet-collective/std", - "pallet-democracy/std", - "pallet-sudo/std", - "pallet-timestamp/std", - "pallet-transaction-payment-rpc-runtime-api/std", - "pallet-transaction-payment/std", - "pallet-treasury/std", - "pallet-utility/std", - "pallet-vesting/std", - "pallet-proxy/std", - "pallet-safe-mode/std", - "pallet-tx-pause/std", - "sp-api/std", - "sp-block-builder/std", - "sp-consensus-aura/std", - "sp-core/std", - "sp-inherents/std", - "sp-offchain/std", - "sp-runtime/std", - "sp-session/std", - "sp-arithmetic/std", - "sp-std/std", - "sp-transaction-pool/std", - "sp-version/std", - "sp-io/std", - "frame-benchmarking/std", - "frame-try-runtime/std", - "frame-metadata-hash-extension/std", - "pallet-scheduler/std", - "pallet-unified-accounts/std", - "pallet-ethereum-checked/std", - "moonbeam-evm-tracer/std", - "moonbeam-rpc-primitives-debug/std", - "moonbeam-rpc-primitives-txpool/std", - "substrate-wasm-builder", - "pallet-chain-extension-assets/std", - "astar-primitives/std", - "frame-system-benchmarking?/std", - "log?/std", - "num_enum/std", - "pallet-evm-precompile-assets-erc20/std", - "precompile-utils/std", - "scale-info/std", - "ethereum/std", -] -runtime-benchmarks = [ - "frame-benchmarking", - "frame-support/runtime-benchmarks", - "frame-system-benchmarking/runtime-benchmarks", - "pallet-collective-proxy/runtime-benchmarks", - "frame-system/runtime-benchmarks", - "sp-runtime/runtime-benchmarks", - "pallet-balances/runtime-benchmarks", - "pallet-timestamp/runtime-benchmarks", - "pallet-transaction-payment/runtime-benchmarks", - "pallet-treasury/runtime-benchmarks", - "pallet-ethereum/runtime-benchmarks", - "pallet-preimage/runtime-benchmarks", - "pallet-democracy/runtime-benchmarks", - "pallet-collective/runtime-benchmarks", - "pallet-ethereum-checked/runtime-benchmarks", - "pallet-unified-accounts/runtime-benchmarks", - "astar-primitives/runtime-benchmarks", - "pallet-assets/runtime-benchmarks", - "pallet-dapp-staking/runtime-benchmarks", - "pallet-inflation/runtime-benchmarks", - "pallet-membership/runtime-benchmarks", - "pallet-dynamic-evm-base-fee/runtime-benchmarks", - "frame-benchmarking/runtime-benchmarks", - "pallet-chain-extension-assets/runtime-benchmarks", - "pallet-contracts/runtime-benchmarks", - "pallet-evm/runtime-benchmarks", - "pallet-evm-precompile-assets-erc20/runtime-benchmarks", - "pallet-evm-precompile-dapp-staking/runtime-benchmarks", - "pallet-grandpa/runtime-benchmarks", - "pallet-proxy/runtime-benchmarks", - "pallet-safe-mode/runtime-benchmarks", - "pallet-scheduler/runtime-benchmarks", - "pallet-static-price-provider/runtime-benchmarks", - "pallet-sudo/runtime-benchmarks", - "pallet-tx-pause/runtime-benchmarks", - "pallet-utility/runtime-benchmarks", - "pallet-vesting/runtime-benchmarks", -] -try-runtime = [ - "fp-self-contained/try-runtime", - "log", - "frame-try-runtime/try-runtime", - "frame-executive/try-runtime", - "frame-support/try-runtime", - "frame-system/try-runtime", - "pallet-aura/try-runtime", - "pallet-balances/try-runtime", - "pallet-contracts/try-runtime", - "pallet-collective-proxy/try-runtime", - "pallet-dapp-staking/try-runtime", - "pallet-treasury/try-runtime", - "pallet-inflation/try-runtime", - "pallet-membership/try-runtime", - "pallet-grandpa/try-runtime", - "pallet-insecure-randomness-collective-flip/try-runtime", - "pallet-sudo/try-runtime", - "pallet-timestamp/try-runtime", - "pallet-transaction-payment/try-runtime", - "pallet-tx-pause/try-runtime", - "pallet-utility/try-runtime", - "pallet-vesting/try-runtime", - "pallet-unified-accounts/try-runtime", - "pallet-ethereum/try-runtime", - "pallet-assets/try-runtime", - "pallet-safe-mode/try-runtime", - "pallet-scheduler/try-runtime", - "pallet-proxy/try-runtime", - "pallet-preimage/try-runtime", - "pallet-collective/try-runtime", - "pallet-democracy/try-runtime", - "pallet-dynamic-evm-base-fee/try-runtime", - "pallet-evm/try-runtime", - "pallet-ethereum-checked/try-runtime", - "pallet-static-price-provider/try-runtime", - "astar-primitives/try-runtime", - "pallet-chain-extension-assets/try-runtime", - "sp-runtime/try-runtime", -] - -# Enable metadata hash generation at compile time for the `CheckMetadataHash` extension. -metadata-hash = ["substrate-wasm-builder?/metadata-hash"] - -# A feature that should be enabled when the runtime should be built for on-chain -# deployment. This will disable stuff that shouldn't be part of the on-chain wasm -on-chain-release-build = ["metadata-hash"] diff --git a/runtime/local/build.rs b/runtime/local/build.rs deleted file mode 100644 index acb0392d54..0000000000 --- a/runtime/local/build.rs +++ /dev/null @@ -1,39 +0,0 @@ -// This file is part of Astar. - -// Copyright (C) Stake Technologies Pte.Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later - -// Astar is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Astar is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Astar. If not, see . - -#[cfg(all(feature = "std", not(feature = "metadata-hash")))] -fn main() { - substrate_wasm_builder::WasmBuilder::new() - .with_current_project() - .export_heap_base() - .import_memory() - .build(); -} - -#[cfg(all(feature = "std", feature = "metadata-hash"))] -fn main() { - substrate_wasm_builder::WasmBuilder::new() - .with_current_project() - .export_heap_base() - .import_memory() - .enable_metadata_hash("LOC", 18) - .build(); -} - -#[cfg(not(feature = "std"))] -fn main() {} diff --git a/runtime/local/src/chain_extensions.rs b/runtime/local/src/chain_extensions.rs deleted file mode 100644 index b08131be29..0000000000 --- a/runtime/local/src/chain_extensions.rs +++ /dev/null @@ -1,40 +0,0 @@ -// This file is part of Astar. - -// Copyright (C) Stake Technologies Pte.Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later - -// Astar is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Astar is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Astar. If not, see . - -use super::{Runtime, UnifiedAccounts}; - -/// Registered WASM contracts chain extensions. -pub use pallet_chain_extension_assets::AssetsExtension; -use pallet_contracts::chain_extension::RegisteredChainExtension; - -pub use pallet_chain_extension_unified_accounts::UnifiedAccountsExtension; - -// Following impls defines chain extension IDs. - -impl RegisteredChainExtension for AssetsExtension { - const ID: u16 = 02; -} - -impl RegisteredChainExtension for UnifiedAccountsExtension { - const ID: u16 = 03; -} - -pub type LocalChainExtensions = ( - AssetsExtension, - UnifiedAccountsExtension, -); diff --git a/runtime/local/src/genesis_config.rs b/runtime/local/src/genesis_config.rs deleted file mode 100644 index 2e3706c962..0000000000 --- a/runtime/local/src/genesis_config.rs +++ /dev/null @@ -1,188 +0,0 @@ -// This file is part of Astar. - -// Copyright (C) Stake Technologies Pte.Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later - -// Astar is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Astar is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Astar. If not, see . - -use crate::*; -use astar_primitives::{ - evm::EVM_REVERT_CODE, - genesis::{get_from_seed, GenesisAccount}, -}; -use sp_core::crypto::Ss58Codec; - -/// Provides the JSON representation of predefined genesis config for given `id`. -pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option> { - let genesis = match id.as_str() { - "development" => default_config(), - _ => return None, - }; - Some( - serde_json::to_string(&genesis) - .expect("serialization to json is expected to work. qed.") - .into_bytes(), - ) -} - -/// Get the default genesis config for the local runtime. -pub fn default_config() -> serde_json::Value { - let alice = GenesisAccount::::from_seed("Alice"); - let bob = GenesisAccount::::from_seed("Bob"); - let charlie = GenesisAccount::::from_seed("Charlie"); - let dave = GenesisAccount::::from_seed("Dave"); - let eve = GenesisAccount::::from_seed("Eve"); - - let accounts = vec![&alice, &bob, &charlie, &dave, &eve] - .iter() - .map(|x| x.account_id()) - .collect::>(); - - let balances = accounts - .iter() - .chain( - vec![ - TreasuryPalletId::get().into_account_truncating(), - CommunityTreasuryPalletId::get().into_account_truncating(), - // Private key: 0x01ab6e801c06e59ca97a14fc0a1978b27fa366fc87450e0b65459dd3515b7391 - // H160 public address: 0xaaafB3972B05630fCceE866eC69CdADd9baC2771 - AccountId::from_ss58check("5FQedkNQcF2fJPwkB6Z1ZcMgGti4vcJQNs6x85YPv3VhjBBT") - .expect("Invalid SS58 address"), - ] - .iter(), - ) - .map(|x| (x.clone(), 1_000_000_000 * AST)) - .collect::>(); - - let config = RuntimeGenesisConfig { - system: Default::default(), - sudo: SudoConfig { - key: Some(alice.account_id()), - }, - balances: BalancesConfig { - balances, - ..Default::default() - }, - vesting: VestingConfig { vesting: vec![] }, - aura: AuraConfig { - authorities: vec![get_from_seed::("Alice")], - }, - grandpa: GrandpaConfig { - authorities: vec![(get_from_seed::("Alice"), 1)], - ..Default::default() - }, - evm: EVMConfig { - // We need _some_ code inserted at the precompile address so that - // the evm will actually call the address. - accounts: Precompiles::used_addresses_h160() - .map(|addr| { - ( - addr, - fp_evm::GenesisAccount { - nonce: Default::default(), - balance: Default::default(), - storage: Default::default(), - code: EVM_REVERT_CODE.into(), - }, - ) - }) - .collect(), - ..Default::default() - }, - ethereum: Default::default(), - assets: Default::default(), - transaction_payment: Default::default(), - dapp_staking: DappStakingConfig { - reward_portion: vec![ - Permill::from_percent(40), - Permill::from_percent(30), - Permill::from_percent(20), - Permill::from_percent(10), - ], - slot_distribution: vec![ - Permill::from_percent(10), - Permill::from_percent(20), - Permill::from_percent(30), - Permill::from_percent(40), - ], - tier_thresholds: vec![ - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(35_700_000), // 3.57% - minimum_required_percentage: Perbill::from_parts(23_800_000), // 2.38% - maximum_possible_percentage: Perbill::from_percent(100), - }, - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(8_900_000), // 0.89% - minimum_required_percentage: Perbill::from_parts(6_000_000), // 0.6% - maximum_possible_percentage: Perbill::from_percent(100), - }, - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(23_800_000), // 2.38% - minimum_required_percentage: Perbill::from_parts(17_900_000), // 1.79% - maximum_possible_percentage: Perbill::from_percent(100), - }, - TierThreshold::FixedPercentage { - required_percentage: Perbill::from_parts(600_000), // 0.06% - }, - ], - slots_per_tier: vec![10, 20, 30, 40], - safeguard: Some(false), - ..Default::default() - }, - inflation: InflationConfig { - params: InflationParameters { - max_inflation_rate: Perquintill::from_percent(7), - treasury_part: Perquintill::from_percent(5), - collators_part: Perquintill::from_percent(3), - dapps_part: Perquintill::from_percent(20), - base_stakers_part: Perquintill::from_percent(25), - adjustable_stakers_part: Perquintill::from_percent(35), - bonus_part: Perquintill::from_percent(12), - ideal_staking_rate: Perquintill::from_percent(50), - decay_rate: Perquintill::one(), - }, - ..Default::default() - }, - council_membership: CouncilMembershipConfig { - members: accounts - .clone() - .try_into() - .expect("Should support at least 5 members."), - phantom: Default::default(), - }, - technical_committee_membership: TechnicalCommitteeMembershipConfig { - members: accounts[..3] - .to_vec() - .try_into() - .expect("Should support at least 3 members."), - phantom: Default::default(), - }, - community_council_membership: CommunityCouncilMembershipConfig { - members: accounts - .try_into() - .expect("Should support at least 5 members."), - phantom: Default::default(), - }, - council: Default::default(), - technical_committee: Default::default(), - community_council: Default::default(), - democracy: Default::default(), - treasury: Default::default(), - community_treasury: Default::default(), - safe_mode: Default::default(), - tx_pause: Default::default(), - }; - - serde_json::to_value(&config).expect("Could not build genesis config.") -} diff --git a/runtime/local/src/lib.rs b/runtime/local/src/lib.rs deleted file mode 100644 index ca65ee0ec5..0000000000 --- a/runtime/local/src/lib.rs +++ /dev/null @@ -1,2122 +0,0 @@ -// This file is part of Astar. - -// Copyright (C) Stake Technologies Pte.Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later - -// Astar is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Astar is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Astar. If not, see . - -#![cfg_attr(not(feature = "std"), no_std)] -// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. -#![recursion_limit = "256"] - -// Make the WASM binary available. -#[cfg(feature = "std")] -include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); - -extern crate alloc; -extern crate core; - -use alloc::{borrow::Cow, collections::btree_map::BTreeMap, vec, vec::Vec}; -use core::marker::PhantomData; - -use ethereum::AuthorizationList; -use frame_support::{ - construct_runtime, genesis_builder_helper, parameter_types, - traits::{ - fungible::{Balanced, Credit, HoldConsideration}, - AsEnsureOriginWithArg, ConstU128, ConstU32, ConstU64, ConstU8, Contains, - EqualPrivilegeOnly, FindAuthor, Get, InsideBoth, InstanceFilter, LinearStoragePrice, - Nothing, OnFinalize, WithdrawReasons, - }, - weights::{ - constants::{ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND}, - ConstantMultiplier, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients, - WeightToFeePolynomial, - }, - ConsensusEngineId, PalletId, -}; -use frame_system::{ - limits::{BlockLength, BlockWeights}, - EnsureRoot, EnsureSigned, EnsureWithSuccess, -}; -use pallet_ethereum::PostLogContent; -use pallet_evm::{FeeCalculator, GasWeightMapping, Runner}; -use pallet_evm_precompile_assets_erc20::AddressToAssetId; -use pallet_grandpa::{fg_primitives, AuthorityList as GrandpaAuthorityList}; -use pallet_transaction_payment::{FungibleAdapter, Multiplier, TargetedFeeAdjustment}; -use parity_scale_codec::{Compact, Decode, Encode, MaxEncodedLen}; -use sp_api::impl_runtime_apis; -use sp_core::{ - crypto::KeyTypeId, sr25519, ConstBool, DecodeWithMemTracking, OpaqueMetadata, H160, H256, U256, -}; -use sp_runtime::{ - generic, impl_opaque_keys, - traits::{ - AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, - DispatchInfoOf, Dispatchable, NumberFor, PostDispatchInfoOf, UniqueSaturatedInto, - }, - transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError}, - ApplyExtrinsicResult, FixedPointNumber, Perbill, Permill, Perquintill, RuntimeDebug, -}; - -use astar_primitives::{ - dapp_staking::{ - CycleConfiguration, DAppId, EraNumber, PeriodNumber, RankedTier, SmartContract, - }, - evm::{EvmRevertCodeHandler, HashedDefaultMappings}, - governance::{ - CommunityCouncilCollectiveInst, CommunityCouncilMembershipInst, CommunityTreasuryInst, - EnsureRootOrAllMainCouncil, EnsureRootOrAllTechnicalCommittee, - EnsureRootOrHalfTechnicalCommittee, EnsureRootOrTwoThirdsCommunityCouncil, - EnsureRootOrTwoThirdsMainCouncil, EnsureRootOrTwoThirdsTechnicalCommittee, - MainCouncilCollectiveInst, MainCouncilMembershipInst, MainTreasuryInst, - TechnicalCommitteeCollectiveInst, TechnicalCommitteeMembershipInst, - }, - Address, AssetId, Balance, BlockNumber, Hash, Header, Nonce, -}; - -pub use astar_primitives::{AccountId, Signature}; -pub use pallet_dapp_staking::TierThreshold; - -pub use crate::precompiles::WhitelistedCalls; -#[cfg(feature = "std")] -use sp_version::NativeVersion; -use sp_version::RuntimeVersion; - -pub use frame_system::Call as SystemCall; -pub use pallet_balances::Call as BalancesCall; -pub use pallet_grandpa::AuthorityId as GrandpaId; -pub use pallet_inflation::InflationParameters; -pub use pallet_timestamp::Call as TimestampCall; -pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; -#[cfg(any(feature = "std", test))] -pub use sp_runtime::BuildStorage; - -#[cfg(feature = "std")] -/// Wasm binary unwrapped. If built with `BUILD_DUMMY_WASM_BINARY`, the function panics. -pub fn wasm_binary_unwrap() -> &'static [u8] { - WASM_BINARY.expect( - "Development wasm binary is not available. This means the client is \ - built with `BUILD_DUMMY_WASM_BINARY` flag and it is only usable for \ - production chains. Please rebuild with the flag disabled.", - ) -} - -#[sp_version::runtime_version] -pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: Cow::Borrowed("local"), - impl_name: Cow::Borrowed("local"), - authoring_version: 1, - spec_version: 1, - impl_version: 1, - apis: RUNTIME_API_VERSIONS, - transaction_version: 1, - system_version: 1, -}; - -impl_opaque_keys! { - pub struct SessionKeys { - pub aura: Aura, - pub grandpa: Grandpa, - } -} - -mod precompiles; -pub use precompiles::{LocalPrecompiles, ASSET_PRECOMPILE_ADDRESS_PREFIX}; -pub type Precompiles = LocalPrecompiles; - -mod chain_extensions; -pub use chain_extensions::LocalChainExtensions; - -pub mod genesis_config; -mod weights; - -/// Constant values used within the runtime. -pub const MICROAST: Balance = 1_000_000_000_000; -pub const MILLIAST: Balance = 1_000 * MICROAST; -pub const AST: Balance = 1_000 * MILLIAST; - -pub const STORAGE_BYTE_FEE: Balance = 100 * MICROAST; - -/// Charge fee for stored bytes and items. -pub const fn deposit(items: u32, bytes: u32) -> Balance { - items as Balance * 1 * AST + (bytes as Balance) * STORAGE_BYTE_FEE -} - -/// This determines the average expected block time that we are targeting. -/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`. -/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked -/// up by `pallet_aura` to implement `fn slot_duration()`. -/// -/// Change this to adjust the block time. -pub const MILLISECS_PER_BLOCK: u64 = 2000; -pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK; - -// Time is measured by number of blocks. -pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber); -pub const HOURS: BlockNumber = MINUTES * 60; -pub const DAYS: BlockNumber = HOURS * 24; - -impl AddressToAssetId for Runtime { - fn address_to_asset_id(address: H160) -> Option { - let mut data = [0u8; 16]; - let address_bytes: [u8; 20] = address.into(); - if ASSET_PRECOMPILE_ADDRESS_PREFIX.eq(&address_bytes[0..4]) { - data.copy_from_slice(&address_bytes[4..20]); - Some(u128::from_be_bytes(data)) - } else { - None - } - } - - fn asset_id_to_address(asset_id: AssetId) -> H160 { - let mut data = [0u8; 20]; - data[0..4].copy_from_slice(ASSET_PRECOMPILE_ADDRESS_PREFIX); - data[4..20].copy_from_slice(&asset_id.to_be_bytes()); - H160::from(data) - } -} - -/// The version information used to identify this runtime when compiled natively. -#[cfg(feature = "std")] -pub fn native_version() -> NativeVersion { - NativeVersion { - runtime_version: VERSION, - can_author_with: Default::default(), - } -} - -/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used -/// by Operational extrinsics. -const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); - -parameter_types! { - pub const Version: RuntimeVersion = VERSION; - pub const BlockHashCount: BlockNumber = 2400; - /// We allow for 1 seconds of compute with a 2 second average block time. - pub RuntimeBlockWeights: BlockWeights = BlockWeights - ::with_sensible_defaults(Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND, u64::MAX), NORMAL_DISPATCH_RATIO); - pub RuntimeBlockLength: BlockLength = BlockLength - ::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); - pub const SS58Prefix: u8 = 5; -} - -// Configure FRAME pallets to include in runtime. -impl frame_system::Config for Runtime { - /// The basic call filter to use in dispatchable. - type BaseCallFilter = InsideBoth; - /// Block & extrinsics weights: base values and limits. - type BlockWeights = RuntimeBlockWeights; - /// The maximum length of a block (in bytes). - type BlockLength = RuntimeBlockLength; - /// The identifier used to distinguish between accounts. - type AccountId = AccountId; - /// The aggregated dispatch type that is available for extrinsics. - type RuntimeCall = RuntimeCall; - /// The lookup mechanism to get account ID from whatever is passed in dispatchers. - type Lookup = (AccountIdLookup, UnifiedAccounts); - /// The nonce type for storing how many extrinsics an account has signed. - type Nonce = Nonce; - /// The type for blocks. - type Block = Block; - /// The type for hashing blocks and tries. - type Hash = Hash; - /// The hashing algorithm used. - type Hashing = BlakeTwo256; - /// The ubiquitous event type. - type RuntimeEvent = RuntimeEvent; - /// The ubiquitous origin type. - type RuntimeOrigin = RuntimeOrigin; - /// The aggregated RuntimeTask type. - type RuntimeTask = RuntimeTask; - /// Maximum number of block number to block hash mappings to keep (oldest pruned first). - type BlockHashCount = BlockHashCount; - /// The weight of database operations that the runtime can invoke. - type DbWeight = RocksDbWeight; - /// Version of the runtime. - type Version = Version; - /// Converts a module to the index of the module in `construct_runtime!`. - /// - /// This type is being generated by `construct_runtime!`. - type PalletInfo = PalletInfo; - /// What to do if a new account is created. - type OnNewAccount = (); - /// What to do if an account is fully reaped from the system. - type OnKilledAccount = pallet_unified_accounts::KillAccountMapping; - /// The data to be stored in an account. - type AccountData = pallet_balances::AccountData; - /// Weight information for the extrinsics of this pallet. - type SystemWeightInfo = frame_system::weights::SubstrateWeight; - /// This is used as an identifier of the chain. 42 is the generic substrate prefix. - type SS58Prefix = SS58Prefix; - /// The set code logic, just the default since we're not a parachain. - type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; - type SingleBlockMigrations = (); - type MultiBlockMigrator = (); - type PreInherents = (); - type PostInherents = (); - type PostTransactions = (); - type ExtensionsWeightInfo = (); -} - -impl pallet_aura::Config for Runtime { - type AuthorityId = AuraId; - type DisabledValidators = (); - type MaxAuthorities = ConstU32<50>; - type SlotDuration = pallet_aura::MinimumPeriodTimesTwo; - type AllowMultipleBlocksPerSlot = ConstBool; -} - -impl pallet_grandpa::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - - type KeyOwnerProof = sp_core::Void; - type EquivocationReportSystem = (); - - type WeightInfo = (); - type MaxAuthorities = ConstU32<50>; - type MaxSetIdSessionEntries = ConstU64<0>; - type MaxNominators = ConstU32<0>; -} - -parameter_types! { - pub const MinimumPeriod: u64 = SLOT_DURATION / 2; -} - -impl pallet_timestamp::Config for Runtime { - /// A timestamp: milliseconds since the unix epoch. - type Moment = u64; - type OnTimestampSet = Aura; - type MinimumPeriod = MinimumPeriod; - type WeightInfo = pallet_timestamp::weights::SubstrateWeight; -} - -impl pallet_insecure_randomness_collective_flip::Config for Runtime {} - -parameter_types! { - pub const ExistentialDeposit: u128 = 500; - pub const MaxLocks: u32 = 50; -} - -impl pallet_balances::Config for Runtime { - type MaxLocks = MaxLocks; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - /// The type for recording an account's balance. - type Balance = Balance; - /// The ubiquitous event type. - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type WeightInfo = weights::pallet_balances::SubstrateWeight; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = RuntimeFreezeReason; - type MaxFreezes = ConstU32<1>; - type DoneSlashHandler = (); -} - -parameter_types! { - pub const AssetDeposit: Balance = 1 * AST; - pub const AssetsStringLimit: u32 = 50; - /// Key = 32 bytes, Value = 36 bytes (32+1+1+1+1) - // https://github.com/paritytech/substrate/blob/069917b/frame/assets/src/lib.rs#L257L271 - pub const MetadataDepositBase: Balance = deposit(1, 68); - pub const MetadataDepositPerByte: Balance = deposit(0, 1); - pub const AssetAccountDeposit: Balance = deposit(1, 18); -} - -impl pallet_assets::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type Balance = Balance; - type AssetId = AssetId; - type Currency = Balances; - type CreateOrigin = AsEnsureOriginWithArg>; - type ForceOrigin = EnsureRoot; - type AssetDeposit = AssetDeposit; - type MetadataDepositBase = MetadataDepositBase; - type MetadataDepositPerByte = MetadataDepositPerByte; - type AssetAccountDeposit = AssetAccountDeposit; - type ApprovalDeposit = ExistentialDeposit; - type StringLimit = AssetsStringLimit; - type Freezer = (); - type Extra = (); - type Holder = (); - type WeightInfo = weights::pallet_assets::SubstrateWeight; - type RemoveItemsLimit = ConstU32<1000>; - type AssetIdParameter = Compact; - type CallbackHandle = EvmRevertCodeHandler; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = astar_primitives::benchmarks::AssetsBenchmarkHelper; -} - -// These values are based on the Astar 2.0 Tokenomics Modeling report. -parameter_types! { - pub const TransactionLengthFeeFactor: Balance = 23_500_000_000_000; // 0.000_023_500_000_000_000 AST per byte - pub const WeightFeeFactor: Balance = 30_855_000_000_000_000; // Around 0.03 AST per unit of ref time. - pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25); - pub const OperationalFeeMultiplier: u8 = 5; - pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(000_015, 1_000_000); // 0.000_015 - pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 10); // 0.1 - pub MaximumMultiplier: Multiplier = Multiplier::saturating_from_integer(10); // 10 -} - -/// Handles converting a weight scalar to a fee value, based on the scale and granularity of the -/// node's balance type. -/// -/// This should typically create a mapping between the following ranges: -/// - [0, MAXIMUM_BLOCK_WEIGHT] -/// - [Balance::min, Balance::max] -/// -/// Yet, it can be used for any other sort of change to weight-fee. Some examples being: -/// - Setting it to `0` will essentially disable the weight fee. -/// - Setting it to `1` will cause the literal `#[weight = x]` values to be charged. -pub struct WeightToFee; -impl WeightToFeePolynomial for WeightToFee { - type Balance = Balance; - fn polynomial() -> WeightToFeeCoefficients { - let p = WeightFeeFactor::get(); - let q = Balance::from(ExtrinsicBaseWeight::get().ref_time()); - smallvec::smallvec![WeightToFeeCoefficient { - degree: 1, - negative: false, - coeff_frac: Perbill::from_rational(p % q, q), - coeff_integer: p / q, - }] - } -} - -impl pallet_transaction_payment::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type OnChargeTransaction = FungibleAdapter; - type WeightToFee = WeightToFee; - type OperationalFeeMultiplier = OperationalFeeMultiplier; - type FeeMultiplierUpdate = TargetedFeeAdjustment< - Self, - TargetBlockFullness, - AdjustmentVariable, - MinimumMultiplier, - MaximumMultiplier, - >; - type LengthToFee = ConstantMultiplier; - type WeightInfo = (); -} - -parameter_types! { - pub DefaultBaseFeePerGas: U256 = U256::from(1_470_000_000_000_u128); - pub MinBaseFeePerGas: U256 = U256::from(800_000_000_000_u128); - pub MaxBaseFeePerGas: U256 = U256::from(80_000_000_000_000_u128); - pub StepLimitRatio: Perquintill = Perquintill::from_rational(5_u128, 100_000); -} - -/// Simple wrapper for fetching current native transaction fee weight fee multiplier. -pub struct AdjustmentFactorGetter; -impl Get for AdjustmentFactorGetter { - fn get() -> Multiplier { - pallet_transaction_payment::NextFeeMultiplier::::get() - } -} - -impl pallet_dynamic_evm_base_fee::Config for Runtime { - type DefaultBaseFeePerGas = DefaultBaseFeePerGas; - type MinBaseFeePerGas = MinBaseFeePerGas; - type MaxBaseFeePerGas = MaxBaseFeePerGas; - type AdjustmentFactor = AdjustmentFactorGetter; - type WeightFactor = WeightFeeFactor; - type StepLimitRatio = StepLimitRatio; - type WeightInfo = pallet_dynamic_evm_base_fee::weights::SubstrateWeight; -} - -parameter_types! { - pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); - pub const DappsStakingPalletId: PalletId = PalletId(*b"py/dpsst"); -} - -impl pallet_static_price_provider::Config for Runtime {} - -#[cfg(feature = "runtime-benchmarks")] -pub struct BenchmarkHelper(PhantomData<(SC, ACC)>); -#[cfg(feature = "runtime-benchmarks")] -impl pallet_dapp_staking::BenchmarkHelper, AccountId> - for BenchmarkHelper, AccountId> -{ - fn get_smart_contract(id: u32) -> SmartContract { - SmartContract::Wasm(AccountId::from([id as u8; 32])) - } - - fn set_balance(account: &AccountId, amount: Balance) { - use frame_support::traits::fungible::Unbalanced as FunUnbalanced; - Balances::write_balance(account, amount) - .expect("Must succeed in test/benchmark environment."); - } -} - -impl pallet_dapp_staking::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type RuntimeFreezeReason = RuntimeFreezeReason; - type Currency = Balances; - type SmartContract = SmartContract; - type ContractRegisterOrigin = EnsureRootOrTwoThirdsCommunityCouncil; - type ContractUnregisterOrigin = EnsureRoot; - type ManagerOrigin = EnsureRootOrTwoThirdsTechnicalCommittee; - type StakingRewardHandler = Inflation; - type CycleConfiguration = InflationCycleConfig; - type Observers = Inflation; - type AccountCheck = (); - type EraRewardSpanLength = ConstU32<8>; - type RewardRetentionInPeriods = ConstU32<2>; - type MaxNumberOfContracts = ConstU32<100>; - type MaxNumberOfContractsLegacy = ConstU32<100>; - type MaxUnlockingChunks = ConstU32<5>; - type MinimumLockedAmount = ConstU128; - type UnlockingPeriod = ConstU32<2>; - type MaxNumberOfStakedContracts = ConstU32<3>; - type MinimumStakeAmount = ConstU128; - type NumberOfTiers = ConstU32<4>; - type RankingEnabled = ConstBool; - type MaxBonusSafeMovesPerPeriod = ConstU8<0>; - type WeightInfo = pallet_dapp_staking::weights::SubstrateWeight; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = BenchmarkHelper, AccountId>; -} - -pub struct InflationPayoutPerBlock; -impl pallet_inflation::PayoutPerBlock> for InflationPayoutPerBlock { - fn treasury(reward: Credit) { - let _ = Balances::resolve(&TreasuryPalletId::get().into_account_truncating(), reward); - } - - fn collators(_reward: Credit) { - // no collators for local dev node - } -} - -pub struct InflationCycleConfig; -impl CycleConfiguration for InflationCycleConfig { - fn periods_per_cycle() -> PeriodNumber { - 4 - } - - fn eras_per_voting_subperiod() -> EraNumber { - 2 - } - - fn eras_per_build_and_earn_subperiod() -> EraNumber { - 22 - } - - fn blocks_per_era() -> BlockNumber { - 30 - } -} - -impl pallet_inflation::Config for Runtime { - type Currency = Balances; - type PayoutPerBlock = InflationPayoutPerBlock; - type CycleConfiguration = InflationCycleConfig; - type WeightInfo = pallet_inflation::weights::SubstrateWeight; -} - -impl pallet_utility::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type RuntimeCall = RuntimeCall; - type PalletsOrigin = OriginCaller; - type WeightInfo = pallet_utility::weights::SubstrateWeight; -} - -parameter_types! { - // 2 storage items with value size 20 and 32 - pub const AccountMappingStorageFee: u128 = deposit(2, 32 + 20); -} - -impl pallet_unified_accounts::Config for Runtime { - type Currency = Balances; - type DefaultMappings = HashedDefaultMappings; - type ChainId = ChainId; - type AccountMappingStorageFee = AccountMappingStorageFee; - type WeightInfo = pallet_unified_accounts::weights::SubstrateWeight; -} - -parameter_types! { - pub ReservedXcmpWeight: Weight = Weight::zero(); -} - -impl pallet_ethereum_checked::Config for Runtime { - type ReservedXcmpWeight = ReservedXcmpWeight; - type InvalidEvmTransactionError = pallet_ethereum::InvalidTransactionWrapper; - type ValidatedTransaction = pallet_ethereum::ValidatedTransaction; - type AddressMapper = UnifiedAccounts; - type XcmTransactOrigin = pallet_ethereum_checked::EnsureXcmEthereumTx; - type WeightInfo = pallet_ethereum_checked::weights::SubstrateWeight; -} - -/// Current approximation of the gas/s consumption considering -/// EVM execution over compiled WASM (on 4.4Ghz CPU). -/// Given the 500ms Weight, from which 75% only are used for transactions, -/// the total EVM execution gas limit is: GAS_PER_SECOND * 0.500 * 0.75 ~= 15_000_000. -pub const GAS_PER_SECOND: u64 = 40_000_000; - -/// Approximate ratio of the amount of Weight per Gas. -/// u64 works for approximations because Weight is a very small unit compared to gas. -pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND.saturating_div(GAS_PER_SECOND); - -pub struct FindAuthorTruncated(PhantomData); -impl> FindAuthor for FindAuthorTruncated { - fn find_author<'a, I>(digests: I) -> Option - where - I: 'a + IntoIterator, - { - if let Some(author_index) = F::find_author(digests) { - let authority_id = - pallet_aura::Authorities::::get()[author_index as usize].clone(); - return Some(H160::from_slice(&authority_id.encode()[4..24])); - } - - None - } -} - -parameter_types! { - /// Ethereum-compatible chain_id: - /// * Dusty: 80 - /// * Shibuya: 81 - /// * Shiden: 336 - /// * Local: 4369 - pub ChainId: u64 = 0x1111; - /// EVM gas limit - pub BlockGasLimit: U256 = U256::from( - NORMAL_DISPATCH_RATIO * WEIGHT_REF_TIME_PER_SECOND / WEIGHT_PER_GAS - ); - pub PrecompilesValue: Precompiles = LocalPrecompiles::<_>::new(); - pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0); - /// The amount of gas per PoV size. Value is calculated as: - /// - /// max_gas_limit = max_tx_ref_time / WEIGHT_PER_GAS = max_pov_size * gas_limit_pov_size_ratio - /// gas_limit_pov_size_ratio = ceil((max_tx_ref_time / WEIGHT_PER_GAS) / max_pov_size) - /// - /// Local runtime has no strict bounds as parachain, but we keep the value set to 4 for consistency. - pub const GasLimitPovSizeRatio: u64 = 4; -} - -impl pallet_evm::Config for Runtime { - type FeeCalculator = DynamicEvmBaseFee; - type GasWeightMapping = pallet_evm::FixedGasWeightMapping; - type WeightPerGas = WeightPerGas; - type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping; - type CallOrigin = pallet_evm::EnsureAddressRoot; - type WithdrawOrigin = pallet_evm::EnsureAddressTruncated; - type AddressMapping = UnifiedAccounts; - type Currency = Balances; - type Runner = pallet_evm::runner::stack::Runner; - type PrecompilesType = Precompiles; - type PrecompilesValue = PrecompilesValue; - type ChainId = ChainId; - type OnChargeTransaction = pallet_evm::EVMFungibleAdapter; - type BlockGasLimit = BlockGasLimit; - type Timestamp = Timestamp; - type OnCreate = (); - type FindAuthor = FindAuthorTruncated; - type GasLimitPovSizeRatio = GasLimitPovSizeRatio; - type AccountProvider = pallet_evm::FrameSystemAccountProvider; - // gas based storage limit not enabled - type GasLimitStorageGrowthRatio = ConstU64<0>; - type CreateOriginFilter = (); - type CreateInnerOriginFilter = (); - type WeightInfo = pallet_evm::weights::SubstrateWeight; -} - -parameter_types! { - pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes; -} - -impl pallet_ethereum::Config for Runtime { - type StateRoot = - pallet_ethereum::IntermediateStateRoot<::Version>; - type PostLogContent = PostBlockAndTxnHashes; - // Maximum length (in bytes) of revert message to include in Executed event - type ExtraDataLength = ConstU32<30>; -} - -parameter_types! { - pub MaximumSchedulerWeight: Weight = NORMAL_DISPATCH_RATIO * RuntimeBlockWeights::get().max_block; -} - -impl pallet_scheduler::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type PalletsOrigin = OriginCaller; - type RuntimeCall = RuntimeCall; - type MaximumWeight = MaximumSchedulerWeight; - type ScheduleOrigin = EnsureRoot; - type MaxScheduledPerBlock = ConstU32<50>; - // TODO: re-bench pallet_scheduler weights or use default weights. - type WeightInfo = pallet_scheduler::weights::SubstrateWeight; - type OriginPrivilegeCmp = EqualPrivilegeOnly; - type Preimages = Preimage; - type BlockNumberProvider = System; -} - -parameter_types! { - pub const PreimageBaseDeposit: Balance = deposit(1, 0); - pub const PreimageByteDeposit: Balance = deposit(0, 1); - pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage); -} - -impl pallet_preimage::Config for Runtime { - type WeightInfo = pallet_preimage::weights::SubstrateWeight; - type RuntimeEvent = RuntimeEvent; - type Currency = Balances; - type ManagerOrigin = EnsureRoot; - type Consideration = HoldConsideration< - AccountId, - Balances, - PreimageHoldReason, - LinearStoragePrice, - >; -} - -parameter_types! { - pub const MinVestedTransfer: Balance = 1 * AST; - pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons = - WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE); -} - -impl pallet_vesting::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type Currency = Balances; - type BlockNumberToBalance = ConvertInto; - type MinVestedTransfer = MinVestedTransfer; - type WeightInfo = pallet_vesting::weights::SubstrateWeight; - type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; - type BlockNumberProvider = System; - // `VestingInfo` encode length is 36bytes. 28 schedules gets encoded as 1009 bytes, which is the - // highest number of schedules that encodes less than 2^10. - const MAX_VESTING_SCHEDULES: u32 = 28; -} - -parameter_types! { - pub const DepositPerItem: Balance = deposit(1, 0); - pub const DepositPerByte: Balance = deposit(0, 1); - // Fallback value if storage deposit limit not set by the user - pub const DefaultDepositLimit: Balance = deposit(16, 16 * 1024); - pub const MaxDelegateDependencies: u32 = 32; - pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(10); - pub Schedule: pallet_contracts::Schedule = Default::default(); -} - -impl pallet_contracts::Config for Runtime { - type Time = Timestamp; - type Randomness = RandomnessCollectiveFlip; - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - type RuntimeCall = RuntimeCall; - /// The safest default is to allow no calls at all. - /// - /// Runtimes should whitelist dispatchables that are allowed to be called from contracts - /// and make sure they are stable. Dispatchables exposed to contracts are not allowed to - /// change because that would break already deployed contracts. The `Call` structure itself - /// is not allowed to change the indices of existing pallets, too. - type CallFilter = Nothing; - type DepositPerItem = DepositPerItem; - type DepositPerByte = DepositPerByte; - type DefaultDepositLimit = DefaultDepositLimit; - type CallStack = [pallet_contracts::Frame; 5]; - type WeightPrice = pallet_transaction_payment::Pallet; - type WeightInfo = pallet_contracts::weights::SubstrateWeight; - type ChainExtension = LocalChainExtensions; - type Schedule = Schedule; - type AddressGenerator = pallet_contracts::DefaultAddressGenerator; - type MaxCodeLen = ConstU32<{ 123 * 1024 }>; - type MaxStorageKeyLen = ConstU32<128>; - type UnsafeUnstableInterface = ConstBool; - type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>; - type MaxDelegateDependencies = MaxDelegateDependencies; - type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; - type RuntimeHoldReason = RuntimeHoldReason; - type Debug = (); - type Environment = (); - type Migrations = (); - type Xcm = (); - type UploadOrigin = EnsureSigned<::AccountId>; - type InstantiateOrigin = EnsureSigned<::AccountId>; - type ApiVersion = (); - type MaxTransientStorageSize = ConstU32<{ 1 * 1024 * 1024 }>; -} - -impl pallet_sudo::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type RuntimeCall = RuntimeCall; - type WeightInfo = pallet_sudo::weights::SubstrateWeight; -} - -/// The type used to represent the kinds of proxying allowed. -#[derive( - Copy, - Clone, - Eq, - PartialEq, - Ord, - PartialOrd, - Encode, - Decode, - DecodeWithMemTracking, - RuntimeDebug, - MaxEncodedLen, - scale_info::TypeInfo, -)] -pub enum ProxyType { - /// Allows all runtime calls for proxy account - Any, - /// Allows only NonTransfer runtime calls for proxy account - /// To know exact calls check InstanceFilter implementation for ProxyTypes - NonTransfer, - /// All Runtime calls from Pallet Balances allowed for proxy account - Balances, - /// All Runtime calls from Pallet Assets allowed for proxy account - Assets, - /// Only reject_announcement call from pallet proxy allowed for proxy account - CancelProxy, - /// All runtime calls from pallet DappStaking allowed for proxy account - DappStaking, - /// Only claim_staker call from pallet DappStaking allowed for proxy account - StakerRewardClaim, - /// All governance related calls allowed for proxy account - Governance, -} - -impl Default for ProxyType { - fn default() -> Self { - Self::Any - } -} - -impl InstanceFilter for ProxyType { - fn filter(&self, c: &RuntimeCall) -> bool { - match self { - // Always allowed RuntimeCall::Utility no matter type. - // Only transactions allowed by Proxy.filter can be executed - _ if matches!(c, RuntimeCall::Utility(..)) => true, - // Allows all runtime calls for proxy account - ProxyType::Any => true, - // Allows only NonTransfer runtime calls for proxy account - ProxyType::NonTransfer => { - matches!( - c, - RuntimeCall::System(..) - | RuntimeCall::Proxy(..) - | RuntimeCall::Vesting( - pallet_vesting::Call::vest { .. } - | pallet_vesting::Call::vest_other { .. } - ) - | RuntimeCall::DappStaking(..) - ) - } - // All Runtime calls from Pallet Balances allowed for proxy account - ProxyType::Balances => { - matches!(c, RuntimeCall::Balances(..)) - } - // All Runtime calls from Pallet Assets allowed for proxy account - ProxyType::Assets => { - matches!(c, RuntimeCall::Assets(..)) - } - // Only reject_announcement call from pallet proxy allowed for proxy account - ProxyType::CancelProxy => { - matches!( - c, - RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. }) - ) - } - // All runtime calls from pallet DappStaking allowed for proxy account - ProxyType::DappStaking => { - matches!(c, RuntimeCall::DappStaking(..)) - } - ProxyType::StakerRewardClaim => { - matches!( - c, - RuntimeCall::DappStaking( - pallet_dapp_staking::Call::claim_staker_rewards { .. } - ) - ) - } - ProxyType::Governance => { - matches!( - c, - RuntimeCall::Democracy(..) - | RuntimeCall::Council(..) - | RuntimeCall::TechnicalCommittee(..) - | RuntimeCall::CommunityCouncil(..) - ) - } - } - } - - fn is_superset(&self, o: &Self) -> bool { - match (self, o) { - (x, y) if x == y => true, - (ProxyType::Any, _) => true, - (_, ProxyType::Any) => false, - (ProxyType::NonTransfer, _) => true, - (ProxyType::DappStaking, ProxyType::StakerRewardClaim) => true, - _ => false, - } - } -} - -impl pallet_proxy::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type RuntimeCall = RuntimeCall; - type Currency = Balances; - type ProxyType = ProxyType; - // One storage item; key size 32, value size 8; . - type ProxyDepositBase = ConstU128<{ AST * 10 }>; - // Additional storage item size of 33 bytes. - type ProxyDepositFactor = ConstU128<{ MILLIAST * 330 }>; - type MaxProxies = ConstU32<32>; - type WeightInfo = pallet_proxy::weights::SubstrateWeight; - type MaxPending = ConstU32<32>; - type CallHasher = BlakeTwo256; - // Key size 32 + 1 item - type AnnouncementDepositBase = ConstU128<{ AST * 10 }>; - // Acc Id + Hash + block number - type AnnouncementDepositFactor = ConstU128<{ MILLIAST * 660 }>; - type BlockNumberProvider = System; -} - -parameter_types! { - pub const CouncilMaxMembers: u32 = 5; - pub const TechnicalCommitteeMaxMembers: u32 = 3; - pub const CommunityCouncilMaxMembers: u32 = 10; -} - -impl pallet_membership::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type AddOrigin = EnsureRootOrTwoThirdsMainCouncil; - type RemoveOrigin = EnsureRootOrTwoThirdsMainCouncil; - type SwapOrigin = EnsureRootOrTwoThirdsMainCouncil; - type ResetOrigin = EnsureRootOrTwoThirdsMainCouncil; - type PrimeOrigin = EnsureRootOrTwoThirdsMainCouncil; - type MembershipInitialized = Council; - type MembershipChanged = Council; - type MaxMembers = CouncilMaxMembers; - type WeightInfo = pallet_membership::weights::SubstrateWeight; -} - -impl pallet_membership::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type AddOrigin = EnsureRootOrTwoThirdsMainCouncil; - type RemoveOrigin = EnsureRootOrTwoThirdsMainCouncil; - type SwapOrigin = EnsureRootOrTwoThirdsMainCouncil; - type ResetOrigin = EnsureRootOrTwoThirdsMainCouncil; - type PrimeOrigin = EnsureRootOrTwoThirdsMainCouncil; - type MembershipInitialized = TechnicalCommittee; - type MembershipChanged = TechnicalCommittee; - type MaxMembers = TechnicalCommitteeMaxMembers; - type WeightInfo = pallet_membership::weights::SubstrateWeight; -} - -impl pallet_membership::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type AddOrigin = EnsureRootOrTwoThirdsMainCouncil; - type RemoveOrigin = EnsureRootOrTwoThirdsMainCouncil; - type SwapOrigin = EnsureRootOrTwoThirdsMainCouncil; - type ResetOrigin = EnsureRootOrTwoThirdsMainCouncil; - type PrimeOrigin = EnsureRootOrTwoThirdsMainCouncil; - type MembershipInitialized = CommunityCouncil; - type MembershipChanged = CommunityCouncil; - type MaxMembers = CommunityCouncilMaxMembers; - type WeightInfo = pallet_membership::weights::SubstrateWeight; -} - -parameter_types! { - pub MaxProposalWeight: Weight = Perbill::from_percent(50) * RuntimeBlockWeights::get().max_block; -} - -impl pallet_collective::Config for Runtime { - type RuntimeOrigin = RuntimeOrigin; - type Proposal = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type MotionDuration = ConstU32<{ 5 * MINUTES }>; - type MaxProposals = ConstU32<16>; - type MaxMembers = CouncilMaxMembers; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type SetMembersOrigin = EnsureRoot; - type MaxProposalWeight = MaxProposalWeight; - type KillOrigin = EnsureRoot; - type DisapproveOrigin = EnsureRoot; - type Consideration = (); - type WeightInfo = pallet_collective::weights::SubstrateWeight; -} - -impl pallet_collective::Config for Runtime { - type RuntimeOrigin = RuntimeOrigin; - type Proposal = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type MotionDuration = ConstU32<{ 5 * MINUTES }>; - type MaxProposals = ConstU32<16>; - type MaxMembers = TechnicalCommitteeMaxMembers; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type SetMembersOrigin = EnsureRoot; - type MaxProposalWeight = MaxProposalWeight; - type KillOrigin = EnsureRoot; - type DisapproveOrigin = EnsureRoot; - type Consideration = (); - type WeightInfo = pallet_collective::weights::SubstrateWeight; -} - -impl pallet_collective::Config for Runtime { - type RuntimeOrigin = RuntimeOrigin; - type Proposal = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type MotionDuration = ConstU32<{ 5 * MINUTES }>; - type MaxProposals = ConstU32<16>; - type MaxMembers = CommunityCouncilMaxMembers; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type SetMembersOrigin = EnsureRoot; - type MaxProposalWeight = MaxProposalWeight; - type KillOrigin = EnsureRoot; - type DisapproveOrigin = EnsureRoot; - type Consideration = (); - type WeightInfo = pallet_collective::weights::SubstrateWeight; -} - -impl pallet_democracy::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type Currency = Balances; - type EnactmentPeriod = ConstU32<{ 5 * MINUTES }>; - type LaunchPeriod = ConstU32<{ 5 * MINUTES }>; - type VotingPeriod = ConstU32<{ 5 * MINUTES }>; - type VoteLockingPeriod = ConstU32<{ 2 * MINUTES }>; - type MinimumDeposit = ConstU128<{ 10 * AST }>; - type FastTrackVotingPeriod = ConstU32<{ MINUTES / 2 }>; - type CooloffPeriod = ConstU32<{ 2 * MINUTES }>; - - type MaxVotes = ConstU32<128>; - type MaxProposals = ConstU32<128>; - type MaxDeposits = ConstU32<128>; - type MaxBlacklisted = ConstU32<128>; - - /// A two third majority of the Council can choose the next external "super majority approve" proposal. - type ExternalOrigin = EnsureRootOrTwoThirdsMainCouncil; - /// A two third majority of the Council can choose the next external "majority approve" proposal. Also bypasses blacklist filter. - type ExternalMajorityOrigin = EnsureRootOrTwoThirdsMainCouncil; - /// Unanimous approval of the Council can choose the next external "super majority against" proposal. - type ExternalDefaultOrigin = EnsureRootOrAllMainCouncil; - /// A two third majority of the Technical Committee can have an external proposal tabled immediately - /// for a _fast track_ vote, and a custom enactment period. - type FastTrackOrigin = EnsureRootOrTwoThirdsTechnicalCommittee; - /// Unanimous approval of the Technical Committee can have an external proposal tabled immediately - /// for a completely custom _voting period length_ vote, and a custom enactment period. - type InstantOrigin = EnsureRootOrAllTechnicalCommittee; - type InstantAllowed = ConstBool; - - /// A two third majority of the Council can cancel a passed proposal. Can happen only once per unique proposal. - type CancellationOrigin = EnsureRootOrTwoThirdsMainCouncil; - /// Only a passed public referendum can permanently blacklist a proposal. - type BlacklistOrigin = EnsureRoot; - /// An unanimous Technical Committee can cancel a public proposal, slashing the deposit(s). - type CancelProposalOrigin = EnsureRootOrAllTechnicalCommittee; - /// Any member of the Technical Committee can veto Council's proposal. This can be only done once per proposal, and _veto_ lasts for a _cooloff_ period. - type VetoOrigin = pallet_collective::EnsureMember; - - type SubmitOrigin = EnsureSigned; - type PalletsOrigin = OriginCaller; - type Preimages = Preimage; - type Scheduler = Scheduler; - type Slash = (); - type WeightInfo = pallet_democracy::weights::SubstrateWeight; -} - -parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); - pub MainTreasuryAccount: AccountId = Treasury::account_id(); -} - -impl pallet_treasury::Config for Runtime { - type PalletId = TreasuryPalletId; - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - - // Two origins which can either approve or reject the spending proposal - type ApproveOrigin = EnsureRootOrTwoThirdsMainCouncil; - type RejectOrigin = EnsureRootOrTwoThirdsMainCouncil; - - type OnSlash = Treasury; - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU128<{ 10 * AST }>; - type ProposalBondMaximum = ConstU128<{ 100 * AST }>; - type SpendPeriod = ConstU32<{ 1 * MINUTES }>; - - // We don't do periodic burns of the treasury - type Burn = (); - type BurnDestination = (); - type SpendFunds = (); - type MaxApprovals = ConstU32<64>; - - type WeightInfo = pallet_treasury::weights::SubstrateWeight; -} - -parameter_types! { - pub const CommunityTreasuryPalletId: PalletId = PalletId(*b"py/comtr"); -} - -impl pallet_treasury::Config for Runtime { - type PalletId = CommunityTreasuryPalletId; - type Currency = Balances; - type RuntimeEvent = RuntimeEvent; - - // Two origins which can either approve or reject the spending proposal - type ApproveOrigin = EnsureRootOrTwoThirdsCommunityCouncil; - type RejectOrigin = EnsureRootOrTwoThirdsCommunityCouncil; - - type OnSlash = CommunityTreasury; - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU128<{ 10 * AST }>; - type ProposalBondMaximum = ConstU128<{ 100 * AST }>; - type SpendPeriod = ConstU32<{ 1 * MINUTES }>; - - // We don't do periodic burns of the community treasury - type Burn = (); - type BurnDestination = (); - type SpendFunds = (); - type MaxApprovals = ConstU32<64>; - - type WeightInfo = pallet_treasury::weights::SubstrateWeight; -} - -parameter_types! { - pub CommunityTreasuryAccountId: AccountId = CommunityTreasuryPalletId::get().into_account_truncating(); -} - -#[derive(Default)] -pub struct CommunityCouncilCallFilter; -impl InstanceFilter for CommunityCouncilCallFilter { - fn filter(&self, c: &RuntimeCall) -> bool { - matches!( - c, - RuntimeCall::DappStaking(..) - | RuntimeCall::System(frame_system::Call::remark { .. }) - | RuntimeCall::Utility(pallet_utility::Call::batch { .. }) - | RuntimeCall::Utility(pallet_utility::Call::batch_all { .. }) - ) - } -} - -impl pallet_collective_proxy::Config for Runtime { - type RuntimeCall = RuntimeCall; - type CollectiveProxy = EnsureRootOrTwoThirdsCommunityCouncil; - type ProxyAccountId = CommunityTreasuryAccountId; - type CallFilter = CommunityCouncilCallFilter; - type WeightInfo = pallet_collective_proxy::weights::SubstrateWeight; -} - -/// Calls that can bypass the safe-mode pallet. -pub struct SafeModeWhitelistedCalls; -impl Contains for SafeModeWhitelistedCalls { - fn contains(call: &RuntimeCall) -> bool { - match call { - // System and Timestamp are required for block production - RuntimeCall::System(_) - | RuntimeCall::Timestamp(_) - | RuntimeCall::Sudo(_) - | RuntimeCall::TxPause(_) => true, - _ => false, - } - } -} - -impl pallet_safe_mode::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type Currency = Balances; - type RuntimeHoldReason = RuntimeHoldReason; - type WhitelistedCalls = SafeModeWhitelistedCalls; - type EnterDuration = ConstU32<{ 5 * MINUTES }>; - type EnterDepositAmount = (); - type ExtendDuration = ConstU32<{ 2 * MINUTES }>; - type ExtendDepositAmount = (); - // The 'Success' values below represent the number of blocks that the origin may induce safe mode - type ForceEnterOrigin = - EnsureWithSuccess>; - type ForceExtendOrigin = - EnsureWithSuccess>; - type ForceExitOrigin = EnsureRootOrTwoThirdsTechnicalCommittee; - type ForceDepositOrigin = EnsureRootOrTwoThirdsTechnicalCommittee; - type ReleaseDelay = (); - type Notify = DappStaking; - type WeightInfo = pallet_safe_mode::weights::SubstrateWeight; -} - -impl pallet_tx_pause::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type RuntimeCall = RuntimeCall; - type PauseOrigin = EnsureRootOrHalfTechnicalCommittee; - type UnpauseOrigin = EnsureRootOrHalfTechnicalCommittee; - type WhitelistedCalls = (); - type MaxNameLen = ConstU32<256>; - type WeightInfo = pallet_tx_pause::weights::SubstrateWeight; -} - -construct_runtime!( - pub struct Runtime { - System: frame_system = 10, - Utility: pallet_utility = 11, - Timestamp: pallet_timestamp = 13, - RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip = 16, - Scheduler: pallet_scheduler = 17, - Proxy: pallet_proxy = 18, - - TransactionPayment: pallet_transaction_payment = 30, - Balances: pallet_balances = 31, - Vesting: pallet_vesting = 32, - DappStaking: pallet_dapp_staking = 34, - Inflation: pallet_inflation = 35, - Assets: pallet_assets = 36, - StaticPriceProvider: pallet_static_price_provider = 37, - - Aura: pallet_aura = 43, - Grandpa: pallet_grandpa = 44, - - EVM: pallet_evm = 60, - Ethereum: pallet_ethereum = 61, - DynamicEvmBaseFee: pallet_dynamic_evm_base_fee = 62, - EthereumChecked: pallet_ethereum_checked = 64, - UnifiedAccounts: pallet_unified_accounts = 65, - - Contracts: pallet_contracts = 70, - - Preimage: pallet_preimage = 84, - - // skip 90 - for runtimes consistency (pallet_xvm previously) - - // Governance - Sudo: pallet_sudo = 99, - CouncilMembership: pallet_membership:: = 100, - TechnicalCommitteeMembership: pallet_membership:: = 101, - CommunityCouncilMembership: pallet_membership:: = 102, - Council: pallet_collective:: = 103, - TechnicalCommittee: pallet_collective:: = 104, - CommunityCouncil: pallet_collective:: = 105, - Democracy: pallet_democracy = 106, - Treasury: pallet_treasury:: = 107, - CommunityTreasury: pallet_treasury:: = 108, - CollectiveProxy: pallet_collective_proxy = 109, - SafeMode: pallet_safe_mode = 110, - TxPause: pallet_tx_pause = 111, - } -); - -/// Block type as expected by this runtime. -pub type Block = generic::Block; -/// A Block signed with a Justification -pub type SignedBlock = generic::SignedBlock; -/// BlockId type as expected by this runtime. -pub type BlockId = generic::BlockId; -/// The SignedExtension to the basic transaction logic. -pub type SignedExtra = ( - frame_system::CheckSpecVersion, - frame_system::CheckTxVersion, - frame_system::CheckGenesis, - frame_system::CheckEra, - frame_system::CheckNonce, - frame_system::CheckWeight, - pallet_transaction_payment::ChargeTransactionPayment, - frame_metadata_hash_extension::CheckMetadataHash, -); -/// Unchecked extrinsic type as expected by this runtime. -pub type UncheckedExtrinsic = - fp_self_contained::UncheckedExtrinsic; -/// Extrinsic type that has already been checked. -pub type CheckedExtrinsic = - fp_self_contained::CheckedExtrinsic; -/// The payload being signed in transactions. -pub type SignedPayload = generic::SignedPayload; -/// Executive: handles dispatch to the various modules. -pub type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext, - Runtime, - AllPalletsWithSystem, - Migrations, ->; - -pub type Migrations = (); - -type EventRecord = frame_system::EventRecord< - ::RuntimeEvent, - ::Hash, ->; - -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, - 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, - } - } -} - -#[cfg(feature = "runtime-benchmarks")] -#[macro_use] -extern crate frame_benchmarking; - -#[cfg(feature = "runtime-benchmarks")] -mod benches { - define_benchmarks!( - [frame_benchmarking, BaselineBench::] - [pallet_assets, pallet_assets::Pallet::] - [frame_system, SystemBench::] - [frame_system_extensions, SystemExtensionsBench::] - [pallet_balances, Balances] - [pallet_timestamp, Timestamp] - [pallet_transaction_payment, TransactionPayment] - [pallet_ethereum_checked, EthereumChecked] - [pallet_dapp_staking, DappStaking] - [pallet_inflation, Inflation] - [pallet_dynamic_evm_base_fee, DynamicEvmBaseFee] - [pallet_tx_pause, TxPause] - [pallet_safe_mode, SafeMode] - ); -} - -impl_runtime_apis! { - impl sp_api::Core for Runtime { - fn version() -> RuntimeVersion { - VERSION - } - - fn execute_block(block: Block) { - Executive::execute_block(block); - } - - fn initialize_block(header: &::Header) -> sp_runtime::ExtrinsicInclusionMode { - Executive::initialize_block(header) - } - } - - impl sp_api::Metadata for Runtime { - fn metadata() -> OpaqueMetadata { - OpaqueMetadata::new(Runtime::metadata().into()) - } - - fn metadata_at_version(version: u32) -> Option { - Runtime::metadata_at_version(version) - } - - fn metadata_versions() -> Vec { - Runtime::metadata_versions() - } - } - - impl sp_block_builder::BlockBuilder for Runtime { - fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { - Executive::apply_extrinsic(extrinsic) - } - - fn finalize_block() -> ::Header { - Executive::finalize_block() - } - - fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { - data.create_extrinsics() - } - - fn check_inherents( - block: Block, - data: sp_inherents::InherentData, - ) -> sp_inherents::CheckInherentsResult { - data.check_extrinsics(&block) - } - } - - impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { - fn validate_transaction( - source: TransactionSource, - tx: ::Extrinsic, - block_hash: ::Hash, - ) -> TransactionValidity { - Executive::validate_transaction(source, tx, block_hash) - } - } - - impl sp_offchain::OffchainWorkerApi for Runtime { - fn offchain_worker(header: &::Header) { - Executive::offchain_worker(header) - } - } - - impl sp_consensus_aura::AuraApi for Runtime { - fn slot_duration() -> sp_consensus_aura::SlotDuration { - sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION) - } - - fn authorities() -> Vec { - pallet_aura::Authorities::::get().into_inner() - } - } - - impl sp_session::SessionKeys for Runtime { - fn generate_session_keys(seed: Option>) -> Vec { - SessionKeys::generate(seed) - } - - fn decode_session_keys( - encoded: Vec, - ) -> Option, KeyTypeId)>> { - SessionKeys::decode_into_raw_public_keys(&encoded) - } - } - - impl fg_primitives::GrandpaApi for Runtime { - fn grandpa_authorities() -> GrandpaAuthorityList { - Grandpa::grandpa_authorities() - } - - fn current_set_id() -> fg_primitives::SetId { - Grandpa::current_set_id() - } - - fn submit_report_equivocation_unsigned_extrinsic( - _equivocation_proof: fg_primitives::EquivocationProof< - ::Hash, - NumberFor, - >, - _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof, - ) -> Option<()> { - None - } - - fn generate_key_ownership_proof( - _set_id: fg_primitives::SetId, - _authority_id: GrandpaId, - ) -> Option { - // NOTE: this is the only implementation possible since we've - // defined our key owner proof type as a bottom type (i.e. a type - // with no values). - None - } - } - - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Nonce { - System::account_nonce(account) - } - } - - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { - fn query_info( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { - TransactionPayment::query_info(uxt, len) - } - fn query_fee_details( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment::FeeDetails { - 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) - } - } - - 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) - } - 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) - } - } - - impl fp_rpc::EthereumRuntimeRPCApi for Runtime { - fn chain_id() -> u64 { - ChainId::get() - } - - fn account_basic(address: H160) -> pallet_evm::Account { - 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 tmp: [u8; 32] = index.to_big_endian(); - 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)>>, - authorization_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; - - // Reused approach from Moonbeam since Frontier implementation doesn't support this - let mut estimated_transaction_len = data.len() + - // to: 20 - // from: 20 - // value: 32 - // gas_limit: 32 - // nonce: 32 - // 1 byte transaction action variant - // chain id 8 bytes - // 65 bytes signature - 210; - if max_fee_per_gas.is_some() { - estimated_transaction_len += 32; - } - if max_priority_fee_per_gas.is_some() { - estimated_transaction_len += 32; - } - if access_list.is_some() { - estimated_transaction_len += access_list.encoded_size(); - } - - let gas_limit = gas_limit.min(u64::MAX.into()).low_u64(); - let without_base_extrinsic_weight = true; - - let (weight_limit, proof_size_base_cost) = - match ::GasWeightMapping::gas_to_weight( - gas_limit, - without_base_extrinsic_weight - ) { - weight_limit if weight_limit.proof_size() > 0 => { - (Some(weight_limit), Some(estimated_transaction_len as u64)) - } - _ => (None, None), - }; - - ::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(), - authorization_list.unwrap_or_default(), - is_transactional, - validate, - weight_limit, - proof_size_base_cost, - 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)>>, - authorization_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; - - // Reused approach from Moonbeam since Frontier implementation doesn't support this - let mut estimated_transaction_len = data.len() + - // to: 20 - // from: 20 - // value: 32 - // gas_limit: 32 - // nonce: 32 - // 1 byte transaction action variant - // chain id 8 bytes - // 65 bytes signature - 210; - if max_fee_per_gas.is_some() { - estimated_transaction_len += 32; - } - if max_priority_fee_per_gas.is_some() { - estimated_transaction_len += 32; - } - if access_list.is_some() { - estimated_transaction_len += access_list.encoded_size(); - } - - let gas_limit = gas_limit.min(u64::MAX.into()).low_u64(); - let without_base_extrinsic_weight = true; - - let (weight_limit, proof_size_base_cost) = - match ::GasWeightMapping::gas_to_weight( - gas_limit, - without_base_extrinsic_weight - ) { - weight_limit if weight_limit.proof_size() > 0 => { - (Some(weight_limit), Some(estimated_transaction_len as u64)) - } - _ => (None, None), - }; - - #[allow(clippy::or_fun_call)] // suggestion not helpful here - ::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(), - authorization_list.unwrap_or_default(), - is_transactional, - validate, - weight_limit, - proof_size_base_cost, - config - .as_ref() - .unwrap_or(::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(pallet_ethereum::Call::transact { transaction }) => Some(transaction), - _ => None - }).collect::>() - } - - fn elasticity() -> Option { - Some(Permill::zero()) - } - - fn gas_limit_multiplier_support() {} - - fn pending_block( - xts: Vec<::Extrinsic>, - ) -> (Option, Option>) { - for ext in xts.into_iter() { - let _ = Executive::apply_extrinsic(ext); - } - - Ethereum::on_finalize(System::block_number() + 1); - - ( - pallet_ethereum::CurrentBlock::::get(), - pallet_ethereum::CurrentTransactionStatuses::::get() - ) - } - - fn initialize_pending_block(header: &::Header) { - Executive::initialize_block(header); - } - } - - impl fp_rpc::ConvertTransactionRuntimeApi for Runtime { - fn convert_transaction( - transaction: pallet_ethereum::Transaction - ) -> ::Extrinsic { - UncheckedExtrinsic::new_bare( - pallet_ethereum::Call::::transact { transaction }.into(), - ) - } - } - - impl pallet_contracts::ContractsApi for Runtime { - fn call( - origin: AccountId, - dest: AccountId, - value: Balance, - gas_limit: Option, - storage_deposit_limit: Option, - input_data: Vec, - ) -> pallet_contracts::ContractExecResult { - let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block); - Contracts::bare_call( - origin, - dest, - value, - gas_limit, - storage_deposit_limit, - input_data, - pallet_contracts::DebugInfo::UnsafeDebug, - pallet_contracts::CollectEvents::UnsafeCollect, - pallet_contracts::Determinism::Enforced, - ) - } - - fn instantiate( - origin: AccountId, - value: Balance, - gas_limit: Option, - storage_deposit_limit: Option, - code: pallet_contracts::Code, - data: Vec, - salt: Vec, - ) -> pallet_contracts::ContractInstantiateResult { - let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block); - Contracts::bare_instantiate( - origin, - value, - gas_limit, - storage_deposit_limit, - code, - data, - salt, - pallet_contracts::DebugInfo::UnsafeDebug, - pallet_contracts::CollectEvents::UnsafeCollect, - ) - } - - fn upload_code( - origin: AccountId, - code: Vec, - storage_deposit_limit: Option, - determinism: pallet_contracts::Determinism, - ) -> pallet_contracts::CodeUploadResult - { - Contracts::bare_upload_code(origin, code, storage_deposit_limit, determinism) - } - - fn get_storage( - address: AccountId, - key: Vec, - ) -> pallet_contracts::GetStorageResult { - Contracts::get_storage(address, key) - } - } - - impl dapp_staking_runtime_api::DappStakingApi for Runtime { - fn periods_per_cycle() -> PeriodNumber { - InflationCycleConfig::periods_per_cycle() - } - - fn eras_per_voting_subperiod() -> EraNumber { - InflationCycleConfig::eras_per_voting_subperiod() - } - - fn eras_per_build_and_earn_subperiod() -> EraNumber { - InflationCycleConfig::eras_per_build_and_earn_subperiod() - } - - fn blocks_per_era() -> BlockNumber { - InflationCycleConfig::blocks_per_era() - } - - fn get_dapp_tier_assignment() -> BTreeMap { - DappStaking::get_dapp_tier_assignment() - } - } - - - impl sp_genesis_builder::GenesisBuilder for Runtime { - - fn build_state(config: Vec) -> sp_genesis_builder::Result { - genesis_builder_helper::build_state::(config) - } - - fn get_preset(id: &Option) -> Option> { - genesis_builder_helper::get_preset::(id, &genesis_config::get_preset) - } - - fn preset_names() -> Vec { - vec![ - sp_genesis_builder::PresetId::from("development"), - ] - } - } - - #[cfg(feature = "runtime-benchmarks")] - impl frame_benchmarking::Benchmark for Runtime { - fn benchmark_metadata(extra: bool) -> ( - Vec, - Vec, - ) { - use frame_benchmarking::{baseline, BenchmarkList}; - use frame_support::traits::StorageInfoTrait; - pub use frame_system_benchmarking::{ - extensions::Pallet as SystemExtensionsBench, Pallet as SystemBench - }; - use baseline::Pallet as BaselineBench; - - let mut list = Vec::::new(); - list_benchmarks!(list, extra); - - let storage_info = AllPalletsWithSystem::storage_info(); - - (list, storage_info) - } - - #[allow(non_local_definitions)] - fn dispatch_benchmark( - config: frame_benchmarking::BenchmarkConfig - ) -> Result, alloc::string::String> { - use frame_benchmarking::{baseline, BenchmarkBatch}; - pub use frame_system_benchmarking::{ - extensions::Pallet as SystemExtensionsBench, Pallet as SystemBench - }; - use baseline::Pallet as BaselineBench; - - impl frame_system_benchmarking::Config for Runtime {} - impl baseline::Config for Runtime {} - - use frame_support::traits::{WhitelistedStorageKeys, TrackedStorageKey}; - let whitelist: Vec = AllPalletsWithSystem::whitelisted_storage_keys(); - - let mut batches = Vec::::new(); - let params = (&config, &whitelist); - add_benchmarks!(params, batches); - - if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } - Ok(batches) - } - } - - impl moonbeam_rpc_primitives_debug::DebugRuntimeApi for Runtime { - fn trace_transaction( - extrinsics: Vec<::Extrinsic>, - traced_transaction: &pallet_ethereum::Transaction, - header: &::Header, - ) -> Result< - (), - sp_runtime::DispatchError, - > { - use moonbeam_evm_tracer::tracer::EvmTracer; - - // We need to follow the order when replaying the transactions. - // Block initialize happens first then apply_extrinsic. - Executive::initialize_block(header); - - // Apply the a subset of extrinsics: all the substrate-specific or ethereum - // transactions that preceded the requested transaction. - for ext in extrinsics.into_iter() { - let _ = match &ext.0.function { - RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => { - if transaction == traced_transaction { - EvmTracer::new().trace(|| Executive::apply_extrinsic(ext)); - return Ok(()); - } else { - Executive::apply_extrinsic(ext) - } - } - _ => Executive::apply_extrinsic(ext), - }; - } - Err(sp_runtime::DispatchError::Other( - "Failed to find Ethereum transaction among the extrinsics.", - )) - } - - fn trace_block( - extrinsics: Vec<::Extrinsic>, - known_transactions: Vec, - header: &::Header, - ) -> Result< - (), - sp_runtime::DispatchError, - > { - use moonbeam_evm_tracer::tracer::EvmTracer; - - let mut config = ::config().clone(); - config.estimate = true; - - // We need to follow the order when replaying the transactions. - // Block initialize happens first then apply_extrinsic. - Executive::initialize_block(header); - - // Apply all extrinsics. Ethereum extrinsics are traced. - for ext in extrinsics.into_iter() { - match &ext.0.function { - RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => { - if known_transactions.contains(&transaction.hash()) { - // Each known extrinsic is a new call stack. - EvmTracer::emit_new(); - EvmTracer::new().trace(|| Executive::apply_extrinsic(ext)); - } else { - let _ = Executive::apply_extrinsic(ext); - } - } - _ => { - let _ = Executive::apply_extrinsic(ext); - } - }; - } - - Ok(()) - } - - fn trace_call( - header: &::Header, - from: H160, - to: H160, - data: Vec, - value: U256, - gas_limit: U256, - max_fee_per_gas: Option, - max_priority_fee_per_gas: Option, - nonce: Option, - access_list: Option)>>, - authorization_list: Option, - ) -> Result<(), sp_runtime::DispatchError> { - use moonbeam_evm_tracer::tracer::EvmTracer; - - // Initialize block: calls the "on_initialize" hook on every pallet - // in AllPalletsWithSystem. - Executive::initialize_block(header); - - EvmTracer::new().trace(|| { - let is_transactional = false; - let validate = true; - let without_base_extrinsic_weight = true; - - - // Estimated encoded transaction size must be based on the heaviest transaction - // type (EIP1559Transaction) to be compatible with all transaction types. - let mut estimated_transaction_len = data.len() + - // pallet ethereum index: 1 - // transact call index: 1 - // Transaction enum variant: 1 - // chain_id 8 bytes - // nonce: 32 - // max_priority_fee_per_gas: 32 - // max_fee_per_gas: 32 - // gas_limit: 32 - // action: 21 (enum varianrt + call address) - // value: 32 - // access_list: 1 (empty vec size) - // 65 bytes signature - 258; - - if access_list.is_some() { - estimated_transaction_len += access_list.encoded_size(); - } - - let gas_limit = gas_limit.min(u64::MAX.into()).low_u64(); - - let (weight_limit, proof_size_base_cost) = - match ::GasWeightMapping::gas_to_weight( - gas_limit, - without_base_extrinsic_weight - ) { - weight_limit if weight_limit.proof_size() > 0 => { - (Some(weight_limit), Some(estimated_transaction_len as u64)) - } - _ => (None, None), - }; - - let _ = ::Runner::call( - from, - to, - data, - value, - gas_limit, - max_fee_per_gas, - max_priority_fee_per_gas, - nonce, - access_list.unwrap_or_default(), - authorization_list.unwrap_or_default(), - is_transactional, - validate, - weight_limit, - proof_size_base_cost, - ::config(), - ); - }); - Ok(()) - } - } - - impl moonbeam_rpc_primitives_txpool::TxPoolRuntimeApi for Runtime { - fn extrinsic_filter( - xts_ready: Vec<::Extrinsic>, - xts_future: Vec<::Extrinsic>, - ) -> moonbeam_rpc_primitives_txpool::TxPoolResponse { - moonbeam_rpc_primitives_txpool::TxPoolResponse { - ready: xts_ready - .into_iter() - .filter_map(|xt| match xt.0.function { - RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction), - _ => None, - }) - .collect(), - future: xts_future - .into_iter() - .filter_map(|xt| match xt.0.function { - RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction), - _ => None, - }) - .collect(), - } - } - } - - #[cfg(feature = "try-runtime")] - impl frame_try_runtime::TryRuntime for Runtime { - fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { - log::info!("try-runtime::on_runtime_upgrade"); - 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 { - log::info!( - "try-runtime: executing block #{} ({:?}) / root checks: {:?} / sanity-checks: {:?}", - block.header.number, - block.header.hash(), - state_root_check, - select, - ); - Executive::try_execute_block(block, state_root_check, signature_check, select).expect("execute-block failed") - } - } -} diff --git a/runtime/local/src/precompiles.rs b/runtime/local/src/precompiles.rs deleted file mode 100644 index d9b522d274..0000000000 --- a/runtime/local/src/precompiles.rs +++ /dev/null @@ -1,169 +0,0 @@ -// This file is part of Astar. - -// Copyright (C) Stake Technologies Pte.Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later - -// Astar is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Astar is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Astar. If not, see . - -//! The Local Network EVM precompiles. This can be compiled with ``#[no_std]`, ready for Wasm. - -use crate::{Runtime, RuntimeCall, UnifiedAccounts}; -use astar_primitives::precompiles::DispatchFilterValidate; -use frame_support::traits::ConstU32; -use frame_support::{parameter_types, traits::Contains}; -use pallet_evm_precompile_assets_erc20::Erc20AssetsPrecompileSet; -use pallet_evm_precompile_blake2::Blake2F; -use pallet_evm_precompile_bn128::{Bn128Add, Bn128Mul, Bn128Pairing}; -use pallet_evm_precompile_dapp_staking::DappStakingV3Precompile; -use pallet_evm_precompile_dispatch::Dispatch; -use pallet_evm_precompile_dispatch_lockdrop::DispatchLockdrop; -use pallet_evm_precompile_ed25519::Ed25519Verify; -use pallet_evm_precompile_modexp::Modexp; -use pallet_evm_precompile_sha3fips::Sha3FIPS256; -use pallet_evm_precompile_simple::{ECRecover, ECRecoverPublicKey, Identity, Ripemd160, Sha256}; -use pallet_evm_precompile_sr25519::Sr25519Precompile; -use pallet_evm_precompile_substrate_ecdsa::SubstrateEcdsaPrecompile; -use pallet_evm_precompile_unified_accounts::UnifiedAccountsPrecompile; -use precompile_utils::precompile_set::*; -use sp_std::fmt::Debug; - -/// The asset precompile address prefix. Addresses that match against this prefix will be routed -/// to Erc20AssetsPrecompileSet -pub const ASSET_PRECOMPILE_ADDRESS_PREFIX: &[u8] = &[255u8; 4]; -parameter_types! { - pub AssetPrefix: &'static [u8] = ASSET_PRECOMPILE_ADDRESS_PREFIX; -} - -/// Precompile checks for ethereum spec precompiles -/// We allow DELEGATECALL to stay compliant with Ethereum behavior. -type EthereumPrecompilesChecks = (AcceptDelegateCall, CallableByContract, CallableByPrecompile); - -/// Filter that only allows whitelisted runtime call to pass through dispatch precompile -pub struct WhitelistedCalls; - -impl Contains for WhitelistedCalls { - fn contains(t: &RuntimeCall) -> bool { - match t { - RuntimeCall::Utility(pallet_utility::Call::batch { calls }) - | RuntimeCall::Utility(pallet_utility::Call::batch_all { calls }) => { - calls.iter().all(|call| WhitelistedCalls::contains(call)) - } - RuntimeCall::DappStaking(_) => true, - RuntimeCall::Assets(pallet_assets::Call::transfer { .. }) => true, - RuntimeCall::Democracy(_) - | RuntimeCall::Treasury(_) - | RuntimeCall::CommunityTreasury(_) - | RuntimeCall::Preimage(_) => true, - _ => false, - } - } -} - -/// Filter that only allows whitelisted runtime call to pass through dispatch-lockdrop precompile -pub struct WhitelistedLockdropCalls; - -impl Contains for WhitelistedLockdropCalls { - fn contains(t: &RuntimeCall) -> bool { - match t { - RuntimeCall::Utility(pallet_utility::Call::batch { calls }) - | RuntimeCall::Utility(pallet_utility::Call::batch_all { calls }) => calls - .iter() - .all(|call| WhitelistedLockdropCalls::contains(call)), - RuntimeCall::DappStaking(pallet_dapp_staking::Call::unbond_and_unstake { .. }) => true, - RuntimeCall::DappStaking(pallet_dapp_staking::Call::withdraw_unbonded { .. }) => true, - RuntimeCall::Balances(pallet_balances::Call::transfer_all { .. }) => true, - RuntimeCall::Balances(pallet_balances::Call::transfer_keep_alive { .. }) => true, - RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { .. }) => true, - RuntimeCall::Assets(pallet_assets::Call::transfer { .. }) => true, - _ => false, - } - } -} - -/// The PrecompileSet installed in the Local runtime. -#[precompile_utils::precompile_name_from_address] -pub type LocalPrecompilesSetAt = ( - // Ethereum precompiles: - // We allow DELEGATECALL to stay compliant with Ethereum behavior. - PrecompileAt, ECRecover, EthereumPrecompilesChecks>, - PrecompileAt, Sha256, EthereumPrecompilesChecks>, - PrecompileAt, Ripemd160, EthereumPrecompilesChecks>, - PrecompileAt, Identity, EthereumPrecompilesChecks>, - PrecompileAt, Modexp, EthereumPrecompilesChecks>, - PrecompileAt, Bn128Add, EthereumPrecompilesChecks>, - PrecompileAt, Bn128Mul, EthereumPrecompilesChecks>, - PrecompileAt, Bn128Pairing, EthereumPrecompilesChecks>, - PrecompileAt, Blake2F, EthereumPrecompilesChecks>, - // Non-Local specific nor Ethereum precompiles : - PrecompileAt< - AddressU64<1024>, - Sha3FIPS256, - (CallableByContract, CallableByPrecompile), - >, - PrecompileAt< - AddressU64<1025>, - Dispatch>, - // Not callable from smart contract nor precompiles, only EOA accounts - (), - >, - PrecompileAt, ECRecoverPublicKey, (CallableByContract, CallableByPrecompile)>, - PrecompileAt, Ed25519Verify, (CallableByContract, CallableByPrecompile)>, - // Local specific precompiles: - PrecompileAt< - AddressU64<20481>, - DappStakingV3Precompile, - (CallableByContract, CallableByPrecompile), - >, - PrecompileAt< - AddressU64<20482>, - Sr25519Precompile, - (CallableByContract, CallableByPrecompile), - >, - PrecompileAt< - AddressU64<20483>, - SubstrateEcdsaPrecompile, - (CallableByContract, CallableByPrecompile), - >, - // skip 20484 for xcm precompile - // Skipping 20485 to make sure all network have consistent precompiles address - PrecompileAt< - AddressU64<20486>, - UnifiedAccountsPrecompile, - (CallableByContract, CallableByPrecompile), - >, - PrecompileAt< - AddressU64<20487>, - DispatchLockdrop< - R, - DispatchFilterValidate, - ConstU32<8>, - >, - // Not callable from smart contract nor precompiled, only EOA accounts - (), - >, -); - -pub type LocalPrecompiles = PrecompileSetBuilder< - R, - ( - // Skip precompiles if out of range. - PrecompilesInRangeInclusive< - // We take range as last precompile index, UPDATE this once new precompile is added - (AddressU64<1>, AddressU64<20487>), - LocalPrecompilesSetAt, - >, - // Prefixed precompile sets (XC20) - PrecompileSetStartingWith, CallableByContract>, - ), ->; diff --git a/runtime/local/src/weights/mod.rs b/runtime/local/src/weights/mod.rs deleted file mode 100644 index e36df4ccde..0000000000 --- a/runtime/local/src/weights/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -// This file is part of Astar. - -// Copyright (C) Stake Technologies Pte.Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later - -// Astar is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Astar is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Astar. If not, see . - -pub mod pallet_assets; -pub mod pallet_balances; diff --git a/runtime/local/src/weights/pallet_assets.rs b/runtime/local/src/weights/pallet_assets.rs deleted file mode 100644 index 4221949d94..0000000000 --- a/runtime/local/src/weights/pallet_assets.rs +++ /dev/null @@ -1,573 +0,0 @@ - -// This file is part of Astar. - -// Copyright (C) Stake Technologies Pte.Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later - -// Astar is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Astar is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Astar. If not, see . - -//! Autogenerated weights for `pallet_assets` -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 46.1.0 -//! DATE: 2025-05-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `Ashutoshs-MacBook-Pro.local`, CPU: `` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 - -// Executed Command: -// ./target/release/astar-collator -// benchmark -// pallet -// --chain=dev -// --steps=50 -// --repeat=20 -// --pallet=pallet_assets -// --extrinsic=* -// --wasm-execution=compiled -// --heap-pages=4096 -// --output=./runtime/local/src/weights/pallet_assets.rs -// --template=./scripts/templates/weight-template.hbs - -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(missing_docs)] - -use frame_support::{traits::Get, weights::Weight}; -use core::marker::PhantomData; - -/// Weight functions for `pallet_assets`. -pub struct SubstrateWeight(PhantomData); -impl pallet_assets::WeightInfo for SubstrateWeight { - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::NextAssetId` (r:1 w:0) - /// Proof: `Assets::NextAssetId` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `EVM::AccountCodes` (r:1 w:1) - /// Proof: `EVM::AccountCodes` (`max_values`: None, `max_size`: None, mode: `Measured`) - fn create() -> Weight { - // Proof Size summary in bytes: - // Measured: `695` - // Estimated: `4160` - // Minimum execution time: 36_000_000 picoseconds. - Weight::from_parts(39_000_000, 0) - .saturating_add(Weight::from_parts(0, 4160)) - .saturating_add(T::DbWeight::get().reads(4)) - .saturating_add(T::DbWeight::get().writes(3)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::NextAssetId` (r:1 w:0) - /// Proof: `Assets::NextAssetId` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) - /// Storage: `EVM::AccountCodes` (r:1 w:1) - /// Proof: `EVM::AccountCodes` (`max_values`: None, `max_size`: None, mode: `Measured`) - fn force_create() -> Weight { - // Proof Size summary in bytes: - // Measured: `555` - // Estimated: `4020` - // Minimum execution time: 19_000_000 picoseconds. - Weight::from_parts(21_000_000, 0) - .saturating_add(Weight::from_parts(0, 4020)) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - fn start_destroy() -> Weight { - // Proof Size summary in bytes: - // Measured: `360` - // Estimated: `3687` - // Minimum execution time: 13_000_000 picoseconds. - Weight::from_parts(14_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:1001 w:1000) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1000 w:1000) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `UnifiedAccounts::NativeToEvm` (r:1000 w:0) - /// Proof: `UnifiedAccounts::NativeToEvm` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) - /// The range of component `c` is `[0, 1000]`. - fn destroy_accounts(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `491 + c * (208 ±0)` - // Estimated: `3687 + c * (2621 ±0)` - // Minimum execution time: 16_000_000 picoseconds. - Weight::from_parts(22_272_379, 0) - .saturating_add(Weight::from_parts(0, 3687)) - // Standard Error: 26_768 - .saturating_add(Weight::from_parts(14_663_063, 0).saturating_mul(c.into())) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(c.into()))) - .saturating_add(T::DbWeight::get().writes(1)) - .saturating_add(T::DbWeight::get().writes((2_u64).saturating_mul(c.into()))) - .saturating_add(Weight::from_parts(0, 2621).saturating_mul(c.into())) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Approvals` (r:1001 w:1000) - /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(160), added: 2635, mode: `MaxEncodedLen`) - /// The range of component `a` is `[0, 1000]`. - fn destroy_approvals(a: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `509 + a * (86 ±0)` - // Estimated: `3687 + a * (2635 ±0)` - // Minimum execution time: 17_000_000 picoseconds. - Weight::from_parts(17_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - // Standard Error: 7_538 - .saturating_add(Weight::from_parts(15_841_913, 0).saturating_mul(a.into())) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(a.into()))) - .saturating_add(T::DbWeight::get().writes(1)) - .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(a.into()))) - .saturating_add(Weight::from_parts(0, 2635).saturating_mul(a.into())) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Metadata` (r:1 w:0) - /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(152), added: 2627, mode: `MaxEncodedLen`) - /// Storage: `EVM::AccountCodes` (r:0 w:1) - /// Proof: `EVM::AccountCodes` (`max_values`: None, `max_size`: None, mode: `Measured`) - fn finish_destroy() -> Weight { - // Proof Size summary in bytes: - // Measured: `326` - // Estimated: `3687` - // Minimum execution time: 16_000_000 picoseconds. - Weight::from_parts(16_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:1 w:1) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - fn mint() -> Weight { - // Proof Size summary in bytes: - // Measured: `326` - // Estimated: `3687` - // Minimum execution time: 24_000_000 picoseconds. - Weight::from_parts(25_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:1 w:1) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - /// Storage: `UnifiedAccounts::NativeToEvm` (r:1 w:0) - /// Proof: `UnifiedAccounts::NativeToEvm` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) - fn burn() -> Weight { - // Proof Size summary in bytes: - // Measured: `452` - // Estimated: `3687` - // Minimum execution time: 35_000_000 picoseconds. - Weight::from_parts(35_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:2 w:2) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `UnifiedAccounts::NativeToEvm` (r:1 w:0) - /// Proof: `UnifiedAccounts::NativeToEvm` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) - fn transfer() -> Weight { - // Proof Size summary in bytes: - // Measured: `557` - // Estimated: `6232` - // Minimum execution time: 44_000_000 picoseconds. - Weight::from_parts(48_000_000, 0) - .saturating_add(Weight::from_parts(0, 6232)) - .saturating_add(T::DbWeight::get().reads(5)) - .saturating_add(T::DbWeight::get().writes(4)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:2 w:2) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn transfer_keep_alive() -> Weight { - // Proof Size summary in bytes: - // Measured: `551` - // Estimated: `6232` - // Minimum execution time: 39_000_000 picoseconds. - Weight::from_parts(41_000_000, 0) - .saturating_add(Weight::from_parts(0, 6232)) - .saturating_add(T::DbWeight::get().reads(4)) - .saturating_add(T::DbWeight::get().writes(4)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:2 w:2) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `UnifiedAccounts::NativeToEvm` (r:1 w:0) - /// Proof: `UnifiedAccounts::NativeToEvm` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) - fn force_transfer() -> Weight { - // Proof Size summary in bytes: - // Measured: `557` - // Estimated: `6232` - // Minimum execution time: 47_000_000 picoseconds. - Weight::from_parts(48_000_000, 0) - .saturating_add(Weight::from_parts(0, 6232)) - .saturating_add(T::DbWeight::get().reads(5)) - .saturating_add(T::DbWeight::get().writes(4)) - } - /// Storage: `Assets::Asset` (r:1 w:0) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:1 w:1) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - fn freeze() -> Weight { - // Proof Size summary in bytes: - // Measured: `446` - // Estimated: `3687` - // Minimum execution time: 16_000_000 picoseconds. - Weight::from_parts(17_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `Assets::Asset` (r:1 w:0) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:1 w:1) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - fn thaw() -> Weight { - // Proof Size summary in bytes: - // Measured: `446` - // Estimated: `3687` - // Minimum execution time: 15_000_000 picoseconds. - Weight::from_parts(17_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - fn freeze_asset() -> Weight { - // Proof Size summary in bytes: - // Measured: `360` - // Estimated: `3687` - // Minimum execution time: 13_000_000 picoseconds. - Weight::from_parts(14_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - fn thaw_asset() -> Weight { - // Proof Size summary in bytes: - // Measured: `360` - // Estimated: `3687` - // Minimum execution time: 12_000_000 picoseconds. - Weight::from_parts(14_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Metadata` (r:1 w:0) - /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(152), added: 2627, mode: `MaxEncodedLen`) - fn transfer_ownership() -> Weight { - // Proof Size summary in bytes: - // Measured: `326` - // Estimated: `3687` - // Minimum execution time: 15_000_000 picoseconds. - Weight::from_parts(15_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - fn set_team() -> Weight { - // Proof Size summary in bytes: - // Measured: `326` - // Estimated: `3687` - // Minimum execution time: 13_000_000 picoseconds. - Weight::from_parts(13_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `Assets::Asset` (r:1 w:0) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Metadata` (r:1 w:1) - /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(152), added: 2627, mode: `MaxEncodedLen`) - /// The range of component `n` is `[0, 50]`. - /// The range of component `s` is `[0, 50]`. - fn set_metadata(n: u32, s: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `326` - // Estimated: `3687` - // Minimum execution time: 27_000_000 picoseconds. - Weight::from_parts(29_752_036, 0) - .saturating_add(Weight::from_parts(0, 3687)) - // Standard Error: 1_120 - .saturating_add(Weight::from_parts(3_280, 0).saturating_mul(n.into())) - // Standard Error: 1_120 - .saturating_add(Weight::from_parts(4_743, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `Assets::Asset` (r:1 w:0) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Metadata` (r:1 w:1) - /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(152), added: 2627, mode: `MaxEncodedLen`) - fn clear_metadata() -> Weight { - // Proof Size summary in bytes: - // Measured: `502` - // Estimated: `3687` - // Minimum execution time: 29_000_000 picoseconds. - Weight::from_parts(30_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `Assets::Asset` (r:1 w:0) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Metadata` (r:1 w:1) - /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(152), added: 2627, mode: `MaxEncodedLen`) - /// The range of component `n` is `[0, 50]`. - /// The range of component `s` is `[0, 50]`. - fn force_set_metadata(n: u32, _s: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `165` - // Estimated: `3687` - // Minimum execution time: 13_000_000 picoseconds. - Weight::from_parts(14_412_998, 0) - .saturating_add(Weight::from_parts(0, 3687)) - // Standard Error: 2_345 - .saturating_add(Weight::from_parts(17_028, 0).saturating_mul(n.into())) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `Assets::Asset` (r:1 w:0) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Metadata` (r:1 w:1) - /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(152), added: 2627, mode: `MaxEncodedLen`) - fn force_clear_metadata() -> Weight { - // Proof Size summary in bytes: - // Measured: `502` - // Estimated: `3687` - // Minimum execution time: 29_000_000 picoseconds. - Weight::from_parts(30_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - fn force_asset_status() -> Weight { - // Proof Size summary in bytes: - // Measured: `326` - // Estimated: `3687` - // Minimum execution time: 13_000_000 picoseconds. - Weight::from_parts(13_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Approvals` (r:1 w:1) - /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(160), added: 2635, mode: `MaxEncodedLen`) - fn approve_transfer() -> Weight { - // Proof Size summary in bytes: - // Measured: `360` - // Estimated: `3687` - // Minimum execution time: 32_000_000 picoseconds. - Weight::from_parts(34_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Approvals` (r:1 w:1) - /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(160), added: 2635, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:2 w:2) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn transfer_approved() -> Weight { - // Proof Size summary in bytes: - // Measured: `784` - // Estimated: `6232` - // Minimum execution time: 66_000_000 picoseconds. - Weight::from_parts(67_000_000, 0) - .saturating_add(Weight::from_parts(0, 6232)) - .saturating_add(T::DbWeight::get().reads(5)) - .saturating_add(T::DbWeight::get().writes(5)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Approvals` (r:1 w:1) - /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(160), added: 2635, mode: `MaxEncodedLen`) - fn cancel_approval() -> Weight { - // Proof Size summary in bytes: - // Measured: `542` - // Estimated: `3687` - // Minimum execution time: 34_000_000 picoseconds. - Weight::from_parts(35_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Approvals` (r:1 w:1) - /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(160), added: 2635, mode: `MaxEncodedLen`) - fn force_cancel_approval() -> Weight { - // Proof Size summary in bytes: - // Measured: `542` - // Estimated: `3687` - // Minimum execution time: 34_000_000 picoseconds. - Weight::from_parts(35_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - fn set_min_balance() -> Weight { - // Proof Size summary in bytes: - // Measured: `326` - // Estimated: `3687` - // Minimum execution time: 14_000_000 picoseconds. - Weight::from_parts(14_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `Assets::Account` (r:1 w:1) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn touch() -> Weight { - // Proof Size summary in bytes: - // Measured: `533` - // Estimated: `3687` - // Minimum execution time: 35_000_000 picoseconds. - Weight::from_parts(35_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(3)) - } - /// Storage: `Assets::Account` (r:1 w:1) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - fn touch_other() -> Weight { - // Proof Size summary in bytes: - // Measured: `326` - // Estimated: `3687` - // Minimum execution time: 32_000_000 picoseconds. - Weight::from_parts(33_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: `Assets::Account` (r:1 w:1) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn refund() -> Weight { - // Proof Size summary in bytes: - // Measured: `671` - // Estimated: `3687` - // Minimum execution time: 33_000_000 picoseconds. - Weight::from_parts(34_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(3)) - } - /// Storage: `Assets::Account` (r:1 w:1) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - fn refund_other() -> Weight { - // Proof Size summary in bytes: - // Measured: `497` - // Estimated: `3687` - // Minimum execution time: 31_000_000 picoseconds. - Weight::from_parts(31_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: `Assets::Asset` (r:1 w:0) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:1 w:1) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - fn block() -> Weight { - // Proof Size summary in bytes: - // Measured: `446` - // Estimated: `3687` - // Minimum execution time: 17_000_000 picoseconds. - Weight::from_parts(18_000_000, 0) - .saturating_add(Weight::from_parts(0, 3687)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(222), added: 2697, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:2 w:2) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) - /// Storage: `UnifiedAccounts::NativeToEvm` (r:1 w:0) - /// Proof: `UnifiedAccounts::NativeToEvm` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn transfer_all() -> Weight { - // Proof Size summary in bytes: - // Measured: `557` - // Estimated: `6232` - // Minimum execution time: 57_000_000 picoseconds. - Weight::from_parts(58_000_000, 0) - .saturating_add(Weight::from_parts(0, 6232)) - .saturating_add(T::DbWeight::get().reads(5)) - .saturating_add(T::DbWeight::get().writes(4)) - } - - fn total_issuance() -> Weight { - todo!() - } - - fn balance() -> Weight { - todo!() - } - - fn allowance() -> Weight { - todo!() - } -} diff --git a/runtime/local/src/weights/pallet_balances.rs b/runtime/local/src/weights/pallet_balances.rs deleted file mode 100644 index 6b8a68c5b9..0000000000 --- a/runtime/local/src/weights/pallet_balances.rs +++ /dev/null @@ -1,187 +0,0 @@ -// This file is part of Astar. - -// Copyright (C) Stake Technologies Pte.Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later - -// Astar is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Astar is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Astar. If not, see . - -//! Autogenerated weights for pallet_balances -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 46.1.0 -//! DATE: 2025-05-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `Ashutoshs-MacBook-Pro.local`, CPU: `` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 - -// Executed Command: -// ./target/release/astar-collator -// benchmark -// pallet -// --chain=dev -// --steps=50 -// --repeat=20 -// --pallet=pallet_balances -// --extrinsic=* -// --wasm-execution=compiled -// --heap-pages=4096 -// --output=./runtime/local/src/weights/pallet_balances.rs -// --template=./scripts/templates/weight-template.hbs - -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(missing_docs)] - -use frame_support::{traits::Get, weights::Weight}; -use core::marker::PhantomData; - -/// Weight functions for `pallet_balances`. -pub struct SubstrateWeight(PhantomData); -impl pallet_balances::WeightInfo for SubstrateWeight { - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `UnifiedAccounts::NativeToEvm` (r:1 w:0) - /// Proof: `UnifiedAccounts::NativeToEvm` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) - fn transfer_allow_death() -> Weight { - // Proof Size summary in bytes: - // Measured: `58` - // Estimated: `3593` - // Minimum execution time: 57_000_000 picoseconds. - Weight::from_parts(58_000_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn transfer_keep_alive() -> Weight { - // Proof Size summary in bytes: - // Measured: `52` - // Estimated: `3593` - // Minimum execution time: 43_000_000 picoseconds. - Weight::from_parts(44_000_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn force_set_balance_creating() -> Weight { - // Proof Size summary in bytes: - // Measured: `207` - // Estimated: `3593` - // Minimum execution time: 16_000_000 picoseconds. - Weight::from_parts(17_000_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `UnifiedAccounts::NativeToEvm` (r:1 w:0) - /// Proof: `UnifiedAccounts::NativeToEvm` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) - fn force_set_balance_killing() -> Weight { - // Proof Size summary in bytes: - // Measured: `213` - // Estimated: `3593` - // Minimum execution time: 27_000_000 picoseconds. - Weight::from_parts(28_000_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `System::Account` (r:2 w:2) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `UnifiedAccounts::NativeToEvm` (r:1 w:0) - /// Proof: `UnifiedAccounts::NativeToEvm` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) - fn force_transfer() -> Weight { - // Proof Size summary in bytes: - // Measured: `161` - // Estimated: `6196` - // Minimum execution time: 59_000_000 picoseconds. - Weight::from_parts(60_000_000, 0) - .saturating_add(Weight::from_parts(0, 6196)) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `UnifiedAccounts::NativeToEvm` (r:1 w:0) - /// Proof: `UnifiedAccounts::NativeToEvm` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) - fn transfer_all() -> Weight { - // Proof Size summary in bytes: - // Measured: `58` - // Estimated: `3593` - // Minimum execution time: 56_000_000 picoseconds. - Weight::from_parts(57_000_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn force_unreserve() -> Weight { - // Proof Size summary in bytes: - // Measured: `207` - // Estimated: `3593` - // Minimum execution time: 19_000_000 picoseconds. - Weight::from_parts(21_000_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `System::Account` (r:999 w:999) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// The range of component `u` is `[1, 1000]`. - fn upgrade_accounts(u: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `0 + u * (136 ±0)` - // Estimated: `990 + u * (2603 ±0)` - // Minimum execution time: 19_000_000 picoseconds. - Weight::from_parts(20_000_000, 0) - .saturating_add(Weight::from_parts(0, 990)) - // Standard Error: 8_317 - .saturating_add(Weight::from_parts(14_335_968, 0).saturating_mul(u.into())) - .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(u.into()))) - .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(u.into()))) - .saturating_add(Weight::from_parts(0, 2603).saturating_mul(u.into())) - } - fn force_adjust_total_issuance() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 6_000_000 picoseconds. - Weight::from_parts(6_000_000, 0) - .saturating_add(Weight::from_parts(0, 0)) - } - /// Storage: `UnifiedAccounts::NativeToEvm` (r:1 w:0) - /// Proof: `UnifiedAccounts::NativeToEvm` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) - fn burn_allow_death() -> Weight { - // Proof Size summary in bytes: - // Measured: `6` - // Estimated: `3533` - // Minimum execution time: 34_000_000 picoseconds. - Weight::from_parts(35_000_000, 0) - .saturating_add(Weight::from_parts(0, 3533)) - .saturating_add(T::DbWeight::get().reads(1)) - } - fn burn_keep_alive() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 20_000_000 picoseconds. - Weight::from_parts(22_000_000, 0) - .saturating_add(Weight::from_parts(0, 0)) - } -} diff --git a/runtime/shibuya/src/genesis_config.rs b/runtime/shibuya/src/genesis_config.rs index 5c35c868cb..277735ea9f 100644 --- a/runtime/shibuya/src/genesis_config.rs +++ b/runtime/shibuya/src/genesis_config.rs @@ -21,6 +21,7 @@ use astar_primitives::{ dapp_staking::FIXED_TIER_SLOTS_ARGS, evm::EVM_REVERT_CODE, genesis::GenesisAccount, parachain::SHIBUYA_ID, }; +use sp_core::crypto::Ss58Codec; /// Provides the JSON representation of predefined genesis config for given `id`. pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option> { @@ -37,6 +38,8 @@ pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option> { /// Get the default genesis config for the Shibuya runtime. pub fn default_config(para_id: u32) -> serde_json::Value { + const DEV_EVM_PREFUND_SS58: &str = "5FQedkNQcF2fJPwkB6Z1ZcMgGti4vcJQNs6x85YPv3VhjBBT"; + let alice = GenesisAccount::::from_seed("Alice"); let bob = GenesisAccount::::from_seed("Bob"); let charlie = GenesisAccount::::from_seed("Charlie"); @@ -49,12 +52,18 @@ pub fn default_config(para_id: u32) -> serde_json::Value { .map(|x| x.account_id()) .collect::>(); + // Private key: 0x01ab6e801c06e59ca97a14fc0a1978b27fa366fc87450e0b65459dd3515b7391 + // H160 public address: 0xaaafB3972B05630fCceE866eC69CdADd9baC2771 + let dev_evm_prefund_account = + AccountId::from_ss58check(DEV_EVM_PREFUND_SS58).expect("Invalid dev EVM prefund SS58"); + let balances = accounts .iter() .chain( vec![ TreasuryPalletId::get().into_account_truncating(), CommunityTreasuryPalletId::get().into_account_truncating(), + dev_evm_prefund_account, ] .iter(), ) diff --git a/tarpaulin.toml b/tarpaulin.toml index 0e07cb86b6..4bfa67dbc8 100644 --- a/tarpaulin.toml +++ b/tarpaulin.toml @@ -7,7 +7,7 @@ workspace = true out = ["Xml"] # List of packages to exclude from testing. -exclude = ["astar-collator", "xcm-tools", "local-runtime", "shibuya-runtime", "shiden-runtime", "astar-runtime", "integration-tests"] +exclude = ["astar-collator", "xcm-tools", "shibuya-runtime", "shiden-runtime", "astar-runtime", "integration-tests"] # List of file paths to exclude from testing. exclude-files = ["vendor/*", "bin/*", "runtime/*", "tests/*", "**/mock.rs", "**/weights.rs"]