diff --git a/.github/workflows/benchmarking.yml b/.github/workflows/benchmarking.yml index 8e7fe5af..ae80d6ea 100644 --- a/.github/workflows/benchmarking.yml +++ b/.github/workflows/benchmarking.yml @@ -5,20 +5,40 @@ on: jobs: build: - name: Build Target - runs-on: [self-hosted, builder] + runs-on: ubuntu-latest steps: + - name: Setup Ubuntu dependencies + shell: bash + run: sudo apt update && sudo apt install -y protobuf-compiler + + - name: Use Nightly + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: nightly + target: wasm32-unknown-unknown + components: rust-src + - uses: actions/checkout@v4 - - uses: actions/cache@v4 + + - name: Rust Cache + uses: swatinem/rust-cache@v2 with: - path: target - key: ${{ runner.os }}-target-cache - - run: just build-local runtime-benchmarks + cache-on-failure: true + cache-all-crates: true + key: build + + - name: Release build with runtime-benchmarks + uses: actions-rs/cargo@v1 + with: + command: build + args: --release --features runtime-benchmarks + - uses: actions/upload-artifact@v4 with: - name: ${{ github.run_number }}-virto-node - path: ./target/release/virto-node - + name: ${{ github.run_number }}-runtime + path: ./target/release/wbuild/kreivo-runtime/kreivo_runtime.compact.compressed.wasm + benchmark: name: Run Benchmarks needs: build @@ -28,18 +48,24 @@ jobs: pull-requests: write steps: - uses: actions/checkout@v4 - - run: | + + - name: Create `target/release` folder + run: | mkdir -p .benchmarking-logs target/release + - uses: actions/download-artifact@v4 with: - name: ${{ github.run_number }}-virto-node + name: ${{ github.run_number }}-runtime path: ./target/release + - run: | just benchmarks + - uses: actions/upload-artifact@v4 with: name: ${{ github.run_id }}-benchmark_logs path: ./.benchmarking-logs + - uses: peter-evans/create-pull-request@v6 with: add-paths: runtime/kreivo/src/weights diff --git a/.github/workflows/check-pr.yml b/.github/workflows/check-pr.yml deleted file mode 100644 index 96b1c359..00000000 --- a/.github/workflows/check-pr.yml +++ /dev/null @@ -1,28 +0,0 @@ -name: Checks - -on: - pull_request: - -jobs: - build: - name: Check lint - runs-on: [self-hosted, builder] - steps: - - uses: actions/checkout@v4 - - uses: actions/cache@v4 - with: - path: target - key: ${{ runner.os }}-${{ github.ref }}-target-cache - - run: just check - - tests: - name: Check project - runs-on: [self-hosted, builder] - needs: build - steps: - - uses: actions/checkout@v4 - - uses: actions/cache@v4 - with: - path: target - key: ${{ runner.os }}-${{ github.ref }}-target-cache - - run: just test \ No newline at end of file diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 00000000..7144cc64 --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,127 @@ +name: Lint, check, clippy and test + +on: + push: + branches: [ main ] + pull_request: + types: [ opened, synchronize, reopened, ready_for_review ] + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - name: Use Nightly with `rustfmt` + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: nightly + components: rustfmt + + - uses: actions/checkout@v4 + + - name: Check formatting + uses: actions-rs/cargo@v1 + with: + toolchain: nightly + command: fmt + args: --all -- --check + + check: + needs: lint + runs-on: ubuntu-latest + steps: + - name: Setup Ubuntu dependencies + shell: bash + run: sudo apt update && sudo apt install -y protobuf-compiler + + - name: Use Nightly + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: nightly + target: wasm32-unknown-unknown + components: rust-src + + - uses: actions/checkout@v4 + + - name: Rust Cache + uses: swatinem/rust-cache@v2 + with: + cache-on-failure: true + cache-all-crates: true + key: check + + - name: Check Build + uses: actions-rs/cargo@v1 + with: + command: check + toolchain: nightly + args: --release --locked --all-features --workspace + + clippy: + needs: lint + runs-on: ubuntu-latest + permissions: + checks: write + env: + SKIP_WASM_BUILD: 1 + steps: + - name: Setup Ubuntu dependencies + shell: bash + run: sudo apt update && sudo apt install -y protobuf-compiler + + - name: Use Nightly with `clippy` + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: nightly + components: clippy,rust-src + + - uses: actions/checkout@v4 + + - name: Rust Cache + uses: swatinem/rust-cache@v2 + with: + cache-on-failure: true + cache-all-crates: true + key: check + + - name: Annotate with Clippy warnings + uses: actions-rs/clippy-check@v1 + with: + token: ${{ secrets.GITHUB_TOKEN }} + toolchain: nightly + args: --release --locked --all-features --workspace + + test: + needs: lint + runs-on: ubuntu-latest + env: + SKIP_WASM_BUILD: 1 + steps: + - name: Setup Ubuntu dependencies + shell: bash + run: sudo apt update && sudo apt install -y protobuf-compiler + + - name: Use Nightly + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: nightly + components: rust-src + + - uses: actions/checkout@v4 + + - name: Rust Cache + uses: swatinem/rust-cache@v2 + with: + cache-on-failure: true + cache-all-crates: true + key: test + + - name: Run tests + uses: actions-rs/cargo@v1 + with: + command: test + toolchain: nightly + args: --lib --release --locked --all-features --workspace diff --git a/.github/workflows/lint-pr.yml b/.github/workflows/lint-pr.yml new file mode 100644 index 00000000..047030c2 --- /dev/null +++ b/.github/workflows/lint-pr.yml @@ -0,0 +1,20 @@ +name: "Lint PR" + +on: + pull_request_target: + types: + - opened + - edited + - synchronize + +permissions: + pull-requests: read + +jobs: + lint: + name: Validate PR title for conventional commit compliance + runs-on: ubuntu-latest + steps: + - uses: amannn/action-semantic-pull-request@v5 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3a6e197d..7ce242fb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -31,16 +31,3 @@ jobs: with: files: | release/* - - container: - name: Containerize & Publish - needs: build - runs-on: [self-hosted, builder] - steps: - - name: Login to registry - run: echo "${{ secrets.GITHUB_TOKEN }}" | podman login ghcr.io -u ${{ github.actor }} --password-stdin - - - name: Publish image - run: | - podman push ghcr.io/virto-network/virto:$(just version) - podman push ghcr.io/virto-network/virto:latest diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml deleted file mode 100644 index f2f280c5..00000000 --- a/.github/workflows/rust.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: Test parachain - -on: - push: - branches: - - master - -jobs: - build: - name: Build project - runs-on: self-hosted - steps: - - uses: actions/checkout@v4 - - name: Test parachain - run: echo test #TODO: change for integration test when available diff --git a/Cargo.lock b/Cargo.lock index aab22a02..69b0bbb1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -864,14 +864,12 @@ dependencies = [ "clap", "cumulus-primitives-core", "kreivo-runtime", - "parachains-common", "sc-chain-spec", "sc-network", "serde", "serde_json", "sp-core", "sp-runtime", - "staging-xcm", ] [[package]] @@ -3640,6 +3638,7 @@ dependencies = [ "runtime-common", "runtime-constants", "scale-info", + "serde_json", "smallvec", "sp-api", "sp-block-builder", @@ -7145,12 +7144,15 @@ name = "runtime-constants" version = "1.0.0" dependencies = [ "frame-support", + "parachains-common", "polkadot-primitives", "polkadot-runtime-common", "smallvec", "sp-core", "sp-runtime", + "sp-std", "sp-weights", + "staging-xcm", "staging-xcm-builder", ] diff --git a/Cargo.toml b/Cargo.toml index 42231c1b..ab0fcb88 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ parity-scale-codec = { version = "3.6.4", default-features = false, features = [ scale-info = { version = "2.10.0", default-features = false, features = [ "derive", ] } -serde = { version = "1.0.188", default-features = false, features = ["derive"] } -serde_json = "1.0.121" +serde = { version = "1.0.188", default-features = false } +serde_json = { version = "1.0.121", default-features = false } smallvec = "1.11" # Local dependencies diff --git a/chain-spec-generator/Cargo.toml b/chain-spec-generator/Cargo.toml index 372520a2..493d2e91 100644 --- a/chain-spec-generator/Cargo.toml +++ b/chain-spec-generator/Cargo.toml @@ -16,12 +16,10 @@ serde = { workspace = true, features = ["derive"] } kreivo-runtime = { workspace = true, default-features = true } cumulus-primitives-core.workspace = true -parachains-common.workspace = true sp-core.workspace = true sp-runtime.workspace = true sc-chain-spec.workspace = true sc-network.workspace = true -xcm.workspace = true [features] runtime-benchmarks = [ diff --git a/chain-spec-generator/src/common.rs b/chain-spec-generator/src/common.rs deleted file mode 100644 index e56e6e0b..00000000 --- a/chain-spec-generator/src/common.rs +++ /dev/null @@ -1,44 +0,0 @@ -use parachains_common::{AccountId, AuraId, Signature}; -use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup}; -use serde::{Deserialize, Serialize}; -use sp_core::{Pair, Public}; -use sp_runtime::traits::{IdentifyAccount, Verify}; - -/// The default XCM version to set in genesis config. -pub const SAFE_XCM_VERSION: u32 = xcm::prelude::XCM_VERSION; - -/// The extensions for the [`ChainSpec`]. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)] -pub struct Extensions { - /// The relay chain of the Parachain. - #[serde(alias = "relayChain", alias = "RelayChain")] - pub relay_chain: String, - /// The id of the Parachain. - #[serde(alias = "paraId", alias = "ParaId")] - pub para_id: u32, -} - -/// Helper function to generate a crypto pair from seed -pub fn get_from_seed(seed: &str) -> ::Public { - TPublic::Pair::from_string(&format!("//{}", seed), None) - .expect("static values are valid; qed") - .public() -} - -type AccountPublic = ::Signer; - -/// Generate collator keys from seed. -/// -/// This function's return type must always match the session keys of the chain -/// in tuple format. -pub fn get_collator_keys_from_seed(seed: &str) -> AuraId { - get_from_seed::(seed) -} - -/// Helper function to generate an account ID from seed -pub fn get_account_id_from_seed(seed: &str) -> AccountId -where - AccountPublic: From<::Public>, -{ - AccountPublic::from(get_from_seed::(seed)).into_account() -} diff --git a/chain-spec-generator/src/main.rs b/chain-spec-generator/src/main.rs index 3a4a2667..338caeaf 100644 --- a/chain-spec-generator/src/main.rs +++ b/chain-spec-generator/src/main.rs @@ -2,7 +2,6 @@ use clap::Parser; use sc_chain_spec::ChainSpec; use std::collections::HashMap; -mod common; mod spec; use spec::live; diff --git a/chain-spec-generator/src/spec/local.rs b/chain-spec-generator/src/spec/local.rs index b5bbe026..fd40ee60 100644 --- a/chain-spec-generator/src/spec/local.rs +++ b/chain-spec-generator/src/spec/local.rs @@ -1,158 +1,60 @@ use super::*; #[cfg(not(feature = "paseo"))] -pub fn chain_spec() -> Result, String> { +const RELAY_CHAIN_STRING: &str = "kusama-local"; + +#[cfg(not(feature = "paseo"))] +const CHAIN_ID_STRING: &str = "kreivo_kusama_local"; +#[cfg(not(feature = "paseo"))] +const CHAIN_NAME_STRING: &str = "Kreivo-Kusama Local"; + +#[cfg(not(feature = "paseo"))] +pub fn properties() -> sc_chain_spec::Properties { // Give your base currency a unit name and decimal places let mut properties = sc_chain_spec::Properties::new(); + properties.insert("tokenSymbol".into(), "KSM".into()); properties.insert("tokenDecimals".into(), 12.into()); properties.insert("ss58Format".into(), 2.into()); - Ok(Box::new( - KreivoChainSpec::builder( - kreivo_runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"), - Extensions { - relay_chain: "kusama-local".into(), - // You MUST set this to the correct network! - para_id: KREIVO_PARA_ID, - }, - ) - .with_name("Kreivo-Kusama Local") - .with_id("kreivo_kusama_local") - .with_chain_type(ChainType::Local) - .with_properties(properties) - .with_genesis_config_patch(local_genesis( - KREIVO_PARA_ID.into(), - // initial collators. - vec![ - ( - get_account_id_from_seed::("Alice"), - get_collator_keys_from_seed("Alice"), - ), - ( - get_account_id_from_seed::("Bob"), - get_collator_keys_from_seed("Bob"), - ), - ], - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Ferdie"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - get_account_id_from_seed::("Charlie//stash"), - get_account_id_from_seed::("Dave//stash"), - get_account_id_from_seed::("Eve//stash"), - get_account_id_from_seed::("Ferdie//stash"), - ], - )) - .build(), - )) + properties } #[cfg(feature = "paseo")] -pub fn chain_spec() -> Result, String> { +const RELAY_CHAIN_STRING: &str = "paseo-local"; + +#[cfg(feature = "paseo")] +const CHAIN_ID_STRING: &str = "kreivo_paseo_local"; +#[cfg(feature = "paseo")] +const CHAIN_NAME_STRING: &str = "Kreivo de Paseo-Local"; + +#[cfg(feature = "paseo")] +pub fn properties() -> sc_chain_spec::Properties { // Give your base currency a unit name and decimal places let mut properties = sc_chain_spec::Properties::new(); + properties.insert("tokenSymbol".into(), "PAS".into()); properties.insert("tokenDecimals".into(), 10.into()); properties.insert("ss58Format".into(), 1.into()); + properties +} + +pub fn chain_spec() -> Result, String> { Ok(Box::new( KreivoChainSpec::builder( kreivo_runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"), Extensions { - relay_chain: "paseo-local".into(), + relay_chain: RELAY_CHAIN_STRING.into(), // You MUST set this to the correct network! para_id: KREIVO_PARA_ID, }, ) - .with_name("Kreivo de Paseo-Local") - .with_id("kreivo_paseo_local") + .with_id(CHAIN_ID_STRING) + .with_name(CHAIN_NAME_STRING) .with_chain_type(ChainType::Local) - .with_properties(properties) - .with_genesis_config_patch(local_genesis( - KREIVO_PARA_ID.into(), - // initial collators. - vec![ - ( - get_account_id_from_seed::("Alice"), - get_collator_keys_from_seed("Alice"), - ), - ( - get_account_id_from_seed::("Bob"), - get_collator_keys_from_seed("Bob"), - ), - ], - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Ferdie"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - get_account_id_from_seed::("Charlie//stash"), - get_account_id_from_seed::("Dave//stash"), - get_account_id_from_seed::("Eve//stash"), - get_account_id_from_seed::("Ferdie//stash"), - ], - )) + .with_properties(properties()) + .with_genesis_config_preset_name("local") .build(), )) } - -fn local_genesis( - id: ParaId, - invulnerables: Vec<(AccountId, AuraId)>, - endowed_accounts: Vec, -) -> serde_json::Value { - let mut config = serde_json::json!({}).as_object().expect("map given; qed").clone(); - - config.insert( - "balances".into(), - serde_json::json!({ - "balances": endowed_accounts.iter().cloned().map(|k| (k, 1u64 << 60)).collect::>() - }), - ); - config.insert( - "parachainInfo".into(), - serde_json::json!({ - "parachainId": id, - }), - ); - config.insert( - "collatorSelection".into(), - serde_json::json!({ - "invulnerables": invulnerables.iter().cloned().map(|(acc, _)| acc).collect::>(), - "candidacyBond": EXISTENTIAL_DEPOSIT * 16, - }), - ); - config.insert( - "session".into(), - serde_json::json!({ - "keys": invulnerables - .into_iter() - .map(|(acc, aura)| { - ( - acc.clone(), // account id - acc, // validator id - session_keys(aura), // session keys - ) - }) - .collect::>(), - }), - ); - config.insert( - "polkadotXcm".into(), - serde_json::json!({ - "safeXcmVersion": Some(SAFE_XCM_VERSION), - }), - ); - - config.into() -} diff --git a/chain-spec-generator/src/spec/mod.rs b/chain-spec-generator/src/spec/mod.rs index 9cef7635..7b475f49 100644 --- a/chain-spec-generator/src/spec/mod.rs +++ b/chain-spec-generator/src/spec/mod.rs @@ -1,25 +1,24 @@ -use crate::common::{get_account_id_from_seed, get_collator_keys_from_seed, Extensions, SAFE_XCM_VERSION}; -use cumulus_primitives_core::ParaId; - -use kreivo_runtime::{constants::currency::EXISTENTIAL_DEPOSIT, AccountId, AuraId, SessionKeys}; -use sc_chain_spec::{ChainSpec, ChainType}; -use sp_core::sr25519; +use sc_chain_spec::{ChainSpec, ChainSpecExtension, ChainSpecGroup, ChainType}; +use serde::{Deserialize, Serialize}; #[cfg(feature = "paseo")] const KREIVO_PARA_ID: u32 = 2281; #[cfg(not(feature = "paseo"))] const KREIVO_PARA_ID: u32 = 2281; +/// The extensions for the [`ChainSpec`]. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)] +pub struct Extensions { + /// The relay chain of the Parachain. + #[serde(alias = "relayChain", alias = "RelayChain")] + pub relay_chain: String, + /// The id of the Parachain. + #[serde(alias = "paraId", alias = "ParaId")] + pub para_id: u32, +} + /// Specialized `ChainSpec` for the normal parachain runtime. pub type KreivoChainSpec = sc_chain_spec::GenericChainSpec; -/// Generate the session keys from individual elements. -/// -/// The input must be a tuple of individual keys (a single arg for now since we -/// have just one key). -fn session_keys(aura: AuraId) -> SessionKeys { - SessionKeys { aura } -} - pub mod live; pub mod local; diff --git a/justfile b/justfile index 6e5f6309..7e7cd05c 100644 --- a/justfile +++ b/justfile @@ -4,11 +4,14 @@ set shell := ["nu", "-c"] podman := `(which podman) ++ (which docker) | (first).path` # use podman otherwise docker ver := `open chain-spec-generator/Cargo.toml | get package.version` image := "ghcr.io/virto-network/virto" -node := "target/release/virto-node" + chain := "kreivo" +runtime := "target/release/wbuild/kreivo-runtime/kreivo_runtime.compact.compressed.wasm" rol := "collator" relay := "kusama" + + alias b := build-local alias c := check alias t := test @@ -47,58 +50,26 @@ benchmarks: # TODO: build benchmarks for every pallet that's currently within the runtime as # a dependency mkdir .benchmarking-logs - chmod +x {{node}} - ls "pallets" \ - | each {|path| open ($path.name + /Cargo.toml) | get package.name} \ - | filter {|pallet| cat runtime/kreivo/Cargo.toml | str contains $pallet} \ - | filter {|pallet| cat runtime/kreivo/Cargo.toml | str contains ([$pallet, "runtime-benchmarks"] | str join '/')} \ - | each {|pallet| str replace --all '-' '_' } \ - | each {|pallet| just benchmark $pallet} + frame-omni-bencher v1 benchmark pallet --list=pallets --runtime {{runtime}} \ + | from csv \ + | each {|record| just benchmark $record.pallet} benchmark pallet="" extrinsic="*": - touch .benchmarking-logs/{{pallet}}.txt - ./target/release/virto-node benchmark pallet \ - --chain {{chain}}-local \ - --pallet '{{pallet}}' --extrinsic '{{extrinsic}}' \ - --steps 50 \ - --repeat 20 \ - --output runtime/kreivo/src/weights/{{pallet}}.rs | save -a --force .benchmarking-logs/{{pallet}}.txt - -build-container: - #!/usr/bin/env nu - 'FROM docker.io/paritytech/ci-unified:latest as builder - WORKDIR /virto - COPY . /virto - RUN cargo build --release - - FROM debian:bullseye-slim - VOLUME /data - COPY --from=builder /virto/{{ node }} /usr/bin - ENTRYPOINT ["/usr/bin/virto-node"] - CMD ["--dev"]' - | {{ podman }} build . -t {{ image }}:{{ ver }} --ignorefile .build-container-ignore -f - - -# Used to speed things up when the build environment is the same as the container(debian) -build-container-local: build-local - #!/usr/bin/env nu - 'FROM debian:bookworm-slim - LABEL io.containers.autoupdate="registry" - VOLUME /data - COPY {{ node }} /usr/bin - ENTRYPOINT ["/usr/bin/virto-node"] - CMD ["--dev"]' - | {{ podman }} build . -t {{ image }}:{{ ver }} -t {{ image }}:latest -f - - -_parachain_launch_artifacts: - @mkdir release - {{ node }} export-genesis-state --chain {{ chain }} | save -f release/{{ chain }}_genesis - {{ node }} export-genesis-wasm --chain {{ chain }} | save -f release/{{ chain }}_genesis.wasm - {{ node }} build-spec --disable-default-bootnode --chain {{ chain }} | save -f release/{{ chain }}_chainspec.json + frame-omni-bencher v1 benchmark pallet \ + --runtime {{runtime}} \ + --pallet '{{pallet}}' --extrinsic '{{extrinsic}}' \ + --steps 50 \ + --repeat 20 \ + --output ./runtime/kreivo/src/weights/ | \ + save --force .benchmarking-logs/{{pallet}}.out.txt \ + --stderr .benchmarking-logs/{{pallet}}.log.txt + + if ((open .benchmarking-logs/{{pallet}}.out.txt | str length) == 0) { rm .benchmarking-logs/{{pallet}}.out.txt } release-artifacts: @mkdir release; rm -f release/* - cp target/release/wbuild/{{ chain }}-runtime/{{ chain }}_runtime.compact.compressed.wasm release/ + cp {{ runtime }} release/ cp *.container release release-tag: diff --git a/pallets/communities/src/benchmarking.rs b/pallets/communities/src/benchmarking.rs index d457bca3..3bdff2b0 100644 --- a/pallets/communities/src/benchmarking.rs +++ b/pallets/communities/src/benchmarking.rs @@ -1,5 +1,4 @@ //! Benchmarking setup for pallet-communities -#![cfg(feature = "runtime-benchmarks")] use super::*; use self::{ @@ -87,15 +86,14 @@ where Ok((community_id, admin_origin)) } +type Member = (AccountIdOf, MembershipIdOf); + /// Initializes the memberships of a community built for benchmarking /// purposes. /// /// Then, returns a list of tuples, each one containing a member's /// [AccountId] and their corresponding -fn setup_members( - origin: OriginFor, - community_id: CommunityIdOf, -) -> Result, MembershipIdOf)>, BenchmarkError> +fn setup_members(origin: OriginFor, community_id: CommunityIdOf) -> Result>, BenchmarkError> where T: Config, T::MembershipId: From, @@ -135,7 +133,6 @@ where #[benchmarks( where - T: frame_system::Config + crate::Config, OriginFor: From> + From>, RuntimeEventFor: From>, AssetBalanceOf: From, diff --git a/pallets/payments/src/benchmarking.rs b/pallets/payments/src/benchmarking.rs index 4873e0f6..8a5313e0 100644 --- a/pallets/payments/src/benchmarking.rs +++ b/pallets/payments/src/benchmarking.rs @@ -93,11 +93,11 @@ mod benchmarks { fn pay(q: Linear<1, { T::MaxRemarkLength::get() }>) -> Result<(), BenchmarkError> { let (sender, beneficiary, _, beneficiary_lookup) = create_accounts::(); - let asset: AssetIdOf = >::default(); - create_and_mint_asset::(&sender, &beneficiary, &asset)?; - let amount = >::from(100000_u32); + let asset_id: AssetIdOf = >::default(); + create_and_mint_asset::(&sender, &beneficiary, &asset_id)?; + let payment_amount = >::from(100000_u32); - let remark: Option> = if q == 0 { + let order_remark: Option> = if q == 0 { None } else { Some(BoundedVec::try_from(vec![1 as u8; q as usize]).unwrap()) @@ -107,14 +107,14 @@ mod benchmarks { _( RawOrigin::Signed(sender.clone()), beneficiary_lookup, - asset.clone(), - amount, - remark.clone(), + asset_id.clone(), + payment_amount, + order_remark.clone(), ); assert_has_event!( Event::PaymentCreated { asset, amount, remark, .. } - if asset == asset && amount == amount && remark == remark + if asset == asset_id && amount == payment_amount && remark == order_remark ); Ok(()) } diff --git a/runtime/kreivo/Cargo.toml b/runtime/kreivo/Cargo.toml index bbcd0a09..461d59b8 100644 --- a/runtime/kreivo/Cargo.toml +++ b/runtime/kreivo/Cargo.toml @@ -19,6 +19,7 @@ hex-literal = { workspace = true, optional = true } log.workspace = true parity-scale-codec = { workspace = true, features = ["derive"] } scale-info = { workspace = true, features = ["derive"] } +serde_json = { workspace = true, features = ["alloc"] } smallvec.workspace = true # Local diff --git a/runtime/kreivo/src/apis.rs b/runtime/kreivo/src/apis.rs index 0b7f9d81..302a44f4 100644 --- a/runtime/kreivo/src/apis.rs +++ b/runtime/kreivo/src/apis.rs @@ -212,176 +212,13 @@ impl_runtime_apis! { Vec, Vec, ) { - use frame_benchmarking::{Benchmarking, BenchmarkList}; - use frame_support::traits::StorageInfoTrait; - use frame_system_benchmarking::Pallet as SystemBench; - use cumulus_pallet_session_benchmarking::Pallet as SessionBench; - - // This is defined once again in dispatch_benchmark, because list_benchmarks! - // and add_benchmarks! are macros exported by define_benchmarks! macros and those types - // are referenced in that call. - type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::; - type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::; - - let mut list = Vec::::new(); - list_benchmarks!(list, extra); - - let storage_info = AllPalletsWithSystem::storage_info(); - (list, storage_info) + benchmarking::benchmark_metadata(extra) } fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig ) -> Result, sp_runtime::RuntimeString> { - use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; - - use frame_system_benchmarking::Pallet as SystemBench; - impl frame_system_benchmarking::Config for Runtime {} - - use cumulus_pallet_session_benchmarking::Pallet as SessionBench; - impl cumulus_pallet_session_benchmarking::Config for Runtime {} - - use xcm::latest::prelude::{ - Asset, Assets as XcmAssets, AssetId, Fungible, GeneralIndex, - Here, InteriorLocation, Junction, Location, NetworkId, - NonFungible, Response - }; - use xcm_config::RelayLocation; - use pallet_xcm_benchmarks::asset_instance_from; - - parameter_types! { - pub ExistentialDepositAsset: Option = Some(( - RelayLocation::get(), - ExistentialDeposit::get() - ).into()); - } - - impl pallet_xcm_benchmarks::Config for Runtime { - type XcmConfig = xcm_config::XcmConfig; - type AccountIdConverter = xcm_config::LocationToAccountId; - type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< - xcm_config::XcmConfig, - ExistentialDepositAsset, - PriceForParentDelivery, - >; - - fn valid_destination() -> Result { - Ok(RelayLocation::get()) - } - fn worst_case_holding(depositable_count: u32) -> XcmAssets { - // A mix of fungible, non-fungible, and concrete assets. - let holding_non_fungibles = xcm_config::MaxAssetsIntoHolding::get() / 2 - depositable_count; - let holding_fungibles = holding_non_fungibles.saturating_sub(1); - let fungibles_amount: u128 = 100; - let mut assets = (0..holding_fungibles) - .map(|i| { - Asset { - id: AssetId(GeneralIndex(i as u128).into()), - fun: Fungible(fungibles_amount * i as u128), - } - }) - .chain(core::iter::once(Asset { id: AssetId(Here.into()), fun: Fungible(u128::MAX) })) - .chain((0..holding_non_fungibles).map(|i| Asset { - id: AssetId(GeneralIndex(i as u128).into()), - fun: NonFungible(asset_instance_from(i)), - })) - .collect::>(); - - assets.push(Asset{ - id: AssetId(RelayLocation::get()), - fun: Fungible(1_000_000 * UNITS), - }); - assets.into() - } - } - - parameter_types! { - pub const TrustedTeleporter: Option<(Location, Asset)> = Some(( - RelayLocation::get(), - Asset { fun: Fungible(1 * UNITS), id: AssetId(RelayLocation::get()) }, - )); - pub const TrustedReserve: Option<(Location, Asset)> = None; - pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None; - - } - - impl pallet_xcm_benchmarks::fungible::Config for Runtime { - type TransactAsset = Balances; - - type CheckedAccount = CheckedAccount; - type TrustedTeleporter = TrustedTeleporter; - type TrustedReserve = TrustedReserve; - - fn get_asset() -> Asset { - Asset { - id: AssetId(RelayLocation::get()), - fun: Fungible(1 * UNITS), - }.into() - } - } - - impl pallet_xcm_benchmarks::generic::Config for Runtime { - type RuntimeCall = RuntimeCall; - type TransactAsset = Balances; - - fn worst_case_response() -> (u64, Response) { - (0u64, Response::Version(Default::default())) - } - - fn worst_case_asset_exchange() -> Result<(XcmAssets, XcmAssets), BenchmarkError> { - Err(BenchmarkError::Skip) - } - - fn universal_alias() -> Result<(Location, Junction), BenchmarkError> { - Err(BenchmarkError::Skip) - } - - fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> { - Ok((RelayLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) - } - - fn subscribe_origin() -> Result { - Ok(RelayLocation::get()) - } - - fn claimable_asset() -> Result<(Location, Location, XcmAssets), BenchmarkError> { - let origin = RelayLocation::get(); - let assets: XcmAssets = (AssetId(RelayLocation::get()), 1_000 * UNITS).into(); - let ticket = Location { parents: 0, interior: Here }; - Ok((origin, ticket, assets)) - } - - fn fee_asset() -> Result { - Ok(Asset { - id: AssetId(RelayLocation::get()), - fun: Fungible(1_000_000 * UNITS), - }) - } - - fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> { - Err(BenchmarkError::Skip) - } - - fn export_message_origin_and_destination( - ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> { - Err(BenchmarkError::Skip) - } - - fn alias_origin() -> Result<(Location, Location), BenchmarkError> { - Err(BenchmarkError::Skip) - } - } - - type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::; - type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::; - - use frame_support::traits::WhitelistedStorageKeys; - let whitelist = AllPalletsWithSystem::whitelisted_storage_keys(); - - let mut batches = Vec::::new(); - let params = (&config, &whitelist); - add_benchmarks!(params, batches); - Ok(batches) + benchmarking::dispatch_benchmark(config) } } @@ -391,11 +228,11 @@ impl_runtime_apis! { } fn get_preset(id: &Option) -> Option> { - get_preset::(id, |_| None) + get_preset::(id, &genesis_config_presets::get_preset) } fn preset_names() -> Vec { - vec![] + genesis_config_presets::preset_names() } } } diff --git a/runtime/kreivo/src/benchmarking/impls.rs b/runtime/kreivo/src/benchmarking/impls.rs new file mode 100644 index 00000000..ee44858b --- /dev/null +++ b/runtime/kreivo/src/benchmarking/impls.rs @@ -0,0 +1,148 @@ +use super::*; + +pub(super) use cumulus_pallet_session_benchmarking::Pallet as SessionBench; +pub(super) use frame_system_benchmarking::Pallet as SystemBench; + +use super::{xcm_config, Balances, PriceForParentDelivery, Runtime, UNITS}; +use crate::RuntimeCall; +use frame_benchmarking::BenchmarkError; +use frame_support::parameter_types; +use pallet_xcm_benchmarks::asset_instance_from; +use xcm::latest::prelude::{ + Asset, AssetId, Assets as XcmAssets, Fungible, GeneralIndex, Here, InteriorLocation, Junction, Location, NetworkId, + NonFungible, Response, +}; +use xcm_config::RelayLocation; + +impl frame_system_benchmarking::Config for Runtime {} + +impl cumulus_pallet_session_benchmarking::Config for Runtime {} + +parameter_types! { + pub ExistentialDepositAsset: Option = Some(( + RelayLocation::get(), + ExistentialDeposit::get() + ).into()); +} + +impl pallet_xcm_benchmarks::Config for Runtime { + type XcmConfig = xcm_config::XcmConfig; + type AccountIdConverter = xcm_config::LocationToAccountId; + type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< + xcm_config::XcmConfig, + ExistentialDepositAsset, + PriceForParentDelivery, + >; + + fn valid_destination() -> Result { + Ok(RelayLocation::get()) + } + fn worst_case_holding(depositable_count: u32) -> XcmAssets { + // A mix of fungible, non-fungible, and concrete assets. + let holding_non_fungibles = xcm_config::MaxAssetsIntoHolding::get() / 2 - depositable_count; + let holding_fungibles = holding_non_fungibles.saturating_sub(1); + let fungibles_amount: u128 = 100; + let mut assets = (0..holding_fungibles) + .map(|i| Asset { + id: AssetId(GeneralIndex(i as u128).into()), + fun: Fungible(fungibles_amount * i as u128), + }) + .chain(core::iter::once(Asset { + id: AssetId(Here.into()), + fun: Fungible(u128::MAX), + })) + .chain((0..holding_non_fungibles).map(|i| Asset { + id: AssetId(GeneralIndex(i as u128).into()), + fun: NonFungible(asset_instance_from(i)), + })) + .collect::>(); + + assets.push(Asset { + id: AssetId(RelayLocation::get()), + fun: Fungible(1_000_000 * UNITS), + }); + assets.into() + } +} + +parameter_types! { + pub const TrustedTeleporter: Option<(Location, Asset)> = Some(( + RelayLocation::get(), + Asset { fun: Fungible(1 * UNITS), id: AssetId(RelayLocation::get()) }, + )); + pub const TrustedReserve: Option<(Location, Asset)> = None; + pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None; + +} + +impl pallet_xcm_benchmarks::fungible::Config for Runtime { + type TransactAsset = Balances; + type CheckedAccount = CheckedAccount; + type TrustedTeleporter = TrustedTeleporter; + type TrustedReserve = TrustedReserve; + + fn get_asset() -> Asset { + Asset { + id: AssetId(RelayLocation::get()), + fun: Fungible(1 * UNITS), + } + .into() + } +} + +impl pallet_xcm_benchmarks::generic::Config for Runtime { + type RuntimeCall = RuntimeCall; + type TransactAsset = Balances; + + fn worst_case_response() -> (u64, Response) { + (0u64, Response::Version(Default::default())) + } + + fn worst_case_asset_exchange() -> Result<(XcmAssets, XcmAssets), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn universal_alias() -> Result<(Location, Junction), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> { + Ok(( + RelayLocation::get(), + frame_system::Call::remark_with_event { remark: vec![] }.into(), + )) + } + + fn subscribe_origin() -> Result { + Ok(RelayLocation::get()) + } + + fn claimable_asset() -> Result<(Location, Location, XcmAssets), BenchmarkError> { + let origin = RelayLocation::get(); + let assets: XcmAssets = (AssetId(RelayLocation::get()), 1_000 * UNITS).into(); + let ticket = Location { + parents: 0, + interior: Here, + }; + Ok((origin, ticket, assets)) + } + + fn fee_asset() -> Result { + Ok(Asset { + id: AssetId(RelayLocation::get()), + fun: Fungible(1_000_000 * UNITS), + }) + } + + fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn export_message_origin_and_destination() -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn alias_origin() -> Result<(Location, Location), BenchmarkError> { + Err(BenchmarkError::Skip) + } +} diff --git a/runtime/kreivo/src/benchmarking/mod.rs b/runtime/kreivo/src/benchmarking/mod.rs new file mode 100644 index 00000000..833a9cd9 --- /dev/null +++ b/runtime/kreivo/src/benchmarking/mod.rs @@ -0,0 +1,81 @@ +mod impls; + +use super::*; +use frame_benchmarking::{BenchmarkBatch, BenchmarkConfig, BenchmarkList, Benchmarking}; +use frame_support::traits::{StorageInfo, StorageInfoTrait}; +use impls::{SessionBench, SystemBench}; + +use sp_runtime::RuntimeString; + +type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet; +type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet; + +frame_benchmarking::define_benchmarks!( + // System support + [frame_system, SystemBench::] + [cumulus_pallet_parachain_system, ParachainSystem] + [pallet_timestamp, Timestamp] + [pallet_pass, Pass] + + // Monetary stuff + [pallet_balances, Balances] + [pallet_assets, Assets] + [pallet_vesting, Vesting] + + // Collator support + [pallet_collator_selection, CollatorSelection] + [pallet_session, SessionBench::] + + // XCM + [cumulus_pallet_xcmp_queue, XcmpQueue] + // NOTE: Make sure you point to the individual modules below. + [pallet_xcm_benchmarks::fungible, XcmBalances] + [pallet_xcm_benchmarks::generic, XcmGeneric] + + // Utils + [pallet_multisig, Multisig] + [pallet_utility, Utility] + [pallet_proxy, Proxy] + [pallet_scheduler, Scheduler] + [pallet_preimage, Preimage] + + // Governance + [pallet_treasury, Treasury] + [pallet_ranked_collective, KreivoCollective] + [pallet_referenda, KreivoReferenda] + + // Virto Tooling + [pallet_payments, Payments] + + // Communities at Kreivo + [pallet_communities, Communities] + [pallet_referenda_tracks, CommunityTracks] + // [pallet_referenda, CommunityReferenda] + [pallet_nfts, CommunityMemberships] + [pallet_communities_manager, CommunitiesManager] + + // Contracts + [pallet_contracts, Contracts] +); + +pub(crate) fn benchmark_metadata(extra: bool) -> (Vec, Vec) { + // This is defined once again in dispatch_benchmark, because list_benchmarks! + // and add_benchmarks! are macros exported by define_benchmarks! macros and + // those types are referenced in that call. + let mut list = Vec::::new(); + list_benchmarks!(list, extra); + + let storage_info = AllPalletsWithSystem::storage_info(); + (list, storage_info) +} + +pub(crate) fn dispatch_benchmark(config: BenchmarkConfig) -> Result, RuntimeString> { + use frame_support::traits::WhitelistedStorageKeys; + let whitelist = AllPalletsWithSystem::whitelisted_storage_keys(); + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + add_benchmarks!(params, batches); + + Ok(batches) +} diff --git a/runtime/kreivo/src/configuration/monetary_stuff.rs b/runtime/kreivo/src/configuration/monetary_stuff.rs index 4ae439bd..38275264 100644 --- a/runtime/kreivo/src/configuration/monetary_stuff.rs +++ b/runtime/kreivo/src/configuration/monetary_stuff.rs @@ -1,13 +1,18 @@ use super::*; use fc_traits_gas_tank::{NonFungibleGasTank, SelectNonFungibleItem}; - use pallet_asset_tx_payment::FungiblesAdapter; use pallet_assets::BalanceToAssetBalance; use pallet_transaction_payment::FungibleAdapter; use runtime_common::impls::AssetsToBlockAuthor; use virto_common::MembershipId; +#[cfg(not(feature = "runtime-benchmarks"))] +use frame_support::traits::{AsEnsureOriginWithArg, NeverEnsureOrigin}; + +#[cfg(feature = "runtime-benchmarks")] +use frame_system::EnsureSigned; + // #[runtime::pallet_index(10)] // pub type Balances parameter_types! { @@ -80,7 +85,10 @@ impl pallet_assets::Config for Runtime { type AssetIdParameter = FungibleAssetLocation; type Currency = Balances; /// Only root can create assets and force state changes. + #[cfg(not(feature = "runtime-benchmarks"))] type CreateOrigin = AsEnsureOriginWithArg>; + #[cfg(feature = "runtime-benchmarks")] + type CreateOrigin = EnsureSigned; type ForceOrigin = AssetsForceOrigin; type AssetDeposit = AssetDeposit; type MetadataDepositBase = MetadataDepositBase; diff --git a/runtime/kreivo/src/genesis_config_presets.rs b/runtime/kreivo/src/genesis_config_presets.rs new file mode 100644 index 00000000..1f2d18be --- /dev/null +++ b/runtime/kreivo/src/genesis_config_presets.rs @@ -0,0 +1,67 @@ +use crate::*; +use runtime_constants::genesis_presets::*; +use sp_genesis_builder::PresetId; +use sp_std::vec::Vec; + +fn local_genesis( + id: ParaId, + invulnerables: Vec<(AccountId, AuraId)>, + endowed_accounts: Vec, +) -> serde_json::Value { + serde_json::json!({ + "balances": BalancesConfig { + balances: endowed_accounts + .iter() + .cloned() + .map(|k| (k, EXISTENTIAL_DEPOSIT * 4096 * 4096)) + .collect(), + }, + "parachainInfo": ParachainInfoConfig { + parachain_id: id, + ..Default::default() + }, + "collatorSelection": CollatorSelectionConfig { + invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), + candidacy_bond: EXISTENTIAL_DEPOSIT * 16, + ..Default::default() + }, + "session": SessionConfig { + keys: invulnerables + .into_iter() + .map(|(acc, aura)| { + ( + acc.clone(), // account id + acc, // validator id + SessionKeys { aura }, // session keys + ) + }) + .collect(), + ..Default::default() + }, + "polkadotXcm": { + "safeXcmVersion": Some(SAFE_XCM_VERSION), + }, + }) +} + +pub fn local_testnet_genesis(para_id: ParaId) -> serde_json::Value { + local_genesis(para_id, invulnerables(), testnet_accounts()) +} + +pub fn preset_names() -> Vec { + vec![PresetId::from("development"), PresetId::from("local")] +} + +pub fn get_preset(id: &PresetId) -> Option> { + let patch = match id.try_into() { + Ok("development") => local_testnet_genesis(2281.into()), + Ok("local") => local_testnet_genesis(2281.into()), + _ => return None, + }; + + Some( + serde_json::to_string(&patch) + .expect("serialization to json is expected to work; qed") + .into_bytes(), + ) +} diff --git a/runtime/kreivo/src/lib.rs b/runtime/kreivo/src/lib.rs index 68b59fce..5d3fff5c 100644 --- a/runtime/kreivo/src/lib.rs +++ b/runtime/kreivo/src/lib.rs @@ -10,10 +10,14 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); #[cfg(test)] mod tests; +#[cfg(feature = "runtime-benchmarks")] +mod benchmarking; + pub mod apis; pub mod configuration; pub mod constants; pub mod contracts; +mod genesis_config_presets; pub mod governance; pub mod impls; mod weights; @@ -54,8 +58,8 @@ use frame_support::{ fungible::HoldConsideration, fungibles, tokens::{imbalance::ResolveTo, PayFromAccount, UnityAssetBalanceConversion}, - AsEnsureOriginWithArg, ConstBool, ConstU32, ConstU64, ConstU8, Contains, EitherOf, EitherOfDiverse, - EnsureOriginWithArg, LinearStoragePrice, NeverEnsureOrigin, TransformOrigin, WithdrawReasons, + ConstBool, ConstU32, ConstU64, ConstU8, Contains, EitherOf, EitherOfDiverse, EnsureOriginWithArg, + LinearStoragePrice, TransformOrigin, WithdrawReasons, }, weights::{constants::RocksDbWeight, ConstantMultiplier, Weight}, BoundedVec, PalletId, @@ -603,37 +607,6 @@ pub type PriceForParentDelivery = polkadot_runtime_common::xcm_sender::Exponenti ParachainSystem, >; -#[cfg(feature = "runtime-benchmarks")] -mod benches { - frame_benchmarking::define_benchmarks!( - [frame_system, SystemBench::] - [pallet_balances, Balances] - [pallet_session, SessionBench::] - [pallet_timestamp, Timestamp] - [pallet_collator_selection, CollatorSelection] - [cumulus_pallet_xcmp_queue, XcmpQueue] - [pallet_treasury, Treasury] - [pallet_multisig, Multisig] - [pallet_vesting, Vesting] - [pallet_utility, Utility] - [pallet_assets, Assets] - [pallet_proxy, Proxy] - [pallet_referenda, KreivoReferenda] - [pallet_ranked_collective, KreivoCollective] - [pallet_payments, Payments] - [pallet_communities, Communities] - [pallet_referenda_tracks, CommunityTracks] - [pallet_referenda, CommunityReferenda] - [pallet_communities_manager, CommunitiesManager] - [pallet_nfts, CommunityMemberships] - [pallet_contracts, Contracts] - // XCM - // NOTE: Make sure you point to the individual modules below. - [pallet_xcm_benchmarks::fungible, XcmBalances] - [pallet_xcm_benchmarks::generic, XcmGeneric] - ); -} - cumulus_pallet_parachain_system::register_validate_block! { Runtime = Runtime, BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, diff --git a/runtime/runtime-constants/Cargo.toml b/runtime/runtime-constants/Cargo.toml index c8e37392..85c9f2fc 100644 --- a/runtime/runtime-constants/Cargo.toml +++ b/runtime/runtime-constants/Cargo.toml @@ -10,11 +10,14 @@ version = "1.0.0" [dependencies] smallvec = "1.8.0" frame-support.workspace = true +parachains-common.workspace = true polkadot-primitives.workspace = true polkadot-runtime-common.workspace = true sp-runtime.workspace = true sp-weights.workspace = true sp-core.workspace = true +sp-std.workspace = true +xcm.workspace = true xcm-builder.workspace = true [features] diff --git a/runtime/runtime-constants/src/genesis_presets.rs b/runtime/runtime-constants/src/genesis_presets.rs new file mode 100644 index 00000000..644716d6 --- /dev/null +++ b/runtime/runtime-constants/src/genesis_presets.rs @@ -0,0 +1,74 @@ +// Copyright (C) Parity Technologies and the various Polkadot contributors, see +// Contributions.md for a list of specific contributors. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +use parachains_common::AuraId; +use polkadot_primitives::{AccountId, AccountPublic}; +use sp_core::{sr25519, Pair, Public}; +use sp_runtime::traits::IdentifyAccount; +#[cfg(not(feature = "std"))] +use sp_std::alloc::format; +use sp_std::vec::Vec; + +/// Invulnerable Collators +pub fn invulnerables() -> Vec<(parachains_common::AccountId, AuraId)> { + Vec::from([ + ( + get_account_id_from_seed::("Alice"), + get_from_seed::("Alice"), + ), + ( + get_account_id_from_seed::("Bob"), + get_from_seed::("Bob"), + ), + ]) +} + +/// Test accounts +pub fn testnet_accounts() -> Vec { + Vec::from([ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Charlie"), + get_account_id_from_seed::("Dave"), + get_account_id_from_seed::("Eve"), + get_account_id_from_seed::("Ferdie"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + get_account_id_from_seed::("Charlie//stash"), + get_account_id_from_seed::("Dave//stash"), + get_account_id_from_seed::("Eve//stash"), + get_account_id_from_seed::("Ferdie//stash"), + ]) +} + +/// Helper function to generate a crypto pair from seed +pub fn get_from_seed(seed: &str) -> ::Public { + TPublic::Pair::from_string(&format!("//{}", seed), None) + .expect("static values are valid; qed") + .public() +} + +/// Helper function to generate an account ID from seed +pub fn get_account_id_from_seed(seed: &str) -> AccountId +where + AccountPublic: From<::Public>, +{ + AccountPublic::from(get_from_seed::(seed)).into_account() +} + +/// The default XCM version to set in genesis config. +pub const SAFE_XCM_VERSION: u32 = xcm::prelude::XCM_VERSION; diff --git a/runtime/runtime-constants/src/lib.rs b/runtime/runtime-constants/src/lib.rs index 7ab9a507..0d1d7354 100644 --- a/runtime/runtime-constants/src/lib.rs +++ b/runtime/runtime-constants/src/lib.rs @@ -16,6 +16,7 @@ #![cfg_attr(not(feature = "std"), no_std)] +pub mod genesis_presets; pub mod weights; /// Money matters. diff --git a/zombienet/kreivo-kusama-local.toml b/zombienet/kreivo-kusama-local.toml index 32353f3c..1b38b25a 100644 --- a/zombienet/kreivo-kusama-local.toml +++ b/zombienet/kreivo-kusama-local.toml @@ -48,8 +48,6 @@ name = "kreivo1" ws_port = 20000 [[parachains.collators]] -chain = "dev" -chain_spec_command = "./target/release/chain-spec-generator {% raw %} {{chainName}} {% endraw %}" command = "./bin/polkadot-parachain" args = ["--force-authoring --log=xcm=trace,parachain=trace"] name = "kreivo2" diff --git a/zombienet/kreivo-paseo-local.toml b/zombienet/kreivo-paseo-local.toml index da44d0bd..0b313587 100644 --- a/zombienet/kreivo-paseo-local.toml +++ b/zombienet/kreivo-paseo-local.toml @@ -48,8 +48,6 @@ name = "kreivo1" ws_port = 20000 [[parachains.collators]] -chain = "dev" -chain_spec_command = "./target/release/chain-spec-generator {% raw %} {{chainName}} {% endraw %}" command = "./bin/polkadot-parachain" args = ["--force-authoring --log=xcm=trace,parachain=trace"] name = "kreivo2"