From b8d485fd4942539c438bf25a7823e410360fa053 Mon Sep 17 00:00:00 2001 From: Egor_P Date: Tue, 18 Jul 2023 14:29:38 +0200 Subject: [PATCH] Ep backport missing cumulus companions (#14594) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Removal of execution strategies (#14387) * Start * More work! * Moar * More changes * More fixes * More worrk * More fixes * More fixes to make it compile * Adds `NoOffchainStorage` * Pass the extensions * Small basti making small progress * Fix merge errors and remove `ExecutionContext` * Move registration of `ReadRuntimeVersionExt` to `ExecutionExtension` Instead of registering `ReadRuntimeVersionExt` in `sp-state-machine` it is moved to `ExecutionExtension` which provides the default extensions. * Fix compilation * Register the global extensions inside runtime api instance * Fixes * Fix `generate_initial_session_keys` by passing the keystore extension * Fix the grandpa tests * Fix more tests * Fix more tests * Don't set any heap pages if there isn't an override * Fix small fallout * FMT * Fix tests * More tests * Offchain worker custom extensions * More fixes * Make offchain tx pool creation reusable Introduces an `OffchainTransactionPoolFactory` for creating offchain transactions pools that can be registered in the runtime externalities context. This factory will be required for a later pr to make the creation of offchain transaction pools easier. * Fixes * Fixes * Set offchain transaction pool in BABE before using it in the runtime * Add the `offchain_tx_pool` to Grandpa as well * Fix the nodes * Print some error when using the old warnings * Fix merge issues * Fix compilation * Rename `babe_link` * Rename to `offchain_tx_pool_factory` * Cleanup * FMT * Fix benchmark name * Fix `try-runtime` * Remove `--execution` CLI args * Make clippy happy * Forward bls functions * Fix docs * Update UI tests * Update client/api/src/execution_extensions.rs Co-authored-by: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com> * Apply suggestions from code review Co-authored-by: Koute * Update client/cli/src/params/import_params.rs Co-authored-by: Koute * Update client/api/src/execution_extensions.rs Co-authored-by: Koute * Pass the offchain storage to the MMR RPC * Update client/api/src/execution_extensions.rs Co-authored-by: Sebastian Kunert * Review comments * Fixes --------- Co-authored-by: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com> Co-authored-by: Koute Co-authored-by: Sebastian Kunert * `GenesisBuild` deprecated. `BuildGenesisConfig` added. (#14306) * frame::support: GenesisConfig types for Runtime enabled * frame::support: macro generating GenesisBuild::build for RuntimeGenesisConfig * frame: ambiguity BuildStorage vs GenesisBuild fixed * fix * RuntimeGenesisBuild added * Revert "frame: ambiguity BuildStorage vs GenesisBuild fixed" This reverts commit 6017dad47e011d118262a4198ccffea0b0ccbcff. * Revert "fix" This reverts commit 477d7ad8cd66d53f533a1b8f49c611a14a18c49d. * Revert "RuntimeGenesisBuild added" This reverts commit 3c131b618138ced29c01ab8d15d8c6410c9e128b. * Revert "Revert "frame: ambiguity BuildStorage vs GenesisBuild fixed"" This reverts commit 2b1ecd467231eddec69f8d328039ba48a380da3d. * Revert "Revert "fix"" This reverts commit fd7fa629adf579d83e30e6ae9fd162637fc45e30. * Code review suggestions * frame: BuildGenesisConfig added, BuildGenesis deprecated * frame: some pallets updated with BuildGenesisConfig * constuct_runtime: support for BuildGenesisConfig * frame::support: genesis_build macro supports BuildGenesisConfig * frame: BuildGenesisConfig added, BuildGenesis deprecated * Cargo.lock update * test-runtime: fixes * Revert "fix" This reverts commit 477d7ad8cd66d53f533a1b8f49c611a14a18c49d. * Revert "frame: ambiguity BuildStorage vs GenesisBuild fixed" This reverts commit 6017dad47e011d118262a4198ccffea0b0ccbcff. * self review * doc fixed * ui tests fixed * fmt * tests fixed * genesis_build macrto fixed for non-generic GenesisConfig * BuildGenesisConfig constraints added * warning fixed * some duplication removed * fmt * fix * doc tests fix * doc fix * cleanup: remove BuildModuleGenesisStorage * self review comments * fix * Update frame/treasury/src/tests.rs Co-authored-by: Sebastian Kunert * Update frame/support/src/traits/hooks.rs Co-authored-by: Sebastian Kunert * doc fix: GenesisBuild exposed * ".git/.scripts/commands/fmt/fmt.sh" * frame: more serde(skip) + cleanup * Update frame/support/src/traits/hooks.rs Co-authored-by: Davide Galassi * frame: phantom fields moved to the end of structs * chain-spec: Default::default cleanup * test-runtime: phantom at the end * merge master fixes * fix * fix * fix * fix * fix (facepalm) * Update frame/support/procedural/src/pallet/expand/genesis_build.rs Co-authored-by: Bastian Köcher * fmt * fix * fix --------- Co-authored-by: parity-processbot <> Co-authored-by: Sebastian Kunert Co-authored-by: Davide Galassi Co-authored-by: Bastian Köcher * Moves `Block` to `frame_system` instead of `construct_runtime` and removes `Header` and `BlockNumber` (#14437) * Initial setup * Adds node block * Uses UncheckedExtrinsic and removes Where section * Updates frame_system to use Block * Adds deprecation warning * Fixes pallet-timestamp * Removes Header and BlockNumber * Addresses review comments * Addresses review comments * Adds comment about compiler bug * Removes where clause * Refactors code * Fixes errors in cargo check * Fixes errors in cargo check * Fixes warnings in cargo check * Formatting * Fixes construct_runtime tests * Uses import instead of full path for BlockNumber * Uses import instead of full path for Header * Formatting * Fixes construct_runtime tests * Fixes imports in benchmarks * Formatting * Fixes construct_runtime tests * Formatting * Minor updates * Fixes construct_runtime ui tests * Fixes construct_runtime ui tests with 1.70 * Fixes docs * Fixes docs * Adds u128 mock block type * Fixes split example * fixes for cumulus * ".git/.scripts/commands/fmt/fmt.sh" * Updates new tests * Fixes fully-qualified path in few places * Formatting * Update frame/examples/default-config/src/lib.rs Co-authored-by: Juan * Update frame/support/procedural/src/construct_runtime/mod.rs Co-authored-by: Juan * ".git/.scripts/commands/fmt/fmt.sh" * Addresses some review comments * Fixes build * ".git/.scripts/commands/fmt/fmt.sh" * Update frame/democracy/src/lib.rs Co-authored-by: Oliver Tale-Yazdi * Update frame/democracy/src/lib.rs Co-authored-by: Oliver Tale-Yazdi * Update frame/support/procedural/src/construct_runtime/mod.rs Co-authored-by: Oliver Tale-Yazdi * Update frame/support/procedural/src/construct_runtime/mod.rs Co-authored-by: Oliver Tale-Yazdi * Addresses review comments * Updates trait bounds * Minor fix * ".git/.scripts/commands/fmt/fmt.sh" * Removes unnecessary bound * ".git/.scripts/commands/fmt/fmt.sh" * Updates test * Fixes build * Adds a bound for header * ".git/.scripts/commands/fmt/fmt.sh" * Removes where block * Minor fix * Minor fix * Fixes tests * ".git/.scripts/commands/update-ui/update-ui.sh" 1.70 * Updates test * Update primitives/runtime/src/traits.rs Co-authored-by: Bastian Köcher * Update primitives/runtime/src/traits.rs Co-authored-by: Bastian Köcher * Updates doc * Updates doc --------- Co-authored-by: command-bot <> Co-authored-by: Juan Co-authored-by: Oliver Tale-Yazdi Co-authored-by: Bastian Köcher * Replace system config `Index` for `Nonce` (#14290) * replace Index by Nonce * replace Index by Nonce * replace Index by Nonce * replace Index by Nonce * replace Index by Nonce * wip * remove index in lieu of nonce * wip * remove accountnonce in lieu of nonce * add minor improvement * rebase and merge conflicts --------- Co-authored-by: Bastian Köcher Co-authored-by: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com> Co-authored-by: Koute Co-authored-by: Sebastian Kunert Co-authored-by: Davide Galassi Co-authored-by: gupnik <17176722+gupnik@users.noreply.github.com> Co-authored-by: Juan Co-authored-by: Oliver Tale-Yazdi --- Cargo.lock | 18 +- bin/node-template/node/Cargo.toml | 2 + bin/node-template/node/src/chain_spec.rs | 2 + bin/node-template/node/src/rpc.rs | 4 +- bin/node-template/node/src/service.rs | 29 +- .../pallets/template/src/mock.rs | 15 +- .../pallets/template/src/weights.rs | 1 - bin/node-template/runtime/src/lib.rs | 23 +- bin/node/bench/src/construct.rs | 16 +- bin/node/bench/src/import.rs | 23 +- bin/node/bench/src/main.rs | 37 +- bin/node/bench/src/txpool.rs | 4 +- bin/node/cli/Cargo.toml | 1 + bin/node/cli/benches/block_production.rs | 11 - bin/node/cli/benches/transaction_pool.rs | 9 - bin/node/cli/src/chain_spec.rs | 23 +- bin/node/cli/src/service.rs | 80 ++-- bin/node/cli/tests/benchmark_block_works.rs | 2 +- bin/node/executor/tests/basic.rs | 18 +- bin/node/executor/tests/fees.rs | 10 +- bin/node/primitives/src/lib.rs | 2 +- bin/node/rpc/src/lib.rs | 39 +- bin/node/runtime/src/impls.rs | 6 +- bin/node/runtime/src/lib.rs | 18 +- bin/node/testing/src/bench.rs | 65 +-- bin/node/testing/src/genesis.rs | 10 +- bin/node/testing/src/keyring.rs | 4 +- client/api/Cargo.toml | 1 - client/api/src/call_executor.rs | 9 +- client/api/src/execution_extensions.rs | 187 +------- client/api/src/lib.rs | 2 +- client/block-builder/src/lib.rs | 34 +- client/cli/src/arg_enums.rs | 24 - client/cli/src/config.rs | 17 - client/cli/src/params/import_params.rs | 56 +-- client/cli/src/runner.rs | 1 - client/consensus/aura/src/import_queue.rs | 6 +- client/consensus/babe/Cargo.toml | 1 + client/consensus/babe/rpc/Cargo.toml | 1 + client/consensus/babe/rpc/src/lib.rs | 27 +- client/consensus/babe/src/lib.rs | 76 ++- client/consensus/babe/src/tests.rs | 4 + client/consensus/grandpa/Cargo.toml | 1 + client/consensus/grandpa/src/environment.rs | 12 +- client/consensus/grandpa/src/lib.rs | 16 +- client/consensus/grandpa/src/tests.rs | 22 +- client/consensus/pow/src/lib.rs | 5 +- client/merkle-mountain-range/rpc/src/lib.rs | 47 +- client/offchain/Cargo.toml | 5 + client/offchain/src/api.rs | 114 +---- client/offchain/src/lib.rs | 265 +++++++---- client/rpc-spec-v2/Cargo.toml | 1 + .../rpc-spec-v2/src/chain_head/chain_head.rs | 8 +- .../src/chain_head/subscription/inner.rs | 1 - .../rpc-spec-v2/src/chain_head/test_utils.rs | 8 + client/rpc-spec-v2/src/chain_head/tests.rs | 4 +- client/rpc/Cargo.toml | 1 + client/rpc/src/author/mod.rs | 11 +- client/rpc/src/author/tests.rs | 3 +- client/rpc/src/state/state_full.rs | 8 +- client/rpc/src/state/tests.rs | 2 +- client/service/Cargo.toml | 1 - client/service/src/builder.rs | 47 +- client/service/src/client/call_executor.rs | 54 +-- client/service/src/client/client.rs | 37 +- client/service/src/config.rs | 3 - client/service/src/lib.rs | 4 +- client/service/test/src/client/mod.rs | 60 +-- client/service/test/src/lib.rs | 1 - client/statement-store/src/lib.rs | 12 +- client/transaction-pool/api/src/lib.rs | 58 ++- client/transaction-pool/src/lib.rs | 9 +- client/transaction-pool/tests/pool.rs | 8 +- frame/alliance/src/benchmarking.rs | 6 +- frame/alliance/src/lib.rs | 7 +- frame/alliance/src/mock.rs | 30 +- frame/asset-conversion/src/lib.rs | 7 +- frame/asset-conversion/src/mock.rs | 16 +- frame/asset-rate/src/mock.rs | 15 +- frame/assets/src/lib.rs | 2 +- frame/assets/src/mock.rs | 19 +- frame/atomic-swap/src/lib.rs | 5 +- frame/atomic-swap/src/tests.rs | 17 +- frame/aura/src/lib.rs | 6 +- frame/aura/src/mock.rs | 22 +- frame/authority-discovery/src/lib.rs | 39 +- frame/authorship/src/lib.rs | 22 +- frame/babe/src/equivocation.rs | 9 +- frame/babe/src/lib.rs | 57 ++- frame/babe/src/mock.rs | 17 +- frame/babe/src/randomness.rs | 17 +- frame/bags-list/src/mock.rs | 16 +- frame/balances/README.md | 2 +- frame/balances/src/impl_currency.rs | 3 +- frame/balances/src/lib.rs | 25 +- frame/balances/src/tests/currency_tests.rs | 4 +- frame/balances/src/tests/mod.rs | 18 +- frame/beefy-mmr/src/lib.rs | 3 +- frame/beefy-mmr/src/mock.rs | 21 +- frame/beefy/src/equivocation.rs | 5 +- frame/beefy/src/lib.rs | 2 +- frame/beefy/src/mock.rs | 21 +- frame/benchmarking/README.md | 1 - frame/benchmarking/pov/src/benchmarking.rs | 20 +- frame/benchmarking/pov/src/tests.rs | 13 +- frame/benchmarking/src/baseline.rs | 20 +- frame/benchmarking/src/tests.rs | 15 +- frame/benchmarking/src/tests_instance.rs | 15 +- frame/bounties/src/benchmarking.rs | 18 +- frame/bounties/src/lib.rs | 6 +- frame/bounties/src/tests.rs | 30 +- frame/child-bounties/src/benchmarking.rs | 8 +- frame/child-bounties/src/lib.rs | 4 +- frame/child-bounties/src/tests.rs | 28 +- frame/collective/src/benchmarking.rs | 10 +- frame/collective/src/lib.rs | 7 +- frame/collective/src/tests.rs | 12 +- frame/contracts/src/exec.rs | 13 +- frame/contracts/src/lib.rs | 4 +- frame/contracts/src/tests.rs | 19 +- frame/contracts/src/wasm/mod.rs | 5 +- frame/contracts/src/wasm/runtime.rs | 2 +- frame/conviction-voting/src/lib.rs | 16 +- frame/conviction-voting/src/tests.rs | 17 +- frame/core-fellowship/src/benchmarking.rs | 6 +- frame/core-fellowship/src/lib.rs | 5 +- frame/core-fellowship/src/tests.rs | 18 +- frame/democracy/src/benchmarking.rs | 10 +- frame/democracy/src/lib.rs | 78 ++-- frame/democracy/src/migrations/v1.rs | 9 +- frame/democracy/src/tests.rs | 22 +- .../src/benchmarking.rs | 2 +- .../election-provider-multi-phase/src/lib.rs | 34 +- .../election-provider-multi-phase/src/mock.rs | 20 +- .../src/signed.rs | 9 +- .../src/unsigned.rs | 6 +- .../test-staking-e2e/src/mock.rs | 24 +- .../election-provider-support/src/onchain.rs | 15 +- frame/elections-phragmen/src/lib.rs | 20 +- frame/examples/basic/src/lib.rs | 8 +- frame/examples/basic/src/tests.rs | 14 +- frame/examples/default-config/src/lib.rs | 15 +- frame/examples/dev-mode/src/tests.rs | 14 +- frame/examples/kitchensink/src/lib.rs | 16 +- frame/examples/kitchensink/src/tests.rs | 10 +- frame/examples/offchain-worker/src/lib.rs | 52 ++- frame/examples/offchain-worker/src/tests.rs | 19 +- frame/examples/split/src/mock.rs | 13 +- frame/executive/src/lib.rs | 112 ++--- frame/fast-unstake/src/lib.rs | 6 +- frame/fast-unstake/src/mock.rs | 23 +- frame/glutton/src/lib.rs | 6 +- frame/glutton/src/mock.rs | 17 +- frame/grandpa/src/equivocation.rs | 9 +- frame/grandpa/src/lib.rs | 45 +- frame/grandpa/src/mock.rs | 21 +- frame/identity/src/tests.rs | 17 +- frame/im-online/src/benchmarking.rs | 7 +- frame/im-online/src/lib.rs | 20 +- frame/im-online/src/mock.rs | 19 +- frame/indices/src/lib.rs | 2 +- frame/indices/src/mock.rs | 17 +- .../src/lib.rs | 27 +- frame/lottery/src/lib.rs | 10 +- frame/lottery/src/mock.rs | 18 +- frame/membership/src/lib.rs | 24 +- frame/merkle-mountain-range/src/lib.rs | 24 +- frame/merkle-mountain-range/src/mock.rs | 18 +- frame/merkle-mountain-range/src/tests.rs | 5 +- frame/message-queue/src/integration_test.rs | 18 +- frame/message-queue/src/mock.rs | 19 +- frame/multisig/src/lib.rs | 20 +- frame/multisig/src/tests.rs | 18 +- .../nft-fractionalization/src/benchmarking.rs | 13 +- frame/nft-fractionalization/src/mock.rs | 16 +- frame/nfts/src/benchmarking.rs | 8 +- frame/nfts/src/features/approvals.rs | 2 +- frame/nfts/src/features/atomic_swap.rs | 2 +- frame/nfts/src/features/settings.rs | 2 +- frame/nfts/src/lib.rs | 22 +- frame/nfts/src/mock.rs | 18 +- frame/nfts/src/types.rs | 14 +- frame/nfts/src/weights.rs | 1 - frame/nicks/src/lib.rs | 15 +- frame/nis/src/lib.rs | 23 +- frame/nis/src/mock.rs | 17 +- frame/node-authorization/src/lib.rs | 4 +- frame/node-authorization/src/mock.rs | 19 +- .../nomination-pools/benchmarking/src/mock.rs | 18 +- frame/nomination-pools/src/lib.rs | 15 +- frame/nomination-pools/src/mock.rs | 17 +- .../nomination-pools/test-staking/src/mock.rs | 17 +- frame/offences/benchmarking/src/mock.rs | 16 +- frame/offences/src/mock.rs | 18 +- frame/preimage/src/mock.rs | 15 +- frame/proxy/src/benchmarking.rs | 14 +- frame/proxy/src/lib.rs | 35 +- frame/proxy/src/tests.rs | 17 +- frame/ranked-collective/src/lib.rs | 2 +- frame/ranked-collective/src/tests.rs | 17 +- frame/recovery/src/lib.rs | 6 +- frame/recovery/src/mock.rs | 17 +- frame/referenda/src/benchmarking.rs | 4 +- frame/referenda/src/lib.rs | 51 +- frame/referenda/src/migration.rs | 2 +- frame/referenda/src/mock.rs | 16 +- frame/referenda/src/types.rs | 17 +- frame/remark/src/mock.rs | 14 +- frame/root-offences/src/mock.rs | 20 +- frame/salary/src/lib.rs | 11 +- frame/salary/src/tests.rs | 18 +- frame/scheduler/src/benchmarking.rs | 13 +- frame/scheduler/src/lib.rs | 149 +++--- frame/scheduler/src/migration.rs | 37 +- frame/scheduler/src/mock.rs | 18 +- frame/scored-pool/src/lib.rs | 6 +- frame/scored-pool/src/mock.rs | 19 +- frame/session/benchmarking/src/lib.rs | 8 +- frame/session/benchmarking/src/mock.rs | 20 +- frame/session/src/historical/mod.rs | 6 +- frame/session/src/historical/offchain.rs | 8 +- frame/session/src/lib.rs | 15 +- frame/session/src/mock.rs | 27 +- frame/society/src/benchmarking.rs | 5 +- frame/society/src/lib.rs | 33 +- frame/society/src/migrations.rs | 2 +- frame/society/src/mock.rs | 17 +- frame/staking/src/mock.rs | 22 +- frame/staking/src/pallet/impls.rs | 6 +- frame/staking/src/pallet/mod.rs | 10 +- frame/state-trie-migration/src/lib.rs | 27 +- frame/statement/src/mock.rs | 16 +- frame/sudo/src/lib.rs | 2 +- frame/sudo/src/mock.rs | 21 +- .../src/construct_runtime/expand/config.rs | 38 +- .../src/construct_runtime/expand/inherent.rs | 6 +- .../src/construct_runtime/expand/metadata.rs | 4 +- .../procedural/src/construct_runtime/mod.rs | 35 +- .../procedural/src/construct_runtime/parse.rs | 10 +- frame/support/procedural/src/lib.rs | 13 +- .../src/pallet/expand/genesis_build.rs | 34 +- .../procedural/src/pallet/expand/hooks.rs | 40 +- .../src/pallet/parse/genesis_build.rs | 5 +- .../procedural/src/pallet/parse/helper.rs | 33 +- .../procedural/src/pallet/parse/mod.rs | 2 +- frame/support/src/dispatch.rs | 266 +---------- frame/support/src/error.rs | 45 -- frame/support/src/lib.rs | 81 ++-- frame/support/src/migrations.rs | 7 +- frame/support/src/storage/generator/mod.rs | 13 +- frame/support/src/traits.rs | 4 +- frame/support/src/traits/hooks.rs | 11 + frame/support/test/compile_pass/src/lib.rs | 13 +- frame/support/test/pallet/Cargo.toml | 1 + frame/support/test/pallet/src/lib.rs | 9 +- frame/support/test/src/lib.rs | 7 +- .../support/test/tests/common/outer_enums.rs | 6 +- frame/support/test/tests/construct_runtime.rs | 151 ++++-- .../both_use_and_excluded_parts.rs | 7 +- .../both_use_and_excluded_parts.stderr | 4 +- .../conflicting_module_name.rs | 5 +- .../conflicting_module_name.stderr | 16 +- .../deprecated_where_block.rs | 13 + .../deprecated_where_block.stderr | 442 ++++++++++++++++++ .../double_module_parts.rs | 5 +- .../double_module_parts.stderr | 8 +- .../construct_runtime_ui/empty_pallet_path.rs | 5 +- .../empty_pallet_path.stderr | 4 +- .../exclude_undefined_part.rs | 7 +- .../exclude_undefined_part.stderr | 4 +- .../feature_gated_system_pallet.rs | 7 +- .../feature_gated_system_pallet.stderr | 8 +- .../generics_in_invalid_module.rs | 5 +- .../generics_in_invalid_module.stderr | 8 +- .../invalid_meta_literal.rs | 5 +- .../invalid_meta_literal.stderr | 8 +- .../invalid_module_details.rs | 5 +- .../invalid_module_details.stderr | 4 +- .../invalid_module_details_keyword.rs | 5 +- .../invalid_module_details_keyword.stderr | 4 +- .../invalid_module_entry.rs | 5 +- .../invalid_module_entry.stderr | 8 +- .../invalid_token_after_module.rs | 5 +- .../invalid_token_after_module.stderr | 4 +- .../invalid_token_after_name.rs | 5 +- .../invalid_token_after_name.stderr | 4 +- ...g_event_generic_on_module_with_instance.rs | 5 +- ...ent_generic_on_module_with_instance.stderr | 8 +- .../missing_module_instance.rs | 5 +- .../missing_module_instance.stderr | 4 +- ..._origin_generic_on_module_with_instance.rs | 5 +- ...gin_generic_on_module_with_instance.stderr | 8 +- .../missing_system_module.rs | 5 +- .../missing_system_module.stderr | 8 +- .../missing_where_block.rs | 7 - .../missing_where_block.stderr | 5 - .../number_of_pallets_exceeds_tuple_size.rs | 12 +- ...umber_of_pallets_exceeds_tuple_size.stderr | 18 +- .../pallet_error_too_large.rs | 22 +- .../pallet_error_too_large.stderr | 18 +- .../undefined_call_part.rs | 14 +- .../undefined_call_part.stderr | 14 +- .../undefined_event_part.rs | 14 +- .../undefined_event_part.stderr | 30 +- .../undefined_genesis_config_part.rs | 14 +- .../undefined_genesis_config_part.stderr | 30 +- .../undefined_inherent_part.rs | 14 +- .../undefined_inherent_part.stderr | 94 ++-- .../undefined_origin_part.rs | 14 +- .../undefined_origin_part.stderr | 30 +- .../undefined_validate_unsigned_part.rs | 12 +- .../undefined_validate_unsigned_part.stderr | 60 ++- .../unsupported_meta_structure.rs | 5 +- .../unsupported_meta_structure.stderr | 8 +- .../unsupported_pallet_attr.rs | 5 +- .../unsupported_pallet_attr.stderr | 8 +- .../use_undefined_part.rs | 7 +- .../use_undefined_part.stderr | 4 +- frame/support/test/tests/final_keys.rs | 44 +- frame/support/test/tests/genesisconfig.rs | 27 +- frame/support/test/tests/instance.rs | 35 +- frame/support/test/tests/issue2219.rs | 61 +-- frame/support/test/tests/origin.rs | 46 +- frame/support/test/tests/pallet.rs | 23 +- frame/support/test/tests/pallet_instance.rs | 20 +- .../test/tests/pallet_outer_enums_explicit.rs | 30 +- .../test/tests/pallet_outer_enums_implicit.rs | 28 +- .../genesis_default_not_satisfied.rs | 4 +- .../genesis_default_not_satisfied.stderr | 12 +- .../pallet_ui/pallet_doc_arg_non_path.rs | 2 +- .../test/tests/pallet_ui/pallet_doc_empty.rs | 2 +- .../tests/pallet_ui/pallet_doc_invalid_arg.rs | 2 +- .../pallet_ui/pallet_doc_multiple_args.rs | 2 +- .../tests/pallet_ui/pass/dev_mode_valid.rs | 24 +- .../pallet_ui/pass/no_std_genesis_config.rs | 16 +- .../pass/where_clause_missing_hooks.rs | 15 +- frame/support/test/tests/runtime_metadata.rs | 11 +- frame/support/test/tests/storage_layers.rs | 14 +- .../support/test/tests/storage_transaction.rs | 23 +- .../test/tests/versioned_runtime_upgrade.rs | 25 +- frame/system/README.md | 2 +- frame/system/benches/bench.rs | 21 +- frame/system/benchmarking/src/mock.rs | 20 +- frame/system/rpc/runtime-api/src/lib.rs | 8 +- frame/system/src/extensions/check_genesis.rs | 4 +- .../system/src/extensions/check_mortality.rs | 4 +- frame/system/src/extensions/check_nonce.rs | 6 +- frame/system/src/lib.rs | 123 ++--- frame/system/src/migrations/mod.rs | 16 +- frame/system/src/mock.rs | 14 +- frame/system/src/mocking.rs | 15 +- frame/system/src/offchain.rs | 2 +- frame/timestamp/src/lib.rs | 2 +- frame/timestamp/src/mock.rs | 17 +- frame/tips/src/benchmarking.rs | 2 +- frame/tips/src/lib.rs | 11 +- frame/tips/src/tests.rs | 28 +- .../asset-conversion-tx-payment/src/mock.rs | 12 +- .../asset-conversion-tx-payment/src/tests.rs | 4 +- .../asset-tx-payment/src/mock.rs | 18 +- .../asset-tx-payment/src/tests.rs | 4 +- frame/transaction-payment/src/lib.rs | 12 +- frame/transaction-payment/src/mock.rs | 18 +- frame/transaction-payment/src/tests.rs | 13 +- frame/transaction-storage/src/benchmarking.rs | 8 +- frame/transaction-storage/src/lib.rs | 16 +- frame/transaction-storage/src/mock.rs | 14 +- frame/treasury/src/benchmarking.rs | 2 +- frame/treasury/src/lib.rs | 24 +- frame/treasury/src/tests.rs | 31 +- frame/uniques/src/mock.rs | 17 +- frame/utility/src/tests.rs | 20 +- frame/vesting/src/benchmarking.rs | 10 +- frame/vesting/src/lib.rs | 45 +- frame/vesting/src/migrations.rs | 4 +- frame/vesting/src/mock.rs | 19 +- frame/whitelist/src/mock.rs | 12 +- primitives/api/Cargo.toml | 2 + .../api/proc-macro/src/decl_runtime_apis.rs | 34 +- .../api/proc-macro/src/impl_runtime_apis.rs | 39 +- .../proc-macro/src/mock_impl_runtime_apis.rs | 49 +- .../api/proc-macro/src/runtime_metadata.rs | 6 +- primitives/api/src/lib.rs | 29 +- primitives/api/test/benches/bench.rs | 11 +- primitives/api/test/tests/runtime_calls.rs | 39 +- .../tests/ui/mock_only_self_reference.stderr | 39 -- .../application-crypto/test/src/ecdsa.rs | 13 +- .../application-crypto/test/src/ed25519.rs | 13 +- .../application-crypto/test/src/sr25519.rs | 13 +- primitives/consensus/common/src/lib.rs | 10 - primitives/core/Cargo.toml | 2 + primitives/core/src/lib.rs | 39 -- primitives/core/src/offchain/mod.rs | 26 +- primitives/core/src/offchain/storage.rs | 96 +++- primitives/externalities/src/extensions.rs | 14 + primitives/keystore/src/lib.rs | 171 ++++++- primitives/runtime/src/generic/block.rs | 16 +- primitives/runtime/src/generic/header.rs | 9 +- primitives/runtime/src/lib.rs | 3 + primitives/runtime/src/runtime_logger.rs | 7 +- primitives/runtime/src/testing.rs | 6 +- primitives/runtime/src/traits.rs | 50 +- primitives/session/Cargo.toml | 2 + primitives/session/src/lib.rs | 7 +- primitives/state-machine/src/lib.rs | 255 +--------- primitives/test-primitives/src/lib.rs | 2 +- scripts/ci/gitlab/pipeline/test.yml | 6 +- scripts/run_all_benchmarks.sh | 2 - test-utils/client/src/lib.rs | 35 +- test-utils/runtime/src/extrinsic.rs | 6 +- test-utils/runtime/src/genesismap.rs | 10 +- test-utils/runtime/src/lib.rs | 76 +-- .../runtime/src/substrate_test_pallet.rs | 12 +- .../runtime/transaction-pool/src/lib.rs | 4 +- utils/frame/benchmarking-cli/src/block/cmd.rs | 4 +- .../benchmarking-cli/src/overhead/README.md | 5 +- .../benchmarking-cli/src/pallet/command.rs | 21 +- .../frame/benchmarking-cli/src/pallet/mod.rs | 8 +- .../benchmarking-cli/src/pallet/writer.rs | 2 - utils/frame/rpc/support/src/lib.rs | 12 +- utils/frame/rpc/system/src/lib.rs | 18 +- utils/frame/try-runtime/cli/src/lib.rs | 12 +- 422 files changed, 4000 insertions(+), 4713 deletions(-) create mode 100644 frame/support/test/tests/construct_runtime_ui/deprecated_where_block.rs create mode 100644 frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr delete mode 100644 frame/support/test/tests/construct_runtime_ui/missing_where_block.rs delete mode 100644 frame/support/test/tests/construct_runtime_ui/missing_where_block.stderr diff --git a/Cargo.lock b/Cargo.lock index 76f3459b16603..05f4230b140de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2921,6 +2921,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", + "sp-runtime", ] [[package]] @@ -5415,6 +5416,7 @@ dependencies = [ "sc-network-common", "sc-network-statement", "sc-network-sync", + "sc-offchain", "sc-rpc", "sc-service", "sc-service-test", @@ -5577,8 +5579,10 @@ dependencies = [ "sc-consensus-grandpa", "sc-executor", "sc-network", + "sc-offchain", "sc-rpc-api", "sc-service", + "sc-statement-store", "sc-telemetry", "sc-transaction-pool", "sc-transaction-pool-api", @@ -9087,7 +9091,6 @@ dependencies = [ "sp-core", "sp-database", "sp-externalities", - "sp-keystore", "sp-runtime", "sp-state-machine", "sp-statement-store", @@ -9216,6 +9219,7 @@ dependencies = [ "sc-network", "sc-network-test", "sc-telemetry", + "sc-transaction-pool-api", "scale-info", "sp-api", "sp-application-crypto", @@ -9248,6 +9252,7 @@ dependencies = [ "sc-consensus-epochs", "sc-keystore", "sc-rpc-api", + "sc-transaction-pool-api", "serde", "serde_json", "sp-api", @@ -9365,6 +9370,7 @@ dependencies = [ "sc-network-gossip", "sc-network-test", "sc-telemetry", + "sc-transaction-pool-api", "sc-utils", "serde", "serde_json", @@ -9846,6 +9852,7 @@ dependencies = [ "hyper-rustls 0.24.0", "lazy_static", "libp2p", + "log", "num_cpus", "once_cell", "parity-scale-codec", @@ -9855,12 +9862,15 @@ dependencies = [ "sc-client-api", "sc-client-db", "sc-network", + "sc-network-common", "sc-transaction-pool", "sc-transaction-pool-api", "sc-utils", "sp-api", "sp-consensus", "sp-core", + "sp-externalities", + "sp-keystore", "sp-offchain", "sp-runtime", "sp-tracing", @@ -9889,6 +9899,7 @@ dependencies = [ "log", "parity-scale-codec", "parking_lot 0.12.1", + "pretty_assertions", "sc-block-builder", "sc-chain-spec", "sc-client-api", @@ -9961,6 +9972,7 @@ dependencies = [ "log", "parity-scale-codec", "parking_lot 0.12.1", + "pretty_assertions", "sc-block-builder", "sc-chain-spec", "sc-client-api", @@ -10024,7 +10036,6 @@ dependencies = [ "sc-network-light", "sc-network-sync", "sc-network-transactions", - "sc-offchain", "sc-rpc", "sc-rpc-server", "sc-rpc-spec-v2", @@ -10770,6 +10781,7 @@ dependencies = [ "scale-info", "sp-api-proc-macro", "sp-core", + "sp-externalities", "sp-metadata-ir", "sp-runtime", "sp-state-machine", @@ -11153,6 +11165,7 @@ dependencies = [ "substrate-bip39", "thiserror", "tiny-bip39", + "tracing", "w3f-bls", "zeroize", ] @@ -11500,6 +11513,7 @@ dependencies = [ "scale-info", "sp-api", "sp-core", + "sp-keystore", "sp-runtime", "sp-staking", "sp-std", diff --git a/bin/node-template/node/Cargo.toml b/bin/node-template/node/Cargo.toml index a1d1fe1848c33..39f60f52c8344 100644 --- a/bin/node-template/node/Cargo.toml +++ b/bin/node-template/node/Cargo.toml @@ -28,6 +28,8 @@ sc-service = { version = "0.10.0-dev", path = "../../../client/service" } sc-telemetry = { version = "4.0.0-dev", path = "../../../client/telemetry" } sc-transaction-pool = { version = "4.0.0-dev", path = "../../../client/transaction-pool" } sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../../client/transaction-pool/api" } +sc-offchain = { version = "4.0.0-dev", path = "../../../client/offchain" } +sc-statement-store = { version = "4.0.0-dev", path = "../../../client/statement-store" } sc-consensus-aura = { version = "0.10.0-dev", path = "../../../client/consensus/aura" } sp-consensus-aura = { version = "0.10.0-dev", path = "../../../primitives/consensus/aura" } sc-consensus = { version = "0.10.0-dev", path = "../../../client/consensus/common" } diff --git a/bin/node-template/node/src/chain_spec.rs b/bin/node-template/node/src/chain_spec.rs index b28e8140fabc6..2cd2d07293026 100644 --- a/bin/node-template/node/src/chain_spec.rs +++ b/bin/node-template/node/src/chain_spec.rs @@ -136,6 +136,7 @@ fn testnet_genesis( system: SystemConfig { // Add Wasm runtime to storage. code: wasm_binary.to_vec(), + ..Default::default() }, balances: BalancesConfig { // Configure endowed accounts with initial balance of 1 << 60. @@ -146,6 +147,7 @@ fn testnet_genesis( }, grandpa: GrandpaConfig { authorities: initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect(), + ..Default::default() }, sudo: SudoConfig { // Assign network admin rights. diff --git a/bin/node-template/node/src/rpc.rs b/bin/node-template/node/src/rpc.rs index f6995e95945a4..f4f1540f732f7 100644 --- a/bin/node-template/node/src/rpc.rs +++ b/bin/node-template/node/src/rpc.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use jsonrpsee::RpcModule; -use node_template_runtime::{opaque::Block, AccountId, Balance, Index}; +use node_template_runtime::{opaque::Block, AccountId, Balance, Nonce}; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; use sp_block_builder::BlockBuilder; @@ -34,7 +34,7 @@ where C: ProvideRuntimeApi, C: HeaderBackend + HeaderMetadata + 'static, C: Send + Sync + 'static, - C::Api: substrate_frame_rpc_system::AccountNonceApi, + C::Api: substrate_frame_rpc_system::AccountNonceApi, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, C::Api: BlockBuilder, P: TransactionPool + 'static, diff --git a/bin/node-template/node/src/service.rs b/bin/node-template/node/src/service.rs index 07006925fbb68..355e24c95620b 100644 --- a/bin/node-template/node/src/service.rs +++ b/bin/node-template/node/src/service.rs @@ -1,12 +1,14 @@ //! Service and ServiceFactory implementation. Specialized wrapper over substrate service. +use futures::FutureExt; use node_template_runtime::{self, opaque::Block, RuntimeApi}; -use sc_client_api::BlockBackend; +use sc_client_api::{Backend, BlockBackend}; use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams}; use sc_consensus_grandpa::SharedVoterState; pub use sc_executor::NativeElseWasmExecutor; use sc_service::{error::Error as ServiceError, Configuration, TaskManager, WarpSyncParams}; use sc_telemetry::{Telemetry, TelemetryWorker}; +use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sp_consensus_aura::sr25519::AuthorityPair as AuraPair; use std::{sync::Arc, time::Duration}; @@ -179,11 +181,23 @@ pub fn new_full(config: Configuration) -> Result { })?; if config.offchain_worker.enabled { - sc_service::build_offchain_workers( - &config, - task_manager.spawn_handle(), - client.clone(), - network.clone(), + task_manager.spawn_handle().spawn( + "offchain-workers-runner", + "offchain-worker", + sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions { + runtime_api_provider: client.clone(), + is_validator: config.role.is_authority(), + keystore: Some(keystore_container.keystore()), + offchain_db: backend.offchain_storage(), + transaction_pool: Some(OffchainTransactionPoolFactory::new( + transaction_pool.clone(), + )), + network_provider: network.clone(), + enable_http_requests: true, + custom_extensions: |_| vec![], + }) + .run(client.clone(), task_manager.spawn_handle()) + .boxed(), ); } @@ -224,7 +238,7 @@ pub fn new_full(config: Configuration) -> Result { let proposer_factory = sc_basic_authorship::ProposerFactory::new( task_manager.spawn_handle(), client.clone(), - transaction_pool, + transaction_pool.clone(), prometheus_registry.as_ref(), telemetry.as_ref().map(|x| x.handle()), ); @@ -300,6 +314,7 @@ pub fn new_full(config: Configuration) -> Result { 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. diff --git a/bin/node-template/pallets/template/src/mock.rs b/bin/node-template/pallets/template/src/mock.rs index b4d6905378a5d..244ae1b37859b 100644 --- a/bin/node-template/pallets/template/src/mock.rs +++ b/bin/node-template/pallets/template/src/mock.rs @@ -2,19 +2,15 @@ use crate as pallet_template; use frame_support::traits::{ConstU16, ConstU64}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, TemplateModule: pallet_template, @@ -28,13 +24,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -55,5 +50,5 @@ impl pallet_template::Config for Test { // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } diff --git a/bin/node-template/pallets/template/src/weights.rs b/bin/node-template/pallets/template/src/weights.rs index e8fbc09bad8e9..7c42936e09f29 100644 --- a/bin/node-template/pallets/template/src/weights.rs +++ b/bin/node-template/pallets/template/src/weights.rs @@ -19,7 +19,6 @@ // * // --steps=50 // --repeat=20 -// --execution=wasm // --wasm-execution=compiled // --output // pallets/template/src/weights.rs diff --git a/bin/node-template/runtime/src/lib.rs b/bin/node-template/runtime/src/lib.rs index 22fb01b62d0f0..2347d37330be4 100644 --- a/bin/node-template/runtime/src/lib.rs +++ b/bin/node-template/runtime/src/lib.rs @@ -63,7 +63,7 @@ pub type AccountId = <::Signer as IdentifyAccount>::Account pub type Balance = u128; /// Index of a transaction in the chain. -pub type Index = u32; +pub type Nonce = u32; /// A hash of some data used by the chain. pub type Hash = sp_core::H256; @@ -155,6 +155,8 @@ parameter_types! { impl frame_system::Config for Runtime { /// The basic call filter to use in dispatchable. type BaseCallFilter = frame_support::traits::Everything; + /// The block type for the runtime. + type Block = Block; /// Block & extrinsics weights: base values and limits. type BlockWeights = BlockWeights; /// The maximum length of a block (in bytes). @@ -165,16 +167,12 @@ impl frame_system::Config for Runtime { type RuntimeCall = RuntimeCall; /// The lookup mechanism to get account ID from whatever is passed in dispatchers. type Lookup = AccountIdLookup; - /// The index type for storing how many extrinsics an account has signed. - type Index = Index; - /// The index type for blocks. - type BlockNumber = BlockNumber; + /// The type for storing how many extrinsics an account has signed. + type Nonce = Nonce; /// The type for hashing blocks and tries. type Hash = Hash; /// The hashing algorithm used. type Hashing = BlakeTwo256; - /// The header type. - type Header = generic::Header; /// The ubiquitous event type. type RuntimeEvent = RuntimeEvent; /// The ubiquitous origin type. @@ -278,12 +276,7 @@ impl pallet_template::Config for Runtime { // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( - pub struct Runtime - where - Block = Block, - NodeBlock = opaque::Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub struct Runtime { System: frame_system, Timestamp: pallet_timestamp, Aura: pallet_aura, @@ -462,8 +455,8 @@ impl_runtime_apis! { } } - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Index { + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { System::account_nonce(account) } } diff --git a/bin/node/bench/src/construct.rs b/bin/node/bench/src/construct.rs index ec2a829f692a6..4f3ca07f86b9d 100644 --- a/bin/node/bench/src/construct.rs +++ b/bin/node/bench/src/construct.rs @@ -28,7 +28,7 @@ use futures::Future; use std::{borrow::Cow, collections::HashMap, pin::Pin, sync::Arc}; use node_primitives::Block; -use node_testing::bench::{BenchDb, BlockType, DatabaseType, KeyTypes, Profile}; +use node_testing::bench::{BenchDb, BlockType, DatabaseType, KeyTypes}; use sc_transaction_pool_api::{ ImportNotificationStream, PoolFuture, PoolStatus, ReadyTransactions, TransactionFor, TransactionSource, TransactionStatusStreamFor, TxHash, @@ -43,7 +43,6 @@ use crate::{ }; pub struct ConstructionBenchmarkDescription { - pub profile: Profile, pub key_types: KeyTypes, pub block_type: BlockType, pub size: SizeType, @@ -51,7 +50,6 @@ pub struct ConstructionBenchmarkDescription { } pub struct ConstructionBenchmark { - profile: Profile, database: BenchDb, transactions: Transactions, } @@ -60,11 +58,6 @@ impl core::BenchmarkDescription for ConstructionBenchmarkDescription { fn path(&self) -> Path { let mut path = Path::new(&["node", "proposer"]); - match self.profile { - Profile::Wasm => path.push("wasm"), - Profile::Native => path.push("native"), - } - match self.key_types { KeyTypes::Sr25519 => path.push("sr25519"), KeyTypes::Ed25519 => path.push("ed25519"), @@ -99,7 +92,6 @@ impl core::BenchmarkDescription for ConstructionBenchmarkDescription { } Box::new(ConstructionBenchmark { - profile: self.profile, database: bench_db, transactions: Transactions(extrinsics), }) @@ -107,8 +99,8 @@ impl core::BenchmarkDescription for ConstructionBenchmarkDescription { fn name(&self) -> Cow<'static, str> { format!( - "Block construction ({:?}/{}, {:?}, {:?} backend)", - self.block_type, self.size, self.profile, self.database_type, + "Block construction ({:?}/{}, {:?} backend)", + self.block_type, self.size, self.database_type, ) .into() } @@ -116,7 +108,7 @@ impl core::BenchmarkDescription for ConstructionBenchmarkDescription { impl core::Benchmark for ConstructionBenchmark { fn run(&mut self, mode: Mode) -> std::time::Duration { - let context = self.database.create_context(self.profile); + let context = self.database.create_context(); let _ = context .client diff --git a/bin/node/bench/src/import.rs b/bin/node/bench/src/import.rs index 167377ea9a220..78b280076e0bd 100644 --- a/bin/node/bench/src/import.rs +++ b/bin/node/bench/src/import.rs @@ -33,7 +33,7 @@ use std::borrow::Cow; use node_primitives::Block; -use node_testing::bench::{BenchDb, BlockType, DatabaseType, KeyTypes, Profile}; +use node_testing::bench::{BenchDb, BlockType, DatabaseType, KeyTypes}; use sc_client_api::backend::Backend; use sp_state_machine::InspectState; @@ -43,7 +43,6 @@ use crate::{ }; pub struct ImportBenchmarkDescription { - pub profile: Profile, pub key_types: KeyTypes, pub block_type: BlockType, pub size: SizeType, @@ -51,7 +50,6 @@ pub struct ImportBenchmarkDescription { } pub struct ImportBenchmark { - profile: Profile, database: BenchDb, block: Block, block_type: BlockType, @@ -61,11 +59,6 @@ impl core::BenchmarkDescription for ImportBenchmarkDescription { fn path(&self) -> Path { let mut path = Path::new(&["node", "import"]); - match self.profile { - Profile::Wasm => path.push("wasm"), - Profile::Native => path.push("native"), - } - match self.key_types { KeyTypes::Sr25519 => path.push("sr25519"), KeyTypes::Ed25519 => path.push("ed25519"), @@ -88,21 +81,15 @@ impl core::BenchmarkDescription for ImportBenchmarkDescription { } fn setup(self: Box) -> Box { - let profile = self.profile; let mut bench_db = BenchDb::with_key_types(self.database_type, 50_000, self.key_types); let block = bench_db.generate_block(self.block_type.to_content(self.size.transactions())); - Box::new(ImportBenchmark { - database: bench_db, - block_type: self.block_type, - block, - profile, - }) + Box::new(ImportBenchmark { database: bench_db, block_type: self.block_type, block }) } fn name(&self) -> Cow<'static, str> { format!( - "Block import ({:?}/{}, {:?}, {:?} backend)", - self.block_type, self.size, self.profile, self.database_type, + "Block import ({:?}/{}, {:?} backend)", + self.block_type, self.size, self.database_type, ) .into() } @@ -110,7 +97,7 @@ impl core::BenchmarkDescription for ImportBenchmarkDescription { impl core::Benchmark for ImportBenchmark { fn run(&mut self, mode: Mode) -> std::time::Duration { - let mut context = self.database.create_context(self.profile); + let mut context = self.database.create_context(); let _ = context .client diff --git a/bin/node/bench/src/main.rs b/bin/node/bench/src/main.rs index 051d8ddb9bf55..1f69c97695801 100644 --- a/bin/node/bench/src/main.rs +++ b/bin/node/bench/src/main.rs @@ -30,7 +30,7 @@ mod txpool; use clap::Parser; -use node_testing::bench::{BlockType, DatabaseType as BenchDataBaseType, KeyTypes, Profile}; +use node_testing::bench::{BlockType, DatabaseType as BenchDataBaseType, KeyTypes}; use crate::{ common::SizeType, @@ -85,31 +85,28 @@ fn main() { let mut import_benchmarks = Vec::new(); - for profile in [Profile::Wasm, Profile::Native] { - for size in [ - SizeType::Empty, - SizeType::Small, - SizeType::Medium, - SizeType::Large, - SizeType::Full, - SizeType::Custom(opt.transactions.unwrap_or(0)), + for size in [ + SizeType::Empty, + SizeType::Small, + SizeType::Medium, + SizeType::Large, + SizeType::Full, + SizeType::Custom(opt.transactions.unwrap_or(0)), + ] { + for block_type in [ + BlockType::RandomTransfersKeepAlive, + BlockType::RandomTransfersReaping, + BlockType::Noop, ] { - for block_type in [ - BlockType::RandomTransfersKeepAlive, - BlockType::RandomTransfersReaping, - BlockType::Noop, - ] { - for database_type in [BenchDataBaseType::RocksDb, BenchDataBaseType::ParityDb] { - import_benchmarks.push((profile, size, block_type, database_type)); - } + for database_type in [BenchDataBaseType::RocksDb, BenchDataBaseType::ParityDb] { + import_benchmarks.push((size, block_type, database_type)); } } } let benchmarks = matrix!( - (profile, size, block_type, database_type) in import_benchmarks.into_iter() => + (size, block_type, database_type) in import_benchmarks.into_iter() => ImportBenchmarkDescription { - profile, key_types: KeyTypes::Sr25519, size, block_type, @@ -138,14 +135,12 @@ fn main() { .iter().map(move |db_type| (size, db_type))) => TrieWriteBenchmarkDescription { database_size: *size, database_type: *db_type }, ConstructionBenchmarkDescription { - profile: Profile::Wasm, key_types: KeyTypes::Sr25519, block_type: BlockType::RandomTransfersKeepAlive, size: SizeType::Medium, database_type: BenchDataBaseType::RocksDb, }, ConstructionBenchmarkDescription { - profile: Profile::Wasm, key_types: KeyTypes::Sr25519, block_type: BlockType::RandomTransfersKeepAlive, size: SizeType::Large, diff --git a/bin/node/bench/src/txpool.rs b/bin/node/bench/src/txpool.rs index 4e8e5c0d9a4fd..a3524ac5bc890 100644 --- a/bin/node/bench/src/txpool.rs +++ b/bin/node/bench/src/txpool.rs @@ -23,7 +23,7 @@ use std::borrow::Cow; -use node_testing::bench::{BenchDb, BlockType, DatabaseType, KeyTypes, Profile}; +use node_testing::bench::{BenchDb, BlockType, DatabaseType, KeyTypes}; use sc_transaction_pool::BasicPool; use sc_transaction_pool_api::{TransactionPool, TransactionSource}; @@ -57,7 +57,7 @@ impl core::BenchmarkDescription for PoolBenchmarkDescription { impl core::Benchmark for PoolBenchmark { fn run(&mut self, mode: Mode) -> std::time::Duration { - let context = self.database.create_context(Profile::Wasm); + let context = self.database.create_context(); let _ = context .client diff --git a/bin/node/cli/Cargo.toml b/bin/node/cli/Cargo.toml index d9b3ebee995d8..032ba271f3c81 100644 --- a/bin/node/cli/Cargo.toml +++ b/bin/node/cli/Cargo.toml @@ -83,6 +83,7 @@ sc-authority-discovery = { version = "0.10.0-dev", path = "../../../client/autho sc-sync-state-rpc = { version = "0.10.0-dev", path = "../../../client/sync-state-rpc" } sc-sysinfo = { version = "6.0.0-dev", path = "../../../client/sysinfo" } sc-storage-monitor = { version = "0.1.0", path = "../../../client/storage-monitor" } +sc-offchain = { version = "4.0.0-dev", path = "../../../client/offchain" } # frame dependencies frame-system = { version = "4.0.0-dev", path = "../../../frame/system" } diff --git a/bin/node/cli/benches/block_production.rs b/bin/node/cli/benches/block_production.rs index 527b145c62c46..5ee538d18d6a8 100644 --- a/bin/node/cli/benches/block_production.rs +++ b/bin/node/cli/benches/block_production.rs @@ -21,7 +21,6 @@ use criterion::{criterion_group, criterion_main, BatchSize, Criterion, Throughpu use kitchensink_runtime::{constants::currency::*, BalancesCall}; use node_cli::service::{create_extrinsic, FullClient}; use sc_block_builder::{BlockBuilderProvider, BuiltBlock, RecordProof}; -use sc_client_api::execution_extensions::ExecutionStrategies; use sc_consensus::{ block_import::{BlockImportParams, ForkChoiceStrategy}, BlockImport, StateAction, @@ -56,9 +55,6 @@ fn new_node(tokio_handle: Handle) -> node_cli::service::NewFullBase { let spec = Box::new(node_cli::chain_spec::development_config()); - // NOTE: We enforce the use of the WASM runtime to benchmark block production using WASM. - let execution_strategy = sc_client_api::ExecutionStrategy::AlwaysWasm; - let config = Configuration { impl_name: "BenchmarkImpl".into(), impl_version: "1.0".into(), @@ -77,13 +73,6 @@ fn new_node(tokio_handle: Handle) -> node_cli::service::NewFullBase { wasm_method: WasmExecutionMethod::Compiled { instantiation_strategy: WasmtimeInstantiationStrategy::PoolingCopyOnWrite, }, - execution_strategies: ExecutionStrategies { - syncing: execution_strategy, - importing: execution_strategy, - block_construction: execution_strategy, - offchain_worker: execution_strategy, - other: execution_strategy, - }, rpc_addr: None, rpc_max_connections: Default::default(), rpc_cors: None, diff --git a/bin/node/cli/benches/transaction_pool.rs b/bin/node/cli/benches/transaction_pool.rs index 44ebe1e7d4fe6..d3e8c02a958f7 100644 --- a/bin/node/cli/benches/transaction_pool.rs +++ b/bin/node/cli/benches/transaction_pool.rs @@ -23,7 +23,6 @@ use futures::{future, StreamExt}; use kitchensink_runtime::{constants::currency::*, BalancesCall, SudoCall}; use node_cli::service::{create_extrinsic, fetch_nonce, FullClient, TransactionPool}; use node_primitives::AccountId; -use sc_client_api::execution_extensions::ExecutionStrategies; use sc_service::{ config::{ BlocksPruning, DatabaseSource, KeystoreConfig, NetworkConfiguration, OffchainWorkerConfig, @@ -70,14 +69,6 @@ fn new_node(tokio_handle: Handle) -> node_cli::service::NewFullBase { blocks_pruning: BlocksPruning::KeepAll, chain_spec: spec, wasm_method: Default::default(), - // NOTE: we enforce the use of the native runtime to make the errors more debuggable - execution_strategies: ExecutionStrategies { - syncing: sc_client_api::ExecutionStrategy::NativeWhenPossible, - importing: sc_client_api::ExecutionStrategy::NativeWhenPossible, - block_construction: sc_client_api::ExecutionStrategy::NativeWhenPossible, - offchain_worker: sc_client_api::ExecutionStrategy::NativeWhenPossible, - other: sc_client_api::ExecutionStrategy::NativeWhenPossible, - }, rpc_addr: None, rpc_max_connections: Default::default(), rpc_cors: None, diff --git a/bin/node/cli/src/chain_spec.rs b/bin/node/cli/src/chain_spec.rs index ebbda8baabd8b..a56c4e7b4016e 100644 --- a/bin/node/cli/src/chain_spec.rs +++ b/bin/node/cli/src/chain_spec.rs @@ -20,11 +20,10 @@ use grandpa_primitives::AuthorityId as GrandpaId; use kitchensink_runtime::{ - constants::currency::*, wasm_binary_unwrap, AuthorityDiscoveryConfig, BabeConfig, - BalancesConfig, Block, CouncilConfig, DemocracyConfig, ElectionsConfig, GluttonConfig, - GrandpaConfig, ImOnlineConfig, IndicesConfig, MaxNominations, NominationPoolsConfig, - SessionConfig, SessionKeys, SocietyConfig, StakerStatus, StakingConfig, SudoConfig, - SystemConfig, TechnicalCommitteeConfig, + constants::currency::*, wasm_binary_unwrap, BabeConfig, BalancesConfig, Block, CouncilConfig, + DemocracyConfig, ElectionsConfig, ImOnlineConfig, IndicesConfig, MaxNominations, + NominationPoolsConfig, SessionConfig, SessionKeys, SocietyConfig, StakerStatus, StakingConfig, + SudoConfig, SystemConfig, TechnicalCommitteeConfig, }; use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use sc_chain_spec::ChainSpecExtension; @@ -295,7 +294,7 @@ pub fn testnet_genesis( const STASH: Balance = ENDOWMENT / 1000; RuntimeGenesisConfig { - system: SystemConfig { code: wasm_binary_unwrap().to_vec() }, + system: SystemConfig { code: wasm_binary_unwrap().to_vec(), ..Default::default() }, balances: BalancesConfig { balances: endowed_accounts.iter().cloned().map(|x| (x, ENDOWMENT)).collect(), }, @@ -340,12 +339,12 @@ pub fn testnet_genesis( }, sudo: SudoConfig { key: Some(root_key) }, babe: BabeConfig { - authorities: vec![], epoch_config: Some(kitchensink_runtime::BABE_GENESIS_EPOCH_CONFIG), + ..Default::default() }, im_online: ImOnlineConfig { keys: vec![] }, - authority_discovery: AuthorityDiscoveryConfig { keys: vec![] }, - grandpa: GrandpaConfig { authorities: vec![] }, + authority_discovery: Default::default(), + grandpa: Default::default(), technical_membership: Default::default(), treasury: Default::default(), society: SocietyConfig { pot: 0 }, @@ -365,11 +364,7 @@ pub fn testnet_genesis( min_join_bond: 1 * DOLLARS, ..Default::default() }, - glutton: GluttonConfig { - compute: Default::default(), - storage: Default::default(), - trash_data_count: Default::default(), - }, + glutton: Default::default(), } } diff --git a/bin/node/cli/src/service.rs b/bin/node/cli/src/service.rs index 81f4575384473..487c6c48f0061 100644 --- a/bin/node/cli/src/service.rs +++ b/bin/node/cli/src/service.rs @@ -28,7 +28,7 @@ use futures::prelude::*; use kitchensink_runtime::RuntimeApi; use node_executor::ExecutorDispatch; use node_primitives::Block; -use sc_client_api::BlockBackend; +use sc_client_api::{Backend, BlockBackend}; use sc_consensus_babe::{self, SlotProportion}; use sc_executor::NativeElseWasmExecutor; use sc_network::{event::Event, NetworkEventStream, NetworkService}; @@ -37,6 +37,7 @@ use sc_network_sync::SyncingService; use sc_service::{config::Configuration, error::Error as ServiceError, RpcHandlers, TaskManager}; use sc_statement_store::Store as StatementStore; use sc_telemetry::{Telemetry, TelemetryWorker}; +use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sp_api::ProvideRuntimeApi; use sp_core::crypto::Pair; use sp_runtime::{generic, traits::Block as BlockT, SaturatedConversion}; @@ -205,27 +206,29 @@ pub fn new_partial( )?; let slot_duration = babe_link.config().slot_duration(); - let (import_queue, babe_worker_handle) = sc_consensus_babe::import_queue( - babe_link.clone(), - block_import.clone(), - Some(Box::new(justification_import)), - client.clone(), - select_chain.clone(), - move |_, ()| async move { - let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); + let (import_queue, babe_worker_handle) = + sc_consensus_babe::import_queue(sc_consensus_babe::ImportQueueParams { + link: babe_link.clone(), + block_import: block_import.clone(), + justification_import: Some(Box::new(justification_import)), + client: client.clone(), + select_chain: select_chain.clone(), + create_inherent_data_providers: move |_, ()| async move { + let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); - let slot = + let slot = sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_slot_duration( *timestamp, slot_duration, ); - Ok((slot, timestamp)) - }, - &task_manager.spawn_essential_handle(), - config.prometheus_registry(), - telemetry.as_ref().map(|x| x.handle()), - )?; + Ok((slot, timestamp)) + }, + spawner: &task_manager.spawn_essential_handle(), + registry: config.prometheus_registry(), + telemetry: telemetry.as_ref().map(|x| x.handle()), + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(transaction_pool.clone()), + })?; let import_setup = (block_import, grandpa_link, babe_link); @@ -278,9 +281,10 @@ pub fn new_partial( finality_provider: finality_proof_provider.clone(), }, statement_store: rpc_statement_store.clone(), + backend: rpc_backend.clone(), }; - node_rpc::create_full(deps, rpc_backend.clone()).map_err(Into::into) + node_rpc::create_full(deps).map_err(Into::into) }; (rpc_extensions_builder, shared_voter_state2) @@ -381,15 +385,6 @@ pub fn new_full_base( warp_sync_params: Some(WarpSyncParams::WithProvider(warp_sync)), })?; - if config.offchain_worker.enabled { - sc_service::build_offchain_workers( - &config, - task_manager.spawn_handle(), - client.clone(), - network.clone(), - ); - } - let role = config.role.clone(); let force_authoring = config.force_authoring; let backoff_authoring_blocks = @@ -397,10 +392,11 @@ pub fn new_full_base( let name = config.network.node_name.clone(); let enable_grandpa = !config.disable_grandpa; let prometheus_registry = config.prometheus_registry().cloned(); + let enable_offchain_worker = config.offchain_worker.enabled; let rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams { config, - backend, + backend: backend.clone(), client: client.clone(), keystore: keystore_container.keystore(), network: network.clone(), @@ -525,14 +521,14 @@ pub fn new_full_base( // need a keystore, regardless of which protocol we use below. let keystore = if role.is_authority() { Some(keystore_container.keystore()) } else { None }; - let config = grandpa::Config { + let grandpa_config = grandpa::Config { // FIXME #1578 make this available through chainspec gossip_duration: std::time::Duration::from_millis(333), justification_period: 512, name: Some(name), observer_enabled: false, keystore, - local_role: role, + local_role: role.clone(), telemetry: telemetry.as_ref().map(|x| x.handle()), protocol_name: grandpa_protocol_name, }; @@ -545,7 +541,7 @@ pub fn new_full_base( // been tested extensively yet and having most nodes in a network run it // could lead to finality stalls. let grandpa_config = grandpa::GrandpaParams { - config, + config: grandpa_config, link: grandpa_link, network: network.clone(), sync: Arc::new(sync_service.clone()), @@ -553,6 +549,7 @@ pub fn new_full_base( voting_rule: grandpa::VotingRulesBuilder::default().build(), prometheus_registry: prometheus_registry.clone(), shared_voter_state, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(transaction_pool.clone()), }; // the GRANDPA voter task is considered infallible, i.e. @@ -584,6 +581,29 @@ pub fn new_full_base( statement_handler.run(), ); + if enable_offchain_worker { + task_manager.spawn_handle().spawn( + "offchain-workers-runner", + "offchain-work", + sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions { + runtime_api_provider: client.clone(), + keystore: Some(keystore_container.keystore()), + offchain_db: backend.offchain_storage(), + transaction_pool: Some(OffchainTransactionPoolFactory::new( + transaction_pool.clone(), + )), + network_provider: network.clone(), + is_validator: role.is_authority(), + enable_http_requests: true, + custom_extensions: move |_| { + vec![Box::new(statement_store.clone().as_statement_store_ext()) as Box<_>] + }, + }) + .run(client.clone(), task_manager.spawn_handle()) + .boxed(), + ); + } + network_starter.start_network(); Ok(NewFullBase { task_manager, diff --git a/bin/node/cli/tests/benchmark_block_works.rs b/bin/node/cli/tests/benchmark_block_works.rs index 50103a66a4d40..09c2f262e2c29 100644 --- a/bin/node/cli/tests/benchmark_block_works.rs +++ b/bin/node/cli/tests/benchmark_block_works.rs @@ -39,7 +39,7 @@ async fn benchmark_block_works() { .arg(base_dir.path()) .args(["--from", "1", "--to", "1"]) .args(["--repeat", "1"]) - .args(["--execution", "wasm", "--wasm-execution", "compiled"]) + .args(["--wasm-execution", "compiled"]) .status() .unwrap(); diff --git a/bin/node/executor/tests/basic.rs b/bin/node/executor/tests/basic.rs index d301aa06f90b0..a2f46e9fdbe99 100644 --- a/bin/node/executor/tests/basic.rs +++ b/bin/node/executor/tests/basic.rs @@ -183,7 +183,7 @@ fn panic_execution_with_foreign_code_gives_error() { let mut t = new_test_ext(bloaty_code_unwrap()); t.insert( >::hashed_key_for(alice()), - AccountInfo::<::Index, _> { + AccountInfo::<::Nonce, _> { providers: 1, data: (69u128, 0u128, 0u128, 1u128 << 127), ..Default::default() @@ -209,7 +209,7 @@ fn bad_extrinsic_with_native_equivalent_code_gives_error() { let mut t = new_test_ext(compact_code_unwrap()); t.insert( >::hashed_key_for(alice()), - AccountInfo::<::Index, _> { + AccountInfo::<::Nonce, _> { providers: 1, data: (69u128, 0u128, 0u128, 1u128 << 127), ..Default::default() @@ -235,7 +235,7 @@ fn successful_execution_with_native_equivalent_code_gives_ok() { let mut t = new_test_ext(compact_code_unwrap()); t.insert( >::hashed_key_for(alice()), - AccountInfo::<::Index, _> { + AccountInfo::<::Nonce, _> { providers: 1, data: (111 * DOLLARS, 0u128, 0u128, 1u128 << 127), ..Default::default() @@ -245,7 +245,7 @@ fn successful_execution_with_native_equivalent_code_gives_ok() { t.insert( >::hashed_key_for(bob()), AccountInfo::< - ::Index, + ::Nonce, ::AccountData, >::default() .encode(), @@ -277,7 +277,7 @@ fn successful_execution_with_foreign_code_gives_ok() { let mut t = new_test_ext(bloaty_code_unwrap()); t.insert( >::hashed_key_for(alice()), - AccountInfo::<::Index, _> { + AccountInfo::<::Nonce, _> { providers: 1, data: (111 * DOLLARS, 0u128, 0u128, 1u128 << 127), ..Default::default() @@ -287,7 +287,7 @@ fn successful_execution_with_foreign_code_gives_ok() { t.insert( >::hashed_key_for(bob()), AccountInfo::< - ::Index, + ::Nonce, ::AccountData, >::default() .encode(), @@ -766,7 +766,7 @@ fn panic_execution_gives_error() { let mut t = new_test_ext(bloaty_code_unwrap()); t.insert( >::hashed_key_for(alice()), - AccountInfo::<::Index, _> { + AccountInfo::<::Nonce, _> { data: (0 * DOLLARS, 0u128, 0u128, 0u128), ..Default::default() } @@ -795,7 +795,7 @@ fn successful_execution_gives_ok() { let mut t = new_test_ext(compact_code_unwrap()); t.insert( >::hashed_key_for(alice()), - AccountInfo::<::Index, _> { + AccountInfo::<::Nonce, _> { providers: 1, data: (111 * DOLLARS, 0u128, 0u128, 1u128 << 127), ..Default::default() @@ -805,7 +805,7 @@ fn successful_execution_gives_ok() { t.insert( >::hashed_key_for(bob()), AccountInfo::< - ::Index, + ::Nonce, ::AccountData, >::default() .encode(), diff --git a/bin/node/executor/tests/fees.rs b/bin/node/executor/tests/fees.rs index 970d790a87d3b..7519ce6e8b1b4 100644 --- a/bin/node/executor/tests/fees.rs +++ b/bin/node/executor/tests/fees.rs @@ -196,7 +196,7 @@ fn transaction_fee_is_correct() { fn block_weight_capacity_report() { // Just report how many transfer calls you could fit into a block. The number should at least // be a few hundred (250 at the time of writing but can change over time). Runs until panic. - use node_primitives::Index; + use node_primitives::Nonce; // execution ext. let mut t = new_test_ext(compact_code_unwrap()); @@ -205,7 +205,7 @@ fn block_weight_capacity_report() { let factor = 50; let mut time = 10; - let mut nonce: Index = 0; + let mut nonce: Nonce = 0; let mut block_number = 1; let mut previous_hash: node_primitives::Hash = GENESIS_HASH.into(); @@ -213,7 +213,7 @@ fn block_weight_capacity_report() { let num_transfers = block_number * factor; let mut xts = (0..num_transfers) .map(|i| CheckedExtrinsic { - signed: Some((charlie(), signed_extra(nonce + i as Index, 0))), + signed: Some((charlie(), signed_extra(nonce + i as Nonce, 0))), function: RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { dest: bob().into(), value: 0, @@ -266,7 +266,7 @@ fn block_length_capacity_report() { // Just report how big a block can get. Executes until panic. Should be ignored unless if // manually inspected. The number should at least be a few megabytes (5 at the time of // writing but can change over time). - use node_primitives::Index; + use node_primitives::Nonce; // execution ext. let mut t = new_test_ext(compact_code_unwrap()); @@ -275,7 +275,7 @@ fn block_length_capacity_report() { let factor = 256 * 1024; let mut time = 10; - let mut nonce: Index = 0; + let mut nonce: Nonce = 0; let mut block_number = 1; let mut previous_hash: node_primitives::Hash = GENESIS_HASH.into(); diff --git a/bin/node/primitives/src/lib.rs b/bin/node/primitives/src/lib.rs index e2fa5c3108149..24a67cbdd8f78 100644 --- a/bin/node/primitives/src/lib.rs +++ b/bin/node/primitives/src/lib.rs @@ -46,7 +46,7 @@ pub type Balance = u128; pub type Moment = u64; /// Index of a transaction in the chain. -pub type Index = u32; +pub type Nonce = u32; /// A hash of some data used by the chain. pub type Hash = sp_core::H256; diff --git a/bin/node/rpc/src/lib.rs b/bin/node/rpc/src/lib.rs index 5ab96bf1c7064..a2ae46904dbfc 100644 --- a/bin/node/rpc/src/lib.rs +++ b/bin/node/rpc/src/lib.rs @@ -34,7 +34,7 @@ use std::sync::Arc; use jsonrpsee::RpcModule; -use node_primitives::{AccountId, Balance, Block, BlockNumber, Hash, Index}; +use node_primitives::{AccountId, Balance, Block, BlockNumber, Hash, Nonce}; use sc_client_api::AuxStore; use sc_consensus_babe::BabeWorkerHandle; use sc_consensus_grandpa::{ @@ -90,12 +90,23 @@ pub struct FullDeps { pub grandpa: GrandpaDeps, /// Shared statement store reference. pub statement_store: Arc, + /// The backend used by the node. + pub backend: Arc, } /// Instantiate all Full RPC extensions. pub fn create_full( - deps: FullDeps, - backend: Arc, + FullDeps { + client, + pool, + select_chain, + chain_spec, + deny_unsafe, + babe, + grandpa, + statement_store, + backend, + }: FullDeps, ) -> Result, Box> where C: ProvideRuntimeApi @@ -106,7 +117,7 @@ where + Sync + Send + 'static, - C::Api: substrate_frame_rpc_system::AccountNonceApi, + C::Api: substrate_frame_rpc_system::AccountNonceApi, C::Api: mmr_rpc::MmrRuntimeApi::Hash, BlockNumber>, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, C::Api: BabeApi, @@ -130,16 +141,6 @@ where use substrate_state_trie_migration_rpc::{StateMigration, StateMigrationApiServer}; let mut io = RpcModule::new(()); - let FullDeps { - client, - pool, - select_chain, - chain_spec, - deny_unsafe, - babe, - grandpa, - statement_store, - } = deps; let BabeDeps { keystore, babe_worker_handle } = babe; let GrandpaDeps { @@ -159,7 +160,15 @@ where // Making synchronous calls in light client freezes the browser currently, // more context: https://github.com/paritytech/substrate/pull/3480 // These RPCs should use an asynchronous caller instead. - io.merge(Mmr::new(client.clone()).into_rpc())?; + io.merge( + Mmr::new( + client.clone(), + backend + .offchain_storage() + .ok_or_else(|| "Backend doesn't provide an offchain storage")?, + ) + .into_rpc(), + )?; io.merge(TransactionPayment::new(client.clone()).into_rpc())?; io.merge( Babe::new(client.clone(), babe_worker_handle.clone(), keystore, select_chain, deny_unsafe) diff --git a/bin/node/runtime/src/impls.rs b/bin/node/runtime/src/impls.rs index 8c4a1ed4bbda2..430a1ac2824b8 100644 --- a/bin/node/runtime/src/impls.rs +++ b/bin/node/runtime/src/impls.rs @@ -120,7 +120,7 @@ mod multiplier_tests { use sp_runtime::{ assert_eq_error_rate, traits::{Convert, One, Zero}, - FixedPointNumber, + BuildStorage, FixedPointNumber, }; use crate::{ @@ -197,8 +197,8 @@ mod multiplier_tests { where F: Fn() -> (), { - let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::default() - .build_storage::() + let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::::default() + .build_storage() .unwrap() .into(); t.execute_with(|| { diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 058f43dad00b1..6a093996e8e52 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -53,7 +53,7 @@ use frame_system::{ EnsureRoot, EnsureRootWithSuccess, EnsureSigned, EnsureSignedBy, EnsureWithSuccess, }; pub use node_primitives::{AccountId, Signature}; -use node_primitives::{AccountIndex, Balance, BlockNumber, Hash, Index, Moment}; +use node_primitives::{AccountIndex, Balance, BlockNumber, Hash, Moment, Nonce}; use pallet_asset_conversion::{NativeOrAssetId, NativeOrAssetIdConverter}; #[cfg(feature = "runtime-benchmarks")] use pallet_contracts::NoopMigration; @@ -226,13 +226,12 @@ impl frame_system::Config for Runtime { type DbWeight = RocksDbWeight; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = Index; - type BlockNumber = BlockNumber; + type Nonce = Nonce; type Hash = Hash; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = Indices; - type Header = generic::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type Version = Version; @@ -1280,7 +1279,7 @@ where call: RuntimeCall, public: ::Signer, account: AccountId, - nonce: Index, + nonce: Nonce, ) -> Option<(RuntimeCall, ::SignaturePayload)> { let tip = 0; // take the biggest period possible. @@ -1868,10 +1867,7 @@ impl pallet_statement::Config for Runtime { } construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = node_primitives::Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system, Utility: pallet_utility, @@ -2258,8 +2254,8 @@ impl_runtime_apis! { } } - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Index { + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { System::account_nonce(account) } } diff --git a/bin/node/testing/src/bench.rs b/bin/node/testing/src/bench.rs index 9708b2c343263..f1ab2212239b1 100644 --- a/bin/node/testing/src/bench.rs +++ b/bin/node/testing/src/bench.rs @@ -40,17 +40,14 @@ use kitchensink_runtime::{ }; use node_primitives::Block; use sc_block_builder::BlockBuilderProvider; -use sc_client_api::{ - execution_extensions::{ExecutionExtensions, ExecutionStrategies}, - ExecutionStrategy, -}; +use sc_client_api::execution_extensions::ExecutionExtensions; use sc_client_db::PruningMode; use sc_consensus::{BlockImport, BlockImportParams, ForkChoiceStrategy, ImportResult, ImportedAux}; use sc_executor::{NativeElseWasmExecutor, WasmExecutionMethod, WasmtimeInstantiationStrategy}; use sp_api::ProvideRuntimeApi; use sp_block_builder::BlockBuilder; use sp_consensus::BlockOrigin; -use sp_core::{blake2_256, ed25519, sr25519, traits::SpawnNamed, ExecutionContext, Pair, Public}; +use sp_core::{blake2_256, ed25519, sr25519, traits::SpawnNamed, Pair, Public}; use sp_inherents::InherentData; use sp_runtime::{ traits::{Block as BlockT, IdentifyAccount, Verify}, @@ -354,7 +351,7 @@ impl BenchDb { dir.path().to_string_lossy(), ); let (_client, _backend, _task_executor) = - Self::bench_client(database_type, dir.path(), Profile::Native, &keyring); + Self::bench_client(database_type, dir.path(), &keyring); let directory_guard = Guard(dir); BenchDb { keyring, directory_guard, database_type } @@ -380,7 +377,6 @@ impl BenchDb { fn bench_client( database_type: DatabaseType, dir: &std::path::Path, - profile: Profile, keyring: &BenchKeyring, ) -> (Client, std::sync::Arc, TaskExecutor) { let db_config = sc_client_db::DatabaseSettings { @@ -415,12 +411,7 @@ impl BenchDb { genesis_block_builder, None, None, - ExecutionExtensions::new( - profile.into_execution_strategies(), - None, - None, - Arc::new(executor), - ), + ExecutionExtensions::new(None, Arc::new(executor)), Box::new(task_executor.clone()), None, None, @@ -444,11 +435,7 @@ impl BenchDb { client .runtime_api() - .inherent_extrinsics_with_context( - client.chain_info().genesis_hash, - ExecutionContext::BlockConstruction, - inherent_data, - ) + .inherent_extrinsics(client.chain_info().genesis_hash, inherent_data) .expect("Get inherents failed") } @@ -459,12 +446,8 @@ impl BenchDb { /// Get cliet for this database operations. pub fn client(&mut self) -> Client { - let (client, _backend, _task_executor) = Self::bench_client( - self.database_type, - self.directory_guard.path(), - Profile::Wasm, - &self.keyring, - ); + let (client, _backend, _task_executor) = + Self::bench_client(self.database_type, self.directory_guard.path(), &self.keyring); client } @@ -507,10 +490,10 @@ impl BenchDb { } /// Clone this database and create context for testing/benchmarking. - pub fn create_context(&self, profile: Profile) -> BenchContext { + pub fn create_context(&self) -> BenchContext { let BenchDb { directory_guard, keyring, database_type } = self.clone(); let (client, backend, task_executor) = - Self::bench_client(database_type, directory_guard.path(), profile, &keyring); + Self::bench_client(database_type, directory_guard.path(), &keyring); BenchContext { client: Arc::new(client), @@ -611,36 +594,6 @@ impl BenchKeyring { } } -/// Profile for exetion strategies. -#[derive(Clone, Copy, Debug)] -pub enum Profile { - /// As native as possible. - Native, - /// As wasm as possible. - Wasm, -} - -impl Profile { - fn into_execution_strategies(self) -> ExecutionStrategies { - match self { - Profile::Wasm => ExecutionStrategies { - syncing: ExecutionStrategy::AlwaysWasm, - importing: ExecutionStrategy::AlwaysWasm, - block_construction: ExecutionStrategy::AlwaysWasm, - offchain_worker: ExecutionStrategy::AlwaysWasm, - other: ExecutionStrategy::AlwaysWasm, - }, - Profile::Native => ExecutionStrategies { - syncing: ExecutionStrategy::NativeElseWasm, - importing: ExecutionStrategy::NativeElseWasm, - block_construction: ExecutionStrategy::NativeElseWasm, - offchain_worker: ExecutionStrategy::NativeElseWasm, - other: ExecutionStrategy::NativeElseWasm, - }, - } - } -} - struct Guard(tempfile::TempDir); impl Guard { diff --git a/bin/node/testing/src/genesis.rs b/bin/node/testing/src/genesis.rs index 0514899dfbab8..8063b8ef45708 100644 --- a/bin/node/testing/src/genesis.rs +++ b/bin/node/testing/src/genesis.rs @@ -50,6 +50,7 @@ pub fn config_endowed(code: Option<&[u8]>, extra_endowed: Vec) -> Run RuntimeGenesisConfig { system: SystemConfig { code: code.map(|x| x.to_vec()).unwrap_or_else(|| wasm_binary_unwrap().to_vec()), + ..Default::default() }, indices: IndicesConfig { indices: vec![] }, balances: BalancesConfig { balances: endowed }, @@ -76,8 +77,12 @@ pub fn config_endowed(code: Option<&[u8]>, extra_endowed: Vec) -> Run invulnerables: vec![alice(), bob(), charlie()], ..Default::default() }, - babe: BabeConfig { authorities: vec![], epoch_config: Some(BABE_GENESIS_EPOCH_CONFIG) }, - grandpa: GrandpaConfig { authorities: vec![] }, + babe: BabeConfig { + authorities: vec![], + epoch_config: Some(BABE_GENESIS_EPOCH_CONFIG), + ..Default::default() + }, + grandpa: GrandpaConfig { authorities: vec![], _config: Default::default() }, im_online: Default::default(), authority_discovery: Default::default(), democracy: Default::default(), @@ -100,6 +105,7 @@ pub fn config_endowed(code: Option<&[u8]>, extra_endowed: Vec) -> Run compute: Default::default(), storage: Default::default(), trash_data_count: Default::default(), + ..Default::default() }, } } diff --git a/bin/node/testing/src/keyring.rs b/bin/node/testing/src/keyring.rs index c3f8d8e6d9485..b4b714d9083d6 100644 --- a/bin/node/testing/src/keyring.rs +++ b/bin/node/testing/src/keyring.rs @@ -20,7 +20,7 @@ use codec::Encode; use kitchensink_runtime::{CheckedExtrinsic, SessionKeys, SignedExtra, UncheckedExtrinsic}; -use node_primitives::{AccountId, Balance, Index}; +use node_primitives::{AccountId, Balance, Nonce}; use sp_keyring::{AccountKeyring, Ed25519Keyring, Sr25519Keyring}; use sp_runtime::generic::Era; @@ -68,7 +68,7 @@ pub fn to_session_keys( } /// Returns transaction extra. -pub fn signed_extra(nonce: Index, extra_fee: Balance) -> SignedExtra { +pub fn signed_extra(nonce: Nonce, extra_fee: Balance) -> SignedExtra { ( frame_system::CheckNonZeroSender::new(), frame_system::CheckSpecVersion::new(), diff --git a/client/api/Cargo.toml b/client/api/Cargo.toml index be47c2931abbd..17f9747c39bc1 100644 --- a/client/api/Cargo.toml +++ b/client/api/Cargo.toml @@ -31,7 +31,6 @@ sp-consensus = { version = "0.10.0-dev", path = "../../primitives/consensus/comm sp-core = { version = "21.0.0", default-features = false, path = "../../primitives/core" } sp-database = { version = "4.0.0-dev", path = "../../primitives/database" } sp-externalities = { version = "0.19.0", path = "../../primitives/externalities" } -sp-keystore = { version = "0.27.0", default-features = false, path = "../../primitives/keystore" } sp-runtime = { version = "24.0.0", default-features = false, path = "../../primitives/runtime" } sp-state-machine = { version = "0.28.0", path = "../../primitives/state-machine" } sp-statement-store = { version = "4.0.0-dev", path = "../../primitives/statement-store" } diff --git a/client/api/src/call_executor.rs b/client/api/src/call_executor.rs index db8e4d8495af2..cecc1053d1b9d 100644 --- a/client/api/src/call_executor.rs +++ b/client/api/src/call_executor.rs @@ -20,12 +20,13 @@ use sc_executor::{RuntimeVersion, RuntimeVersionOf}; use sp_core::traits::CallContext; +use sp_externalities::Extensions; use sp_runtime::traits::Block as BlockT; -use sp_state_machine::{ExecutionStrategy, OverlayedChanges, StorageProof}; +use sp_state_machine::{OverlayedChanges, StorageProof}; use std::cell::RefCell; use crate::execution_extensions::ExecutionExtensions; -use sp_api::{ExecutionContext, ProofRecorder, StorageTransactionCache}; +use sp_api::{ProofRecorder, StorageTransactionCache}; /// Executor Provider pub trait ExecutorProvider { @@ -58,7 +59,6 @@ pub trait CallExecutor: RuntimeVersionOf { at_hash: B::Hash, method: &str, call_data: &[u8], - strategy: ExecutionStrategy, context: CallContext, ) -> Result, sp_blockchain::Error>; @@ -79,7 +79,8 @@ pub trait CallExecutor: RuntimeVersionOf { >, >, proof_recorder: &Option>, - context: ExecutionContext, + call_context: CallContext, + extensions: &RefCell, ) -> sp_blockchain::Result>; /// Extract RuntimeVersion of given block diff --git a/client/api/src/execution_extensions.rs b/client/api/src/execution_extensions.rs index 20dc34d19b1de..6f927105df0bf 100644 --- a/client/api/src/execution_extensions.rs +++ b/client/api/src/execution_extensions.rs @@ -23,48 +23,10 @@ //! extensions to support APIs for particular execution context & capabilities. use parking_lot::RwLock; -use sc_transaction_pool_api::OffchainTransactionPoolFactory; -use sp_core::{ - offchain::{self, OffchainDbExt, OffchainWorkerExt}, - traits::{ReadRuntimeVersion, ReadRuntimeVersionExt}, - ExecutionContext, -}; +use sp_core::traits::{ReadRuntimeVersion, ReadRuntimeVersionExt}; use sp_externalities::{Extension, Extensions}; -use sp_keystore::{KeystoreExt, KeystorePtr}; use sp_runtime::traits::{Block as BlockT, NumberFor}; -pub use sp_state_machine::ExecutionStrategy; -use sp_state_machine::{DefaultHandler, ExecutionManager}; -use std::{ - marker::PhantomData, - sync::{Arc, Weak}, -}; - -/// Execution strategies settings. -#[derive(Debug, Clone)] -pub struct ExecutionStrategies { - /// Execution strategy used when syncing. - pub syncing: ExecutionStrategy, - /// Execution strategy used when importing blocks. - pub importing: ExecutionStrategy, - /// Execution strategy used when constructing blocks. - pub block_construction: ExecutionStrategy, - /// Execution strategy used for offchain workers. - pub offchain_worker: ExecutionStrategy, - /// Execution strategy used in other cases. - pub other: ExecutionStrategy, -} - -impl Default for ExecutionStrategies { - fn default() -> ExecutionStrategies { - ExecutionStrategies { - syncing: ExecutionStrategy::NativeElseWasm, - importing: ExecutionStrategy::NativeElseWasm, - block_construction: ExecutionStrategy::AlwaysWasm, - offchain_worker: ExecutionStrategy::NativeWhenPossible, - other: ExecutionStrategy::NativeElseWasm, - } - } -} +use std::{marker::PhantomData, sync::Arc}; /// Generate the starting set of [`Extensions`]. /// @@ -74,22 +36,12 @@ pub trait ExtensionsFactory: Send + Sync { /// /// - `block_hash`: The hash of the block in the context that extensions will be used. /// - `block_number`: The number of the block in the context that extensions will be used. - /// - `capabilities`: The capabilities - fn extensions_for( - &self, - block_hash: Block::Hash, - block_number: NumberFor, - capabilities: offchain::Capabilities, - ) -> Extensions; + fn extensions_for(&self, block_hash: Block::Hash, block_number: NumberFor) + -> Extensions; } impl ExtensionsFactory for () { - fn extensions_for( - &self, - _: Block::Hash, - _: NumberFor, - _capabilities: offchain::Capabilities, - ) -> Extensions { + fn extensions_for(&self, _: Block::Hash, _: NumberFor) -> Extensions { Extensions::new() } } @@ -99,10 +51,9 @@ impl> ExtensionsFactory for Ve &self, block_hash: Block::Hash, block_number: NumberFor, - capabilities: offchain::Capabilities, ) -> Extensions { let mut exts = Extensions::new(); - exts.extend(self.iter().map(|e| e.extensions_for(block_hash, block_number, capabilities))); + exts.extend(self.iter().map(|e| e.extensions_for(block_hash, block_number))); exts } } @@ -125,12 +76,7 @@ impl ExtensionBeforeBlock { impl ExtensionsFactory for ExtensionBeforeBlock { - fn extensions_for( - &self, - _: Block::Hash, - block_number: NumberFor, - _: offchain::Capabilities, - ) -> Extensions { + fn extensions_for(&self, _: Block::Hash, block_number: NumberFor) -> Extensions { let mut exts = Extensions::new(); if block_number < self.before { @@ -141,154 +87,47 @@ impl ExtensionsFactory } } -/// Create a Offchain DB accessor object. -pub trait DbExternalitiesFactory: Send + Sync { - /// Create [`offchain::DbExternalities`] instance. - fn create(&self) -> Box; -} - -impl DbExternalitiesFactory for T { - fn create(&self) -> Box { - Box::new(self.clone()) - } -} - /// A producer of execution extensions for offchain calls. /// /// This crate aggregates extensions available for the offchain calls /// and is responsible for producing a correct `Extensions` object. /// for each call, based on required `Capabilities`. pub struct ExecutionExtensions { - strategies: ExecutionStrategies, - keystore: Option, - offchain_db: Option>, - // FIXME: these three are only RwLock because of https://github.com/paritytech/substrate/issues/4587 - // remove when fixed. - transaction_pool_factory: RwLock>>, extensions_factory: RwLock>>, - statement_store: RwLock>>, read_runtime_version: Arc, } impl ExecutionExtensions { - /// Create new `ExecutionExtensions` given a `keystore` and `ExecutionStrategies`. + /// Create new `ExecutionExtensions` given an `extensions_factory`. pub fn new( - strategies: ExecutionStrategies, - keystore: Option, - offchain_db: Option>, + extensions_factory: Option>>, read_runtime_version: Arc, ) -> Self { - let transaction_pool = RwLock::new(None); - let statement_store = RwLock::new(None); - let extensions_factory = Box::new(()); Self { - strategies, - keystore, - offchain_db, - extensions_factory: RwLock::new(extensions_factory), - transaction_pool_factory: transaction_pool, - statement_store, + extensions_factory: extensions_factory + .map(RwLock::new) + .unwrap_or_else(|| RwLock::new(Box::new(()))), read_runtime_version, } } - /// Get a reference to the execution strategies. - pub fn strategies(&self) -> &ExecutionStrategies { - &self.strategies - } - /// Set the new extensions_factory pub fn set_extensions_factory(&self, maker: impl ExtensionsFactory + 'static) { *self.extensions_factory.write() = Box::new(maker); } - /// Register transaction pool extension. - pub fn register_transaction_pool_factory( - &self, - factory: OffchainTransactionPoolFactory, - ) { - *self.transaction_pool_factory.write() = Some(factory); - } - - /// Register statement store extension. - pub fn register_statement_store(&self, store: Arc) { - *self.statement_store.write() = Some(Arc::downgrade(&store) as _); - } - /// Based on the execution context and capabilities it produces /// the extensions object to support desired set of APIs. pub fn extensions( &self, block_hash: Block::Hash, block_number: NumberFor, - context: ExecutionContext, ) -> Extensions { - let capabilities = context.capabilities(); - let mut extensions = - self.extensions_factory - .read() - .extensions_for(block_hash, block_number, capabilities); - - if capabilities.contains(offchain::Capabilities::KEYSTORE) { - if let Some(ref keystore) = self.keystore { - extensions.register(KeystoreExt(keystore.clone())); - } - } - - if capabilities.contains(offchain::Capabilities::TRANSACTION_POOL) { - if let Some(pool) = self.transaction_pool_factory.read().as_ref() { - extensions.register(pool.offchain_transaction_pool(block_hash)); - } - } - - if capabilities.contains(offchain::Capabilities::STATEMENT_STORE) { - if let Some(store) = self.statement_store.read().as_ref().and_then(|x| x.upgrade()) { - extensions.register(sp_statement_store::runtime_api::StatementStoreExt(store)); - } - } - if capabilities.contains(offchain::Capabilities::OFFCHAIN_DB_READ) || - capabilities.contains(offchain::Capabilities::OFFCHAIN_DB_WRITE) - { - if let Some(offchain_db) = self.offchain_db.as_ref() { - extensions.register(OffchainDbExt::new(offchain::LimitedExternalities::new( - capabilities, - offchain_db.create(), - ))); - } - } - - if let ExecutionContext::OffchainCall(Some(ext)) = context { - extensions.register(OffchainWorkerExt::new(offchain::LimitedExternalities::new( - capabilities, - ext.0, - ))); - } + self.extensions_factory.read().extensions_for(block_hash, block_number); extensions.register(ReadRuntimeVersionExt::new(self.read_runtime_version.clone())); extensions } - - /// Create `ExecutionManager` and `Extensions` for given offchain call. - /// - /// Based on the execution context and capabilities it produces - /// the right manager and extensions object to support desired set of APIs. - pub fn manager_and_extensions( - &self, - block_hash: Block::Hash, - block_number: NumberFor, - context: ExecutionContext, - ) -> (ExecutionManager>, Extensions) { - let manager = match context { - ExecutionContext::BlockConstruction => self.strategies.block_construction.get_manager(), - ExecutionContext::Syncing => self.strategies.syncing.get_manager(), - ExecutionContext::Importing => self.strategies.importing.get_manager(), - ExecutionContext::OffchainCall(Some((_, capabilities))) if capabilities.is_all() => - self.strategies.offchain_worker.get_manager(), - ExecutionContext::OffchainCall(_) => self.strategies.other.get_manager(), - }; - - (manager, self.extensions(block_hash, block_number, context)) - } } diff --git a/client/api/src/lib.rs b/client/api/src/lib.rs index 0faddc10fe016..faadf3663a59d 100644 --- a/client/api/src/lib.rs +++ b/client/api/src/lib.rs @@ -36,7 +36,7 @@ pub use proof_provider::*; pub use sp_blockchain as blockchain; pub use sp_blockchain::HeaderBackend; -pub use sp_state_machine::{CompactProof, ExecutionStrategy, StorageProof}; +pub use sp_state_machine::{CompactProof, StorageProof}; pub use sp_storage::{ChildInfo, PrefixedStorageKey, StorageData, StorageKey}; /// Usage Information Provider interface diff --git a/client/block-builder/src/lib.rs b/client/block-builder/src/lib.rs index f055d4688822a..7c57c77f3dad5 100644 --- a/client/block-builder/src/lib.rs +++ b/client/block-builder/src/lib.rs @@ -32,7 +32,7 @@ use sp_api::{ ApiExt, ApiRef, Core, ProvideRuntimeApi, StorageChanges, StorageProof, TransactionOutcome, }; use sp_blockchain::{ApplyExtrinsicFailed, Error}; -use sp_core::ExecutionContext; +use sp_core::traits::CallContext; use sp_runtime::{ legacy, traits::{Block as BlockT, Hash, HashFor, Header as HeaderT, NumberFor, One}, @@ -178,11 +178,9 @@ where api.record_proof(); } - api.initialize_block_with_context( - parent_hash, - ExecutionContext::BlockConstruction, - &header, - )?; + api.set_call_context(CallContext::Onchain); + + api.initialize_block(parent_hash, &header)?; let version = api .api_version::>(parent_hash)? @@ -209,18 +207,10 @@ where self.api.execute_in_transaction(|api| { let res = if version < 6 { #[allow(deprecated)] - api.apply_extrinsic_before_version_6_with_context( - parent_hash, - ExecutionContext::BlockConstruction, - xt.clone(), - ) - .map(legacy::byte_sized_error::convert_to_latest) + api.apply_extrinsic_before_version_6(parent_hash, xt.clone()) + .map(legacy::byte_sized_error::convert_to_latest) } else { - api.apply_extrinsic_with_context( - parent_hash, - ExecutionContext::BlockConstruction, - xt.clone(), - ) + api.apply_extrinsic(parent_hash, xt.clone()) }; match res { @@ -242,9 +232,7 @@ where /// supplied by `self.api`, combined as [`BuiltBlock`]. /// The storage proof will be `Some(_)` when proof recording was enabled. pub fn build(mut self) -> Result>, Error> { - let header = self - .api - .finalize_block_with_context(self.parent_hash, ExecutionContext::BlockConstruction)?; + let header = self.api.finalize_block(self.parent_hash)?; debug_assert_eq!( header.extrinsics_root().clone(), @@ -282,11 +270,7 @@ where .execute_in_transaction(move |api| { // `create_inherents` should not change any state, to ensure this we always rollback // the transaction. - TransactionOutcome::Rollback(api.inherent_extrinsics_with_context( - parent_hash, - ExecutionContext::BlockConstruction, - inherent_data, - )) + TransactionOutcome::Rollback(api.inherent_extrinsics(parent_hash, inherent_data)) }) .map_err(|e| Error::Application(Box::new(e))) } diff --git a/client/cli/src/arg_enums.rs b/client/cli/src/arg_enums.rs index 982979605a32d..40d86fd97988d 100644 --- a/client/cli/src/arg_enums.rs +++ b/client/cli/src/arg_enums.rs @@ -161,17 +161,6 @@ pub enum ExecutionStrategy { NativeElseWasm, } -impl Into for ExecutionStrategy { - fn into(self) -> sc_client_api::ExecutionStrategy { - match self { - ExecutionStrategy::Native => sc_client_api::ExecutionStrategy::NativeWhenPossible, - ExecutionStrategy::Wasm => sc_client_api::ExecutionStrategy::AlwaysWasm, - ExecutionStrategy::Both => sc_client_api::ExecutionStrategy::Both, - ExecutionStrategy::NativeElseWasm => sc_client_api::ExecutionStrategy::NativeElseWasm, - } - } -} - /// Available RPC methods. #[allow(missing_docs)] #[derive(Debug, Copy, Clone, PartialEq, ValueEnum)] @@ -270,16 +259,3 @@ impl Into for SyncMode { } } } - -/// Default value for the `--execution-syncing` parameter. -pub const DEFAULT_EXECUTION_SYNCING: ExecutionStrategy = ExecutionStrategy::Wasm; -/// Default value for the `--execution-import-block` parameter. -pub const DEFAULT_EXECUTION_IMPORT_BLOCK: ExecutionStrategy = ExecutionStrategy::Wasm; -/// Default value for the `--execution-import-block` parameter when the node is a validator. -pub const DEFAULT_EXECUTION_IMPORT_BLOCK_VALIDATOR: ExecutionStrategy = ExecutionStrategy::Wasm; -/// Default value for the `--execution-block-construction` parameter. -pub const DEFAULT_EXECUTION_BLOCK_CONSTRUCTION: ExecutionStrategy = ExecutionStrategy::Wasm; -/// Default value for the `--execution-offchain-worker` parameter. -pub const DEFAULT_EXECUTION_OFFCHAIN_WORKER: ExecutionStrategy = ExecutionStrategy::Wasm; -/// Default value for the `--execution-other` parameter. -pub const DEFAULT_EXECUTION_OTHER: ExecutionStrategy = ExecutionStrategy::Wasm; diff --git a/client/cli/src/config.rs b/client/cli/src/config.rs index 04c62a73b40ed..4d218da6aa898 100644 --- a/client/cli/src/config.rs +++ b/client/cli/src/config.rs @@ -24,7 +24,6 @@ use crate::{ }; use log::warn; use names::{Generator, Name}; -use sc_client_api::execution_extensions::ExecutionStrategies; use sc_service::{ config::{ BasePath, Configuration, DatabaseSource, KeystoreConfig, NetworkConfiguration, @@ -291,21 +290,6 @@ pub trait CliConfiguration: Sized { self.import_params().map(|x| x.wasm_runtime_overrides()).unwrap_or_default() } - /// Get the execution strategies. - /// - /// By default this is retrieved from `ImportParams` if it is available. Otherwise its - /// `ExecutionStrategies::default()`. - fn execution_strategies( - &self, - is_dev: bool, - is_validator: bool, - ) -> Result { - Ok(self - .import_params() - .map(|x| x.execution_strategies(is_dev, is_validator)) - .unwrap_or_default()) - } - /// Get the RPC address. fn rpc_addr(&self, _default_listen_port: u16) -> Result> { Ok(None) @@ -508,7 +492,6 @@ pub trait CliConfiguration: Sized { blocks_pruning: self.blocks_pruning()?, wasm_method: self.wasm_method()?, wasm_runtime_overrides: self.wasm_runtime_overrides(), - execution_strategies: self.execution_strategies(is_dev, is_validator)?, rpc_addr: self.rpc_addr(DCV::rpc_listen_port())?, rpc_methods: self.rpc_methods()?, rpc_max_connections: self.rpc_max_connections()?, diff --git a/client/cli/src/params/import_params.rs b/client/cli/src/params/import_params.rs index 9e57a017e51ca..bfa54a35058f6 100644 --- a/client/cli/src/params/import_params.rs +++ b/client/cli/src/params/import_params.rs @@ -19,15 +19,11 @@ use crate::{ arg_enums::{ ExecutionStrategy, WasmExecutionMethod, WasmtimeInstantiationStrategy, - DEFAULT_EXECUTION_BLOCK_CONSTRUCTION, DEFAULT_EXECUTION_IMPORT_BLOCK, - DEFAULT_EXECUTION_IMPORT_BLOCK_VALIDATOR, DEFAULT_EXECUTION_OFFCHAIN_WORKER, - DEFAULT_EXECUTION_OTHER, DEFAULT_EXECUTION_SYNCING, DEFAULT_WASMTIME_INSTANTIATION_STRATEGY, DEFAULT_WASM_EXECUTION_METHOD, }, params::{DatabaseParams, PruningParams}, }; use clap::Args; -use sc_client_api::execution_extensions::ExecutionStrategies; use std::path::PathBuf; /// Parameters for block import. @@ -104,6 +100,8 @@ impl ImportParams { /// Get the WASM execution method from the parameters pub fn wasm_method(&self) -> sc_service::config::WasmExecutionMethod { + self.execution_strategies.check_usage_and_print_deprecation_warning(); + crate::execution_method_from_cli(self.wasm_method, self.wasmtime_instantiation_strategy) } @@ -112,36 +110,6 @@ impl ImportParams { pub fn wasm_runtime_overrides(&self) -> Option { self.wasm_runtime_overrides.clone() } - - /// Get execution strategies for the parameters - pub fn execution_strategies(&self, is_dev: bool, is_validator: bool) -> ExecutionStrategies { - let exec = &self.execution_strategies; - let exec_all_or = |strat: Option, default: ExecutionStrategy| { - let default = if is_dev { ExecutionStrategy::Native } else { default }; - - exec.execution.unwrap_or_else(|| strat.unwrap_or(default)).into() - }; - - let default_execution_import_block = if is_validator { - DEFAULT_EXECUTION_IMPORT_BLOCK_VALIDATOR - } else { - DEFAULT_EXECUTION_IMPORT_BLOCK - }; - - ExecutionStrategies { - syncing: exec_all_or(exec.execution_syncing, DEFAULT_EXECUTION_SYNCING), - importing: exec_all_or(exec.execution_import_block, default_execution_import_block), - block_construction: exec_all_or( - exec.execution_block_construction, - DEFAULT_EXECUTION_BLOCK_CONSTRUCTION, - ), - offchain_worker: exec_all_or( - exec.execution_offchain_worker, - DEFAULT_EXECUTION_OFFCHAIN_WORKER, - ), - other: exec_all_or(exec.execution_other, DEFAULT_EXECUTION_OTHER), - } - } } /// Execution strategies parameters. @@ -186,3 +154,23 @@ pub struct ExecutionStrategiesParams { )] pub execution: Option, } + +impl ExecutionStrategiesParams { + /// Check if one of the parameters is still passed and print a warning if so. + fn check_usage_and_print_deprecation_warning(&self) { + for (param, name) in [ + (&self.execution_syncing, "execution-syncing"), + (&self.execution_import_block, "execution-import-block"), + (&self.execution_block_construction, "execution-block-construction"), + (&self.execution_offchain_worker, "execution-offchain-worker"), + (&self.execution_other, "execution-other"), + (&self.execution, "execution"), + ] { + if param.is_some() { + eprintln!( + "CLI parameter `--{name}` has no effect anymore and will be removed in the future!" + ); + } + } + } +} diff --git a/client/cli/src/runner.rs b/client/cli/src/runner.rs index 66c3fe41b6c21..c96f494354f9a 100644 --- a/client/cli/src/runner.rs +++ b/client/cli/src/runner.rs @@ -265,7 +265,6 @@ mod tests { )), wasm_method: Default::default(), wasm_runtime_overrides: None, - execution_strategies: Default::default(), rpc_addr: None, rpc_max_connections: Default::default(), rpc_cors: None, diff --git a/client/consensus/aura/src/import_queue.rs b/client/consensus/aura/src/import_queue.rs index ef7a2a1cc865b..0b9ceb4fe7760 100644 --- a/client/consensus/aura/src/import_queue.rs +++ b/client/consensus/aura/src/import_queue.rs @@ -38,7 +38,7 @@ use sp_blockchain::HeaderBackend; use sp_consensus::Error as ConsensusError; use sp_consensus_aura::{inherents::AuraInherentData, AuraApi}; use sp_consensus_slots::Slot; -use sp_core::{crypto::Pair, ExecutionContext}; +use sp_core::crypto::Pair; use sp_inherents::{CreateInherentDataProviders, InherentDataProvider as _}; use sp_runtime::{ traits::{Block as BlockT, Header, NumberFor}, @@ -138,7 +138,6 @@ where at_hash: B::Hash, inherent_data: sp_inherents::InherentData, create_inherent_data_providers: CIDP::InherentDataProviders, - execution_context: ExecutionContext, ) -> Result<(), Error> where C: ProvideRuntimeApi, @@ -148,7 +147,7 @@ where let inherent_res = self .client .runtime_api() - .check_inherents_with_context(at_hash, execution_context, block, inherent_data) + .check_inherents(at_hash, block, inherent_data) .map_err(|e| Error::Client(e.into()))?; if !inherent_res.ok() { @@ -249,7 +248,6 @@ where parent_hash, inherent_data, create_inherent_data_providers, - block.origin.into(), ) .await .map_err(|e| e.to_string())?; diff --git a/client/consensus/babe/Cargo.toml b/client/consensus/babe/Cargo.toml index 28bd28c812b32..e036ff1e64cd1 100644 --- a/client/consensus/babe/Cargo.toml +++ b/client/consensus/babe/Cargo.toml @@ -31,6 +31,7 @@ sc-consensus = { version = "0.10.0-dev", path = "../../../client/consensus/commo sc-consensus-epochs = { version = "0.10.0-dev", path = "../epochs" } sc-consensus-slots = { version = "0.10.0-dev", path = "../slots" } sc-telemetry = { version = "4.0.0-dev", path = "../../telemetry" } +sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../transaction-pool/api" } sp-api = { version = "4.0.0-dev", path = "../../../primitives/api" } sp-application-crypto = { version = "23.0.0", path = "../../../primitives/application-crypto" } sp-block-builder = { version = "4.0.0-dev", path = "../../../primitives/block-builder" } diff --git a/client/consensus/babe/rpc/Cargo.toml b/client/consensus/babe/rpc/Cargo.toml index c0b20eb11c95a..7b16ea84c4366 100644 --- a/client/consensus/babe/rpc/Cargo.toml +++ b/client/consensus/babe/rpc/Cargo.toml @@ -34,5 +34,6 @@ serde_json = "1.0.85" tokio = "1.22.0" sc-consensus = { version = "0.10.0-dev", path = "../../../consensus/common" } sc-keystore = { version = "4.0.0-dev", path = "../../../keystore" } +sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../../transaction-pool/api" } sp-keyring = { version = "24.0.0", path = "../../../../primitives/keyring" } substrate-test-runtime-client = { version = "2.0.0", path = "../../../../test-utils/runtime/client" } diff --git a/client/consensus/babe/rpc/src/lib.rs b/client/consensus/babe/rpc/src/lib.rs index 1ae15cc5453d7..bffe026ea6ef6 100644 --- a/client/consensus/babe/rpc/src/lib.rs +++ b/client/consensus/babe/rpc/src/lib.rs @@ -186,6 +186,8 @@ impl From for JsonRpseeError { #[cfg(test)] mod tests { use super::*; + use sc_consensus_babe::ImportQueueParams; + use sc_transaction_pool_api::{OffchainTransactionPoolFactory, RejectAllTxPool}; use sp_consensus_babe::inherents::InherentDataProvider; use sp_core::{crypto::key_types::BABE, testing::TaskExecutor}; use sp_keyring::Sr25519Keyring; @@ -219,22 +221,25 @@ mod tests { sc_consensus_babe::block_import(config.clone(), client.clone(), client.clone()) .expect("can initialize block-import"); - let (_, babe_worker_handle) = sc_consensus_babe::import_queue( - link.clone(), - block_import.clone(), - None, - client.clone(), - longest_chain.clone(), - move |_, _| async move { + let (_, babe_worker_handle) = sc_consensus_babe::import_queue(ImportQueueParams { + link: link.clone(), + block_import: block_import.clone(), + justification_import: None, + client: client.clone(), + select_chain: longest_chain.clone(), + create_inherent_data_providers: move |_, _| async move { Ok((InherentDataProvider::from_timestamp_and_slot_duration( 0.into(), slot_duration, ),)) }, - &task_executor, - None, - None, - ) + spawner: &task_executor, + registry: None, + telemetry: None, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), + }) .unwrap(); Babe::new(client.clone(), babe_worker_handle, keystore, longest_chain, deny_unsafe) diff --git a/client/consensus/babe/src/lib.rs b/client/consensus/babe/src/lib.rs index 64ff00bb58c35..76bd670c20049 100644 --- a/client/consensus/babe/src/lib.rs +++ b/client/consensus/babe/src/lib.rs @@ -106,6 +106,7 @@ use sc_consensus_slots::{ SlotInfo, StorageChanges, }; use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_TRACE}; +use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_application_crypto::AppCrypto; use sp_block_builder::BlockBuilder as BlockBuilderApi; @@ -116,7 +117,7 @@ use sp_blockchain::{ use sp_consensus::{BlockOrigin, Environment, Error as ConsensusError, Proposer, SelectChain}; use sp_consensus_babe::inherents::BabeInherentData; use sp_consensus_slots::Slot; -use sp_core::ExecutionContext; +use sp_core::traits::SpawnEssentialNamed; use sp_inherents::{CreateInherentDataProviders, InherentData, InherentDataProvider}; use sp_keystore::KeystorePtr; use sp_runtime::{ @@ -992,6 +993,7 @@ pub struct BabeVerifier { config: BabeConfiguration, epoch_changes: SharedEpochChanges, telemetry: Option, + offchain_tx_pool_factory: OffchainTransactionPoolFactory, } impl BabeVerifier @@ -1008,12 +1010,11 @@ where at_hash: Block::Hash, inherent_data: InherentData, create_inherent_data_providers: CIDP::InherentDataProviders, - execution_context: ExecutionContext, ) -> Result<(), Error> { let inherent_res = self .client .runtime_api() - .check_inherents_with_context(at_hash, execution_context, block, inherent_data) + .check_inherents(at_hash, block, inherent_data) .map_err(Error::RuntimeApi)?; if !inherent_res.ok() { @@ -1098,8 +1099,13 @@ where }; // submit equivocation report at best block. - self.client - .runtime_api() + let mut runtime_api = self.client.runtime_api(); + + // Register the offchain tx pool to be able to use it from the runtime. + runtime_api + .register_extension(self.offchain_tx_pool_factory.offchain_transaction_pool(best_hash)); + + runtime_api .submit_report_equivocation_unsigned_extrinsic( best_hash, equivocation_proof, @@ -1250,7 +1256,6 @@ where parent_hash, inherent_data, create_inherent_data_providers, - block.origin.into(), ) .await?; } @@ -1768,6 +1773,38 @@ where Ok((import, link)) } +/// Parameters passed to [`import_queue`]. +pub struct ImportQueueParams<'a, Block: BlockT, BI, Client, CIDP, SelectChain, Spawn> { + /// The BABE link that is created by [`block_import`]. + pub link: BabeLink, + /// The block import that should be wrapped. + pub block_import: BI, + /// Optional justification import. + pub justification_import: Option>, + /// The client to interact with the internals of the node. + pub client: Arc, + /// A [`SelectChain`] implementation. + /// + /// Used to determine the best block that should be used as basis when sending an equivocation + /// report. + pub select_chain: SelectChain, + /// Used to crate the inherent data providers. + /// + /// These inherent data providers are then used to create the inherent data that is + /// passed to the `check_inherents` runtime call. + pub create_inherent_data_providers: CIDP, + /// Spawner for spawning futures. + pub spawner: &'a Spawn, + /// Registry for prometheus metrics. + pub registry: Option<&'a Registry>, + /// Optional telemetry handle to report telemetry events. + pub telemetry: Option, + /// The offchain transaction pool factory. + /// + /// Will be used when sending equivocation reports. + pub offchain_tx_pool_factory: OffchainTransactionPoolFactory, +} + /// Start an import queue for the BABE consensus algorithm. /// /// This method returns the import queue, some data that needs to be passed to the block authoring @@ -1777,19 +1814,22 @@ where /// /// The block import object provided must be the `BabeBlockImport` or a wrapper /// of it, otherwise crucial import logic will be omitted. -pub fn import_queue( - babe_link: BabeLink, - block_import: Inner, - justification_import: Option>, - client: Arc, - select_chain: SelectChain, - create_inherent_data_providers: CIDP, - spawner: &impl sp_core::traits::SpawnEssentialNamed, - registry: Option<&Registry>, - telemetry: Option, +pub fn import_queue( + ImportQueueParams { + link: babe_link, + block_import, + justification_import, + client, + select_chain, + create_inherent_data_providers, + spawner, + registry, + telemetry, + offchain_tx_pool_factory, + }: ImportQueueParams<'_, Block, BI, Client, CIDP, SelectChain, Spawn>, ) -> ClientResult<(DefaultImportQueue, BabeWorkerHandle)> where - Inner: BlockImport< + BI: BlockImport< Block, Error = ConsensusError, Transaction = sp_api::TransactionFor, @@ -1807,6 +1847,7 @@ where SelectChain: sp_consensus::SelectChain + 'static, CIDP: CreateInherentDataProviders + Send + Sync + 'static, CIDP::InherentDataProviders: InherentDataProviderExt + Send + Sync, + Spawn: SpawnEssentialNamed, { const HANDLE_BUFFER_SIZE: usize = 1024; @@ -1817,6 +1858,7 @@ where epoch_changes: babe_link.epoch_changes.clone(), telemetry, client: client.clone(), + offchain_tx_pool_factory, }; let (worker_tx, worker_rx) = channel(HANDLE_BUFFER_SIZE); diff --git a/client/consensus/babe/src/tests.rs b/client/consensus/babe/src/tests.rs index 59b4076e2fd01..384e45228b599 100644 --- a/client/consensus/babe/src/tests.rs +++ b/client/consensus/babe/src/tests.rs @@ -26,6 +26,7 @@ use sc_consensus::{BoxBlockImport, BoxJustificationImport}; use sc_consensus_epochs::{EpochIdentifier, EpochIdentifierPosition}; use sc_consensus_slots::BackoffAuthoringOnFinalizedHeadLagging; use sc_network_test::{Block as TestBlock, *}; +use sc_transaction_pool_api::RejectAllTxPool; use sp_application_crypto::key_types::BABE; use sp_consensus::{DisableProofRecording, NoNetwork as DummyOracle, Proposal}; use sp_consensus_babe::{ @@ -283,6 +284,9 @@ impl TestNetFactory for BabeTestNet { config: data.link.config.clone(), epoch_changes: data.link.epoch_changes.clone(), telemetry: None, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), }, mutator: MUTATOR.with(|m| m.borrow().clone()), } diff --git a/client/consensus/grandpa/Cargo.toml b/client/consensus/grandpa/Cargo.toml index 13b472dc70322..af39c640122b6 100644 --- a/client/consensus/grandpa/Cargo.toml +++ b/client/consensus/grandpa/Cargo.toml @@ -32,6 +32,7 @@ prometheus-endpoint = { package = "substrate-prometheus-endpoint", version = "0. sc-block-builder = { version = "0.10.0-dev", path = "../../block-builder" } sc-chain-spec = { version = "4.0.0-dev", path = "../../../client/chain-spec" } sc-client-api = { version = "4.0.0-dev", path = "../../api" } +sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../transaction-pool/api" } sc-consensus = { version = "0.10.0-dev", path = "../common" } sc-network = { version = "0.10.0-dev", path = "../../network" } sc-network-gossip = { version = "0.10.0-dev", path = "../../network-gossip" } diff --git a/client/consensus/grandpa/src/environment.rs b/client/consensus/grandpa/src/environment.rs index 67820a59cc943..eeb9ff4468291 100644 --- a/client/consensus/grandpa/src/environment.rs +++ b/client/consensus/grandpa/src/environment.rs @@ -40,6 +40,8 @@ use sc_client_api::{ utils::is_descendent_of, }; use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_INFO}; +use sc_transaction_pool_api::OffchainTransactionPoolFactory; +use sp_api::ApiExt; use sp_blockchain::HeaderMetadata; use sp_consensus::SelectChain as SelectChainT; use sp_consensus_grandpa::{ @@ -444,6 +446,7 @@ pub(crate) struct Environment< pub(crate) metrics: Option, pub(crate) justification_sender: Option>, pub(crate) telemetry: Option, + pub(crate) offchain_tx_pool_factory: OffchainTransactionPoolFactory, pub(crate) _phantom: PhantomData, } @@ -570,8 +573,13 @@ where // submit equivocation report at **best** block let equivocation_proof = EquivocationProof::new(authority_set.set_id, equivocation); - self.client - .runtime_api() + let mut runtime_api = self.client.runtime_api(); + + runtime_api.register_extension( + self.offchain_tx_pool_factory.offchain_transaction_pool(best_block_hash), + ); + + runtime_api .submit_report_equivocation_unsigned_extrinsic( best_block_hash, equivocation_proof, diff --git a/client/consensus/grandpa/src/lib.rs b/client/consensus/grandpa/src/lib.rs index 9c0aa60c24e1b..c888340f70a34 100644 --- a/client/consensus/grandpa/src/lib.rs +++ b/client/consensus/grandpa/src/lib.rs @@ -64,12 +64,13 @@ use prometheus_endpoint::{PrometheusError, Registry}; use sc_client_api::{ backend::{AuxStore, Backend}, utils::is_descendent_of, - BlockchainEvents, CallExecutor, ExecutionStrategy, ExecutorProvider, Finalizer, LockImportRun, - StorageProvider, TransactionFor, + BlockchainEvents, CallExecutor, ExecutorProvider, Finalizer, LockImportRun, StorageProvider, + TransactionFor, }; use sc_consensus::BlockImport; use sc_network::types::ProtocolName; use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_INFO}; +use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver}; use sp_api::ProvideRuntimeApi; use sp_application_crypto::AppCrypto; @@ -479,7 +480,6 @@ where self.expect_block_hash_from_id(&BlockId::Number(Zero::zero()))?, "GrandpaApi_grandpa_authorities", &[], - ExecutionStrategy::NativeElseWasm, CallContext::Offchain, ) .and_then(|call_result| { @@ -688,6 +688,11 @@ pub struct GrandpaParams { pub shared_voter_state: SharedVoterState, /// TelemetryHandle instance. pub telemetry: Option, + /// Offchain transaction pool factory. + /// + /// This will be used to create an offchain transaction pool instance for sending an + /// equivocation report from the runtime. + pub offchain_tx_pool_factory: OffchainTransactionPoolFactory, } /// Returns the configuration value to put in @@ -736,6 +741,7 @@ where prometheus_registry, shared_voter_state, telemetry, + offchain_tx_pool_factory, } = grandpa_params; // NOTE: we have recently removed `run_grandpa_observer` from the public @@ -810,6 +816,7 @@ where shared_voter_state, justification_sender, telemetry, + offchain_tx_pool_factory, ); let voter_work = voter_work.map(|res| match res { @@ -879,6 +886,7 @@ where shared_voter_state: SharedVoterState, justification_sender: GrandpaJustificationSender, telemetry: Option, + offchain_tx_pool_factory: OffchainTransactionPoolFactory, ) -> Self { let metrics = match prometheus_registry.as_ref().map(Metrics::register) { Some(Ok(metrics)) => Some(metrics), @@ -903,6 +911,7 @@ where metrics: metrics.as_ref().map(|m| m.environment.clone()), justification_sender: Some(justification_sender), telemetry: telemetry.clone(), + offchain_tx_pool_factory, _phantom: PhantomData, }); @@ -1054,6 +1063,7 @@ where metrics: self.env.metrics.clone(), justification_sender: self.env.justification_sender.clone(), telemetry: self.telemetry.clone(), + offchain_tx_pool_factory: self.env.offchain_tx_pool_factory.clone(), _phantom: PhantomData, }); diff --git a/client/consensus/grandpa/src/tests.rs b/client/consensus/grandpa/src/tests.rs index c46e249be485c..4fbeed71a1bf5 100644 --- a/client/consensus/grandpa/src/tests.rs +++ b/client/consensus/grandpa/src/tests.rs @@ -33,6 +33,7 @@ use sc_network_test::{ Block, BlockImportAdapter, FullPeerConfig, Hash, PassThroughVerifier, Peer, PeersClient, PeersFullClient, TestClient, TestNetFactory, }; +use sc_transaction_pool_api::RejectAllTxPool; use sp_api::{ApiRef, ProvideRuntimeApi}; use sp_consensus::{BlockOrigin, Error as ConsensusError, SelectChain}; use sp_consensus_grandpa::{ @@ -331,6 +332,9 @@ fn initialize_grandpa( voting_rule: (), prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), telemetry: None, }; let voter = @@ -481,6 +485,9 @@ async fn finalize_3_voters_1_full_observer() { prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), telemetry: None, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), }; run_grandpa_voter(grandpa_params).expect("all in order with client and network") @@ -573,6 +580,9 @@ async fn transition_3_voters_twice_1_full_observer() { prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), telemetry: None, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), }; voters @@ -1040,6 +1050,9 @@ async fn voter_persists_its_votes() { prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), telemetry: None, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), }; run_grandpa_voter(grandpa_params).expect("all in order with client and network") @@ -1083,6 +1096,9 @@ async fn voter_persists_its_votes() { prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), telemetry: None, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), }; run_grandpa_voter(grandpa_params) @@ -1293,6 +1309,9 @@ async fn voter_catches_up_to_latest_round_when_behind() { prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), telemetry: None, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new( + RejectAllTxPool::default(), + ), }; Box::pin(run_grandpa_voter(grandpa_params).expect("all in order with client and network")) @@ -1422,6 +1441,7 @@ where justification_sender: None, telemetry: None, _phantom: PhantomData, + offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(RejectAllTxPool::default()), } } @@ -1986,7 +2006,7 @@ async fn grandpa_environment_doesnt_send_equivocation_reports_for_itself() { // keys it should work equivocation.identity = TryFrom::try_from(&[1; 32][..]).unwrap(); let equivocation_proof = sp_consensus_grandpa::Equivocation::Prevote(equivocation); - assert!(environment.report_equivocation(equivocation_proof).is_ok()); + environment.report_equivocation(equivocation_proof).unwrap(); } #[tokio::test] diff --git a/client/consensus/pow/src/lib.rs b/client/consensus/pow/src/lib.rs index 913686b7bf36d..763cf10e6cd4f 100644 --- a/client/consensus/pow/src/lib.rs +++ b/client/consensus/pow/src/lib.rs @@ -58,7 +58,6 @@ use sp_block_builder::BlockBuilder as BlockBuilderApi; use sp_blockchain::HeaderBackend; use sp_consensus::{Environment, Error as ConsensusError, Proposer, SelectChain, SyncOracle}; use sp_consensus_pow::{Seal, TotalDifficulty, POW_ENGINE_ID}; -use sp_core::ExecutionContext; use sp_inherents::{CreateInherentDataProviders, InherentDataProvider}; use sp_runtime::{ generic::{BlockId, Digest, DigestItem}, @@ -269,7 +268,6 @@ where block: B, at_hash: B::Hash, inherent_data_providers: CIDP::InherentDataProviders, - execution_context: ExecutionContext, ) -> Result<(), Error> { if *block.header().number() < self.check_inherents_after { return Ok(()) @@ -283,7 +281,7 @@ where let inherent_res = self .client .runtime_api() - .check_inherents_with_context(at_hash, execution_context, block, inherent_data) + .check_inherents(at_hash, block, inherent_data) .map_err(|e| Error::Client(e.into()))?; if !inherent_res.ok() { @@ -348,7 +346,6 @@ where self.create_inherent_data_providers .create_inherent_data_providers(parent_hash, ()) .await?, - block.origin.into(), ) .await?; } diff --git a/client/merkle-mountain-range/rpc/src/lib.rs b/client/merkle-mountain-range/rpc/src/lib.rs index daf2cd1ec298b..5be82b600d914 100644 --- a/client/merkle-mountain-range/rpc/src/lib.rs +++ b/client/merkle-mountain-range/rpc/src/lib.rs @@ -30,9 +30,12 @@ use jsonrpsee::{ }; use serde::{Deserialize, Serialize}; -use sp_api::{NumberFor, ProvideRuntimeApi}; +use sp_api::{ApiExt, NumberFor, ProvideRuntimeApi}; use sp_blockchain::HeaderBackend; -use sp_core::Bytes; +use sp_core::{ + offchain::{storage::OffchainDb, OffchainDbExt, OffchainStorage}, + Bytes, +}; use sp_mmr_primitives::{Error as MmrError, Proof}; use sp_runtime::traits::Block as BlockT; @@ -127,26 +130,28 @@ pub trait MmrApi { } /// MMR RPC methods. -pub struct Mmr { +pub struct Mmr { client: Arc, + offchain_db: OffchainDb, _marker: PhantomData, } -impl Mmr { +impl Mmr { /// Create new `Mmr` with the given reference to the client. - pub fn new(client: Arc) -> Self { - Self { client, _marker: Default::default() } + pub fn new(client: Arc, offchain_storage: S) -> Self { + Self { client, _marker: Default::default(), offchain_db: OffchainDb::new(offchain_storage) } } } #[async_trait] -impl MmrApiServer<::Hash, NumberFor, MmrHash> - for Mmr +impl MmrApiServer<::Hash, NumberFor, MmrHash> + for Mmr where Block: BlockT, Client: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, Client::Api: MmrRuntimeApi>, MmrHash: Codec + Send + Sync + 'static, + S: OffchainStorage + 'static, { fn mmr_root(&self, at: Option<::Hash>) -> RpcResult { let block_hash = at.unwrap_or_else(|| @@ -166,18 +171,15 @@ where best_known_block_number: Option>, at: Option<::Hash>, ) -> RpcResult::Hash>> { - let api = self.client.runtime_api(); + let mut api = self.client.runtime_api(); let block_hash = at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. self.client.info().best_hash); + api.register_extension(OffchainDbExt::new(self.offchain_db.clone())); + let (leaves, proof) = api - .generate_proof_with_context( - block_hash, - sp_core::ExecutionContext::OffchainCall(None), - block_numbers, - best_known_block_number, - ) + .generate_proof(block_hash, block_numbers, best_known_block_number) .map_err(runtime_error_into_rpc_error)? .map_err(mmr_error_into_rpc_error)?; @@ -185,7 +187,7 @@ where } fn verify_proof(&self, proof: LeavesProof<::Hash>) -> RpcResult { - let api = self.client.runtime_api(); + let mut api = self.client.runtime_api(); let leaves = Decode::decode(&mut &proof.leaves.0[..]) .map_err(|e| CallError::InvalidParams(anyhow::Error::new(e)))?; @@ -193,14 +195,11 @@ where let decoded_proof = Decode::decode(&mut &proof.proof.0[..]) .map_err(|e| CallError::InvalidParams(anyhow::Error::new(e)))?; - api.verify_proof_with_context( - proof.block_hash, - sp_core::ExecutionContext::OffchainCall(None), - leaves, - decoded_proof, - ) - .map_err(runtime_error_into_rpc_error)? - .map_err(mmr_error_into_rpc_error)?; + api.register_extension(OffchainDbExt::new(self.offchain_db.clone())); + + api.verify_proof(proof.block_hash, leaves, decoded_proof) + .map_err(runtime_error_into_rpc_error)? + .map_err(mmr_error_into_rpc_error)?; Ok(true) } diff --git a/client/offchain/Cargo.toml b/client/offchain/Cargo.toml index 42504ec590c70..f52b0aa2878f6 100644 --- a/client/offchain/Cargo.toml +++ b/client/offchain/Cargo.toml @@ -30,11 +30,16 @@ threadpool = "1.7" tracing = "0.1.29" sc-client-api = { version = "4.0.0-dev", path = "../api" } sc-network = { version = "0.10.0-dev", path = "../network" } +sc-network-common = { version = "0.10.0-dev", path = "../network/common" } +sc-transaction-pool-api = { version = "4.0.0-dev", path = "../transaction-pool/api" } sc-utils = { version = "4.0.0-dev", path = "../utils" } sp-api = { version = "4.0.0-dev", path = "../../primitives/api" } sp-core = { version = "21.0.0", path = "../../primitives/core" } sp-offchain = { version = "4.0.0-dev", path = "../../primitives/offchain" } sp-runtime = { version = "24.0.0", path = "../../primitives/runtime" } +sp-keystore = { version = "0.27.0", path = "../../primitives/keystore" } +sp-externalities = { version = "0.19.0", path = "../../primitives/externalities" } +log = "0.4.17" [dev-dependencies] lazy_static = "1.4.0" diff --git a/client/offchain/src/api.rs b/client/offchain/src/api.rs index 33ddd46c7a306..e6b0e30f20378 100644 --- a/client/offchain/src/api.rs +++ b/client/offchain/src/api.rs @@ -25,8 +25,8 @@ pub use http::SharedClient; use libp2p::{Multiaddr, PeerId}; use sp_core::{ offchain::{ - self, HttpError, HttpRequestId, HttpRequestStatus, OffchainStorage, OpaqueMultiaddr, - OpaqueNetworkState, StorageKind, Timestamp, + self, HttpError, HttpRequestId, HttpRequestStatus, OpaqueMultiaddr, OpaqueNetworkState, + Timestamp, }, OpaquePeerId, }; @@ -36,110 +36,6 @@ mod http; mod timestamp; -fn unavailable_yet(name: &str) -> R { - tracing::error!( - target: super::LOG_TARGET, - "The {:?} API is not available for offchain workers yet. Follow \ - https://github.com/paritytech/substrate/issues/1458 for details", - name - ); - Default::default() -} - -const LOCAL_DB: &str = "LOCAL (fork-aware) DB"; - -/// Offchain DB reference. -#[derive(Debug, Clone)] -pub struct Db { - /// Persistent storage database. - persistent: Storage, -} - -impl Db { - /// Create new instance of Offchain DB. - pub fn new(persistent: Storage) -> Self { - Self { persistent } - } - - /// Create new instance of Offchain DB, backed by given backend. - pub fn factory_from_backend( - backend: &Backend, - ) -> Option> - where - Backend: sc_client_api::Backend, - Block: sp_runtime::traits::Block, - Storage: 'static, - { - sc_client_api::Backend::offchain_storage(backend).map(|db| Box::new(Self::new(db)) as _) - } -} - -impl offchain::DbExternalities for Db { - fn local_storage_set(&mut self, kind: StorageKind, key: &[u8], value: &[u8]) { - tracing::debug!( - target: "offchain-worker::storage", - ?kind, - key = ?array_bytes::bytes2hex("", key), - value = ?array_bytes::bytes2hex("", value), - "Write", - ); - match kind { - StorageKind::PERSISTENT => self.persistent.set(STORAGE_PREFIX, key, value), - StorageKind::LOCAL => unavailable_yet(LOCAL_DB), - } - } - - fn local_storage_clear(&mut self, kind: StorageKind, key: &[u8]) { - tracing::debug!( - target: "offchain-worker::storage", - ?kind, - key = ?array_bytes::bytes2hex("", key), - "Clear", - ); - match kind { - StorageKind::PERSISTENT => self.persistent.remove(STORAGE_PREFIX, key), - StorageKind::LOCAL => unavailable_yet(LOCAL_DB), - } - } - - fn local_storage_compare_and_set( - &mut self, - kind: StorageKind, - key: &[u8], - old_value: Option<&[u8]>, - new_value: &[u8], - ) -> bool { - tracing::debug!( - target: "offchain-worker::storage", - ?kind, - key = ?array_bytes::bytes2hex("", key), - new_value = ?array_bytes::bytes2hex("", new_value), - old_value = ?old_value.as_ref().map(|s| array_bytes::bytes2hex("", s)), - "CAS", - ); - match kind { - StorageKind::PERSISTENT => - self.persistent.compare_and_set(STORAGE_PREFIX, key, old_value, new_value), - StorageKind::LOCAL => unavailable_yet(LOCAL_DB), - } - } - - fn local_storage_get(&mut self, kind: StorageKind, key: &[u8]) -> Option> { - let result = match kind { - StorageKind::PERSISTENT => self.persistent.get(STORAGE_PREFIX, key), - StorageKind::LOCAL => unavailable_yet(LOCAL_DB), - }; - tracing::debug!( - target: "offchain-worker::storage", - ?kind, - key = ?array_bytes::bytes2hex("", key), - result = ?result.as_ref().map(|s| array_bytes::bytes2hex("", s)), - "Read", - ); - result - } -} - /// Asynchronous offchain API. /// /// NOTE this is done to prevent recursive calls into the runtime @@ -329,7 +225,7 @@ mod tests { config::MultiaddrWithPeerId, types::ProtocolName, NetworkPeers, NetworkStateInfo, ReputationChange, }; - use sp_core::offchain::{DbExternalities, Externalities}; + use sp_core::offchain::{storage::OffchainDb, DbExternalities, Externalities, StorageKind}; use std::time::SystemTime; pub(super) struct TestNetwork(); @@ -418,8 +314,8 @@ mod tests { AsyncApi::new(mock, false, shared_client) } - fn offchain_db() -> Db { - Db::new(LocalStorage::new_test()) + fn offchain_db() -> OffchainDb { + OffchainDb::new(LocalStorage::new_test()) } #[test] diff --git a/client/offchain/src/lib.rs b/client/offchain/src/lib.rs index 0945e39a3a881..4c11a5cb7294d 100644 --- a/client/offchain/src/lib.rs +++ b/client/offchain/src/lib.rs @@ -35,22 +35,26 @@ #![warn(missing_docs)] -use std::{fmt, marker::PhantomData, sync::Arc}; +use std::{fmt, sync::Arc}; use futures::{ future::{ready, Future}, prelude::*, }; use parking_lot::Mutex; +use sc_client_api::BlockchainEvents; use sc_network::{NetworkPeers, NetworkStateInfo}; +use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sp_api::{ApiExt, ProvideRuntimeApi}; -use sp_core::{offchain, traits::SpawnNamed, ExecutionContext}; +use sp_core::{offchain, traits::SpawnNamed}; +use sp_externalities::Extension; +use sp_keystore::{KeystoreExt, KeystorePtr}; use sp_runtime::traits::{self, Header}; use threadpool::ThreadPool; mod api; -pub use api::Db as OffchainDb; +pub use sp_core::offchain::storage::OffchainDb; pub use sp_offchain::{OffchainWorkerApi, STORAGE_PREFIX}; const LOG_TARGET: &str = "offchain-worker"; @@ -61,65 +65,160 @@ pub trait NetworkProvider: NetworkStateInfo + NetworkPeers {} impl NetworkProvider for T where T: NetworkStateInfo + NetworkPeers {} +/// Special type that implements [`OffchainStorage`](offchain::OffchainStorage). +/// +/// This type can not be constructed and should only be used when passing `None` as `offchain_db` to +/// [`OffchainWorkerOptions`] to make the compiler happy. +#[derive(Clone)] +pub enum NoOffchainStorage {} + +impl offchain::OffchainStorage for NoOffchainStorage { + fn set(&mut self, _: &[u8], _: &[u8], _: &[u8]) { + unimplemented!("`NoOffchainStorage` can not be constructed!") + } + + fn remove(&mut self, _: &[u8], _: &[u8]) { + unimplemented!("`NoOffchainStorage` can not be constructed!") + } + + fn get(&self, _: &[u8], _: &[u8]) -> Option> { + unimplemented!("`NoOffchainStorage` can not be constructed!") + } + + fn compare_and_set(&mut self, _: &[u8], _: &[u8], _: Option<&[u8]>, _: &[u8]) -> bool { + unimplemented!("`NoOffchainStorage` can not be constructed!") + } +} + /// Options for [`OffchainWorkers`] -pub struct OffchainWorkerOptions { +pub struct OffchainWorkerOptions { + /// Provides access to the runtime api. + pub runtime_api_provider: Arc, + /// Provides access to the keystore. + pub keystore: Option, + /// Provides access to the offchain database. + /// + /// Use [`NoOffchainStorage`] as type when passing `None` to have some type that works. + pub offchain_db: Option, + /// Provides access to the transaction pool. + pub transaction_pool: Option>, + /// Provides access to network information. + pub network_provider: Arc, + /// Is the node running as validator? + pub is_validator: bool, /// Enable http requests from offchain workers? /// /// If not enabled, any http request will panic. pub enable_http_requests: bool, + /// Callback to create custom [`Extension`]s that should be registered for the + /// `offchain_worker` runtime call. + /// + /// These [`Extension`]s are registered along-side the default extensions and are accessible in + /// the host functions. + /// + /// # Example: + /// + /// ```nocompile + /// custom_extensions: |block_hash| { + /// vec![MyCustomExtension::new()] + /// } + /// ``` + pub custom_extensions: CE, } /// An offchain workers manager. -pub struct OffchainWorkers { - client: Arc, - _block: PhantomData, +pub struct OffchainWorkers { + runtime_api_provider: Arc, thread_pool: Mutex, shared_http_client: api::SharedClient, - enable_http: bool, + enable_http_requests: bool, + keystore: Option, + offchain_db: Option>, + transaction_pool: Option>, + network_provider: Arc, + is_validator: bool, + custom_extensions: Box Vec> + Send>, } -impl OffchainWorkers { +impl OffchainWorkers { /// Creates new [`OffchainWorkers`]. - pub fn new(client: Arc) -> Self { - Self::new_with_options(client, OffchainWorkerOptions { enable_http_requests: true }) - } - - /// Creates new [`OffchainWorkers`] using the given `options`. - pub fn new_with_options(client: Arc, options: OffchainWorkerOptions) -> Self { + pub fn new Vec> + Send + 'static>( + OffchainWorkerOptions { + runtime_api_provider, + keystore, + offchain_db, + transaction_pool, + network_provider, + is_validator, + enable_http_requests, + custom_extensions, + }: OffchainWorkerOptions, + ) -> Self { Self { - client, - _block: PhantomData, + runtime_api_provider, thread_pool: Mutex::new(ThreadPool::with_name( "offchain-worker".into(), num_cpus::get(), )), shared_http_client: api::SharedClient::new(), - enable_http: options.enable_http_requests, + enable_http_requests, + keystore, + offchain_db: offchain_db.map(OffchainDb::new), + transaction_pool, + is_validator, + network_provider, + custom_extensions: Box::new(custom_extensions), } } } -impl fmt::Debug for OffchainWorkers { +impl fmt::Debug + for OffchainWorkers +{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_tuple("OffchainWorkers").finish() } } -impl OffchainWorkers +impl OffchainWorkers where Block: traits::Block, - Client: ProvideRuntimeApi + Send + Sync + 'static, - Client::Api: OffchainWorkerApi, + RA: ProvideRuntimeApi + Send + Sync + 'static, + RA::Api: OffchainWorkerApi, + Storage: offchain::OffchainStorage + 'static, { + /// Run the offchain workers on every block import. + pub async fn run>( + self, + import_events: Arc, + spawner: impl SpawnNamed, + ) { + import_events + .import_notification_stream() + .for_each(move |n| { + if n.is_new_best { + spawner.spawn( + "offchain-on-block", + Some("offchain-worker"), + self.on_block_imported(&n.header).boxed(), + ); + } else { + tracing::debug!( + target: LOG_TARGET, + "Skipping offchain workers for non-canon block: {:?}", + n.header, + ) + } + + ready(()) + }) + .await; + } + /// Start the offchain workers after given block. #[must_use] - pub fn on_block_imported( - &self, - header: &Block::Header, - network_provider: Arc, - is_validator: bool, - ) -> impl Future { - let runtime = self.client.runtime_api(); + fn on_block_imported(&self, header: &Block::Header) -> impl Future { + let runtime = self.runtime_api_provider.runtime_api(); let hash = header.hash(); let has_api_v1 = runtime.has_api_with::, _>(hash, |v| v == 1); let has_api_v2 = runtime.has_api_with::, _>(hash, |v| v == 2); @@ -140,36 +239,59 @@ where }; tracing::debug!( target: LOG_TARGET, - "Checking offchain workers at {:?}: version:{}", - hash, - version + "Checking offchain workers at {hash:?}: version: {version}", ); + let process = (version > 0).then(|| { - let (api, runner) = - api::AsyncApi::new(network_provider, is_validator, self.shared_http_client.clone()); - tracing::debug!(target: LOG_TARGET, "Spawning offchain workers at {:?}", hash); + let (api, runner) = api::AsyncApi::new( + self.network_provider.clone(), + self.is_validator, + self.shared_http_client.clone(), + ); + tracing::debug!(target: LOG_TARGET, "Spawning offchain workers at {hash:?}"); let header = header.clone(); - let client = self.client.clone(); + let client = self.runtime_api_provider.clone(); let mut capabilities = offchain::Capabilities::all(); + capabilities.set(offchain::Capabilities::HTTP, self.enable_http_requests); + + let keystore = self.keystore.clone(); + let db = self.offchain_db.clone(); + let tx_pool = self.transaction_pool.clone(); + let custom_extensions = (*self.custom_extensions)(hash); - capabilities.set(offchain::Capabilities::HTTP, self.enable_http); self.spawn_worker(move || { - let runtime = client.runtime_api(); + let mut runtime = client.runtime_api(); let api = Box::new(api); - tracing::debug!(target: LOG_TARGET, "Running offchain workers at {:?}", hash); + tracing::debug!(target: LOG_TARGET, "Running offchain workers at {hash:?}"); + + if let Some(keystore) = keystore { + runtime.register_extension(KeystoreExt(keystore.clone())); + } + + if let Some(pool) = tx_pool { + runtime.register_extension(pool.offchain_transaction_pool(hash)); + } + + if let Some(offchain_db) = db { + runtime.register_extension(offchain::OffchainDbExt::new( + offchain::LimitedExternalities::new(capabilities, offchain_db.clone()), + )); + } + + runtime.register_extension(offchain::OffchainWorkerExt::new( + offchain::LimitedExternalities::new(capabilities, api), + )); + + custom_extensions.into_iter().for_each(|ext| runtime.register_extension(ext)); - let context = ExecutionContext::OffchainCall(Some((api, capabilities))); let run = if version == 2 { - runtime.offchain_worker_with_context(hash, context, &header) + runtime.offchain_worker(hash, &header) } else { #[allow(deprecated)] - runtime.offchain_worker_before_version_2_with_context( - hash, - context, - *header.number(), - ) + runtime.offchain_worker_before_version_2(hash, *header.number()) }; + if let Err(e) = run { tracing::error!( target: LOG_TARGET, @@ -201,44 +323,6 @@ where } } -/// Inform the offchain worker about new imported blocks -pub async fn notification_future( - is_validator: bool, - client: Arc, - offchain: Arc>, - spawner: Spawner, - network_provider: Arc, -) where - Block: traits::Block, - Client: - ProvideRuntimeApi + sc_client_api::BlockchainEvents + Send + Sync + 'static, - Client::Api: OffchainWorkerApi, - Spawner: SpawnNamed, -{ - client - .import_notification_stream() - .for_each(move |n| { - if n.is_new_best { - spawner.spawn( - "offchain-on-block", - Some("offchain-worker"), - offchain - .on_block_imported(&n.header, network_provider.clone(), is_validator) - .boxed(), - ); - } else { - tracing::debug!( - target: LOG_TARGET, - "Skipping offchain workers for non-canon block: {:?}", - n.header, - ) - } - - ready(()) - }) - .await; -} - #[cfg(test)] mod tests { use super::*; @@ -348,8 +432,17 @@ mod tests { let header = client.header(client.chain_info().genesis_hash).unwrap().unwrap(); // when - let offchain = OffchainWorkers::new(client); - futures::executor::block_on(offchain.on_block_imported(&header, network, false)); + let offchain = OffchainWorkers::new(OffchainWorkerOptions { + runtime_api_provider: client, + keystore: None, + offchain_db: None::, + transaction_pool: Some(OffchainTransactionPoolFactory::new(pool.clone())), + network_provider: network, + is_validator: false, + enable_http_requests: false, + custom_extensions: |_| Vec::new(), + }); + futures::executor::block_on(offchain.on_block_imported(&header)); // then assert_eq!(pool.status().ready, 1); diff --git a/client/rpc-spec-v2/Cargo.toml b/client/rpc-spec-v2/Cargo.toml index c691b7b05fcb4..4f5c11212a9b2 100644 --- a/client/rpc-spec-v2/Cargo.toml +++ b/client/rpc-spec-v2/Cargo.toml @@ -46,3 +46,4 @@ sc-block-builder = { version = "0.10.0-dev", path = "../block-builder" } sc-service = { version = "0.10.0-dev", features = ["test-helpers"], path = "../service" } sc-utils = { version = "4.0.0-dev", path = "../utils" } assert_matches = "1.3.0" +pretty_assertions = "1.2.1" diff --git a/client/rpc-spec-v2/src/chain_head/chain_head.rs b/client/rpc-spec-v2/src/chain_head/chain_head.rs index 0f2d55f100929..bb3599c0e4ae5 100644 --- a/client/rpc-spec-v2/src/chain_head/chain_head.rs +++ b/client/rpc-spec-v2/src/chain_head/chain_head.rs @@ -420,13 +420,7 @@ where let res = client .executor() - .call( - hash, - &function, - &call_parameters, - client.execution_extensions().strategies().other, - CallContext::Offchain, - ) + .call(hash, &function, &call_parameters, CallContext::Offchain) .map(|result| { let result = format!("0x{:?}", HexDisplay::from(&result)); ChainHeadEvent::Done(ChainHeadResult { result }) diff --git a/client/rpc-spec-v2/src/chain_head/subscription/inner.rs b/client/rpc-spec-v2/src/chain_head/subscription/inner.rs index bdb14e8de7172..adab64a01c875 100644 --- a/client/rpc-spec-v2/src/chain_head/subscription/inner.rs +++ b/client/rpc-spec-v2/src/chain_head/subscription/inner.rs @@ -539,7 +539,6 @@ mod tests { genesis_block_builder, None, None, - None, Box::new(TaskExecutor::new()), client_config, ) diff --git a/client/rpc-spec-v2/src/chain_head/test_utils.rs b/client/rpc-spec-v2/src/chain_head/test_utils.rs index ee563debb4502..54c585932a744 100644 --- a/client/rpc-spec-v2/src/chain_head/test_utils.rs +++ b/client/rpc-spec-v2/src/chain_head/test_utils.rs @@ -217,6 +217,14 @@ impl> CallApiAt for ChainHeadMock fn state_at(&self, at: Block::Hash) -> Result { self.client.state_at(at) } + + fn initialize_extensions( + &self, + at: ::Hash, + extensions: &mut sp_api::Extensions, + ) -> Result<(), sp_api::ApiError> { + self.client.initialize_extensions(at, extensions) + } } impl> BlockBackend diff --git a/client/rpc-spec-v2/src/chain_head/tests.rs b/client/rpc-spec-v2/src/chain_head/tests.rs index cb6e65f859133..5dd3cc3da6d3f 100644 --- a/client/rpc-spec-v2/src/chain_head/tests.rs +++ b/client/rpc-spec-v2/src/chain_head/tests.rs @@ -191,6 +191,7 @@ async fn follow_with_runtime() { [\"0xbc9d89904f5b923f\",1],[\"0xc6e9a76309f39b09\",2],[\"0xdd718d5cc53262d4\",1],\ [\"0xcbca25e39f142387\",2],[\"0xf78b278be53f454c\",2],[\"0xab3c0572291feb8b\",1],\ [\"0xed99c5acb25eedf5\",3]],\"transactionVersion\":1,\"stateVersion\":1}"; + let runtime: RuntimeVersion = serde_json::from_str(runtime_str).unwrap(); let finalized_block_runtime = @@ -201,7 +202,7 @@ async fn follow_with_runtime() { finalized_block_runtime, with_runtime: false, }); - assert_eq!(event, expected); + pretty_assertions::assert_eq!(event, expected); // Import a new block without runtime changes. // The runtime field must be None in this case. @@ -1365,7 +1366,6 @@ async fn pin_block_references() { genesis_block_builder, None, None, - None, Box::new(TaskExecutor::new()), client_config, ) diff --git a/client/rpc/Cargo.toml b/client/rpc/Cargo.toml index f9c36bf57c684..a3574ed84d011 100644 --- a/client/rpc/Cargo.toml +++ b/client/rpc/Cargo.toml @@ -50,6 +50,7 @@ sp-consensus = { version = "0.10.0-dev", path = "../../primitives/consensus/comm tokio = "1.22.0" sp-io = { version = "23.0.0", path = "../../primitives/io" } substrate-test-runtime-client = { version = "2.0.0", path = "../../test-utils/runtime/client" } +pretty_assertions = "1.2.1" [features] test-helpers = [] diff --git a/client/rpc/src/author/mod.rs b/client/rpc/src/author/mod.rs index 00a126500e26d..feee22641ef34 100644 --- a/client/rpc/src/author/mod.rs +++ b/client/rpc/src/author/mod.rs @@ -37,10 +37,10 @@ use sc_transaction_pool_api::{ error::IntoPoolError, BlockHash, InPoolTransaction, TransactionFor, TransactionPool, TransactionSource, TxHash, }; -use sp_api::ProvideRuntimeApi; +use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_blockchain::HeaderBackend; use sp_core::Bytes; -use sp_keystore::KeystorePtr; +use sp_keystore::{KeystoreExt, KeystorePtr}; use sp_runtime::{generic, traits::Block as BlockT}; use sp_session::SessionKeys; @@ -122,8 +122,11 @@ where self.deny_unsafe.check_if_safe()?; let best_block_hash = self.client.info().best_hash; - self.client - .runtime_api() + let mut runtime_api = self.client.runtime_api(); + + runtime_api.register_extension(KeystoreExt::from(self.keystore.clone())); + + runtime_api .generate_session_keys(best_block_hash, None) .map(Into::into) .map_err(|api_err| Error::Client(Box::new(api_err)).into()) diff --git a/client/rpc/src/author/tests.rs b/client/rpc/src/author/tests.rs index 1f688e8e85e05..f48b2f9571428 100644 --- a/client/rpc/src/author/tests.rs +++ b/client/rpc/src/author/tests.rs @@ -66,8 +66,7 @@ struct TestSetup { impl Default for TestSetup { fn default() -> Self { let keystore = Arc::new(MemoryKeystore::new()); - let client_builder = substrate_test_runtime_client::TestClientBuilder::new(); - let client = Arc::new(client_builder.set_keystore(keystore.clone()).build()); + let client = Arc::new(substrate_test_runtime_client::TestClientBuilder::new().build()); let spawner = sp_core::testing::TaskExecutor::new(); let pool = diff --git a/client/rpc/src/state/state_full.rs b/client/rpc/src/state/state_full.rs index 20ca5f7131e71..9604d9165f987 100644 --- a/client/rpc/src/state/state_full.rs +++ b/client/rpc/src/state/state_full.rs @@ -198,13 +198,7 @@ where .and_then(|block| { self.client .executor() - .call( - block, - &method, - &call_data, - self.client.execution_extensions().strategies().other, - CallContext::Offchain, - ) + .call(block, &method, &call_data, CallContext::Offchain) .map(Into::into) }) .map_err(client_err) diff --git a/client/rpc/src/state/tests.rs b/client/rpc/src/state/tests.rs index 9e00a04abe386..7c73c1e1cd8da 100644 --- a/client/rpc/src/state/tests.rs +++ b/client/rpc/src/state/tests.rs @@ -522,7 +522,7 @@ async fn should_return_runtime_version() { let runtime_version = api.runtime_version(None.into()).unwrap(); let serialized = serde_json::to_string(&runtime_version).unwrap(); - assert_eq!(serialized, result); + pretty_assertions::assert_eq!(serialized, result); let deserialized: RuntimeVersion = serde_json::from_str(result).unwrap(); assert_eq!(deserialized, runtime_version); diff --git a/client/service/Cargo.toml b/client/service/Cargo.toml index b77a6ef58e6cd..4f280503fbbcb 100644 --- a/client/service/Cargo.toml +++ b/client/service/Cargo.toml @@ -69,7 +69,6 @@ sc-rpc-spec-v2 = { version = "0.10.0-dev", path = "../rpc-spec-v2" } sc-block-builder = { version = "0.10.0-dev", path = "../block-builder" } sc-informant = { version = "0.10.0-dev", path = "../informant" } sc-telemetry = { version = "4.0.0-dev", path = "../telemetry" } -sc-offchain = { version = "4.0.0-dev", path = "../offchain" } prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus", version = "0.10.0-dev" } sc-tracing = { version = "4.0.0-dev", path = "../tracing" } sc-sysinfo = { version = "6.0.0-dev", path = "../sysinfo" } diff --git a/client/service/src/builder.rs b/client/service/src/builder.rs index 166e1b8785511..6b537e7ee48d5 100644 --- a/client/service/src/builder.rs +++ b/client/service/src/builder.rs @@ -187,9 +187,7 @@ where let client = { let extensions = sc_client_api::execution_extensions::ExecutionExtensions::new( - config.execution_strategies.clone(), - Some(keystore_container.keystore()), - sc_offchain::OffchainDb::factory_from_backend(&*backend), + None, Arc::new(executor.clone()), ); @@ -322,19 +320,14 @@ where /// Shared network instance implementing a set of mandatory traits. pub trait SpawnTaskNetwork: - sc_offchain::NetworkProvider + NetworkStateInfo + NetworkStatusProvider + Send + Sync + 'static + NetworkStateInfo + NetworkStatusProvider + Send + Sync + 'static { } impl SpawnTaskNetwork for T where Block: BlockT, - T: sc_offchain::NetworkProvider - + NetworkStateInfo - + NetworkStatusProvider - + Send - + Sync - + 'static, + T: NetworkStateInfo + NetworkStatusProvider + Send + Sync + 'static, { } @@ -368,38 +361,6 @@ pub struct SpawnTasksParams<'a, TBl: BlockT, TCl, TExPool, TRpc, Backend> { pub telemetry: Option<&'a mut Telemetry>, } -/// Build a shared offchain workers instance. -pub fn build_offchain_workers( - config: &Configuration, - spawn_handle: SpawnTaskHandle, - client: Arc, - network: Arc, -) -> Option>> -where - TBl: BlockT, - TCl: Send + Sync + ProvideRuntimeApi + BlockchainEvents + 'static, - >::Api: sc_offchain::OffchainWorkerApi, -{ - let offchain_workers = Some(Arc::new(sc_offchain::OffchainWorkers::new(client.clone()))); - - // Inform the offchain worker about new imported blocks - if let Some(offchain) = offchain_workers.clone() { - spawn_handle.spawn( - "offchain-notifications", - Some("offchain-worker"), - sc_offchain::notification_future( - config.role.is_authority(), - client, - offchain, - Clone::clone(&spawn_handle), - network, - ), - ); - } - - offchain_workers -} - /// Spawn the tasks that are required to run a node. pub fn spawn_tasks( params: SpawnTasksParams, @@ -420,7 +381,6 @@ where + Send + 'static, >::Api: sp_api::Metadata - + sc_offchain::OffchainWorkerApi + sp_transaction_pool::runtime_api::TaggedTransactionQueue + sp_session::SessionKeys + sp_api::ApiExt, @@ -451,6 +411,7 @@ where client.clone(), chain_info.best_hash, config.dev_key_seed.clone().map(|s| vec![s]).unwrap_or_default(), + keystore.clone(), ) .map_err(|e| Error::Application(Box::new(e)))?; diff --git a/client/service/src/client/call_executor.rs b/client/service/src/client/call_executor.rs index 7f83d62874c8e..facde72321db4 100644 --- a/client/service/src/client/call_executor.rs +++ b/client/service/src/client/call_executor.rs @@ -22,14 +22,10 @@ use sc_client_api::{ }; use sc_executor::{RuntimeVersion, RuntimeVersionOf}; use sp_api::{ProofRecorder, StorageTransactionCache}; -use sp_core::{ - traits::{CallContext, CodeExecutor, RuntimeCode}, - ExecutionContext, -}; +use sp_core::traits::{CallContext, CodeExecutor, RuntimeCode}; +use sp_externalities::Extensions; use sp_runtime::{generic::BlockId, traits::Block as BlockT}; -use sp_state_machine::{ - backend::AsTrieBackend, ExecutionStrategy, Ext, OverlayedChanges, StateMachine, StorageProof, -}; +use sp_state_machine::{backend::AsTrieBackend, Ext, OverlayedChanges, StateMachine, StorageProof}; use std::{cell::RefCell, sync::Arc}; /// Call executor that executes methods locally, querying all required @@ -166,7 +162,6 @@ where at_hash: Block::Hash, method: &str, call_data: &[u8], - strategy: ExecutionStrategy, context: CallContext, ) -> sp_blockchain::Result> { let mut changes = OverlayedChanges::default(); @@ -180,11 +175,7 @@ where let runtime_code = self.check_override(runtime_code, &state, at_hash)?.0; - let extensions = self.execution_extensions.extensions( - at_hash, - at_number, - ExecutionContext::OffchainCall(None), - ); + let mut extensions = self.execution_extensions.extensions(at_hash, at_number); let mut sm = StateMachine::new( &state, @@ -192,14 +183,13 @@ where &self.executor, method, call_data, - extensions, + &mut extensions, &runtime_code, context, ) .set_parent_hash(at_hash); - sm.execute_using_consensus_failure_handler(strategy.get_manager()) - .map_err(Into::into) + sm.execute().map_err(Into::into) } fn contextual_call( @@ -210,22 +200,13 @@ where changes: &RefCell, storage_transaction_cache: Option<&RefCell>>, recorder: &Option>, - context: ExecutionContext, + call_context: CallContext, + extensions: &RefCell, ) -> Result, sp_blockchain::Error> { let mut storage_transaction_cache = storage_transaction_cache.map(|c| c.borrow_mut()); - let at_number = - self.backend.blockchain().expect_block_number_from_id(&BlockId::Hash(at_hash))?; let state = self.backend.state_at(at_hash)?; - let call_context = match context { - ExecutionContext::OffchainCall(_) => CallContext::Offchain, - _ => CallContext::Onchain, - }; - - let (execution_manager, extensions) = - self.execution_extensions.manager_and_extensions(at_hash, at_number, context); - let changes = &mut *changes.borrow_mut(); // It is important to extract the runtime code here before we create the proof @@ -236,6 +217,7 @@ where let runtime_code = state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?; let runtime_code = self.check_override(runtime_code, &state, at_hash)?.0; + let mut extensions = extensions.borrow_mut(); match recorder { Some(recorder) => { @@ -251,13 +233,13 @@ where &self.executor, method, call_data, - extensions, + &mut extensions, &runtime_code, call_context, ) .with_storage_transaction_cache(storage_transaction_cache.as_deref_mut()) .set_parent_hash(at_hash); - state_machine.execute_using_consensus_failure_handler(execution_manager) + state_machine.execute() }, None => { let mut state_machine = StateMachine::new( @@ -266,13 +248,13 @@ where &self.executor, method, call_data, - extensions, + &mut extensions, &runtime_code, call_context, ) .with_storage_transaction_cache(storage_transaction_cache.as_deref_mut()) .set_parent_hash(at_hash); - state_machine.execute_using_consensus_failure_handler(execution_manager) + state_machine.execute() }, } .map_err(Into::into) @@ -311,11 +293,7 @@ where method, call_data, &runtime_code, - self.execution_extensions.extensions( - at_hash, - at_number, - ExecutionContext::OffchainCall(None), - ), + &mut self.execution_extensions.extensions(at_hash, at_number), ) .map_err(Into::into) } @@ -411,7 +389,6 @@ mod tests { backend.clone(), executor.clone(), genesis_block_builder, - None, Box::new(TaskExecutor::new()), None, None, @@ -430,8 +407,6 @@ mod tests { ) .unwrap(), execution_extensions: Arc::new(ExecutionExtensions::new( - Default::default(), - None, None, Arc::new(executor.clone()), )), @@ -486,7 +461,6 @@ mod tests { backend.clone(), executor.clone(), genesis_block_builder, - None, Box::new(TaskExecutor::new()), None, None, diff --git a/client/service/src/client/client.rs b/client/service/src/client/client.rs index 3b1a526154d74..8c4b14fbddc24 100644 --- a/client/service/src/client/client.rs +++ b/client/service/src/client/client.rs @@ -62,10 +62,8 @@ use sp_core::{ well_known_keys, ChildInfo, ChildType, PrefixedStorageKey, StorageChild, StorageData, StorageKey, }, - traits::SpawnNamed, + traits::{CallContext, SpawnNamed}, }; -#[cfg(feature = "test-helpers")] -use sp_keystore::KeystorePtr; use sp_runtime::{ generic::{BlockId, SignedBlock}, traits::{ @@ -161,7 +159,6 @@ pub fn new_in_mem( backend: Arc>, executor: E, genesis_block_builder: G, - keystore: Option, prometheus_registry: Option, telemetry: Option, spawn_handle: Box, @@ -181,7 +178,6 @@ where backend, executor, genesis_block_builder, - keystore, spawn_handle, prometheus_registry, telemetry, @@ -224,7 +220,6 @@ pub fn new_with_backend( backend: Arc, executor: E, genesis_block_builder: G, - keystore: Option, spawn_handle: Box, prometheus_registry: Option, telemetry: Option, @@ -239,12 +234,7 @@ where Block: BlockT, B: backend::LocalBackend + 'static, { - let extensions = ExecutionExtensions::new( - Default::default(), - keystore, - sc_offchain::OffchainDb::factory_from_backend(&*backend), - Arc::new(executor.clone()), - ); + let extensions = ExecutionExtensions::new(None, Arc::new(executor.clone())); let call_executor = LocalCallExecutor::new(backend.clone(), executor, config.clone(), extensions)?; @@ -875,12 +865,12 @@ where // We should enact state, but don't have any storage changes, so we need to execute the // block. (true, None, Some(ref body)) => { - let runtime_api = self.runtime_api(); - let execution_context = import_block.origin.into(); + let mut runtime_api = self.runtime_api(); + + runtime_api.set_call_context(CallContext::Onchain); - runtime_api.execute_block_with_context( + runtime_api.execute_block( *parent_hash, - execution_context, Block::new(import_block.header.clone(), body.clone()), )?; @@ -1727,7 +1717,8 @@ where params.overlayed_changes, Some(params.storage_transaction_cache), params.recorder, - params.context, + params.call_context, + params.extensions, ) .map_err(Into::into) } @@ -1739,6 +1730,18 @@ where fn state_at(&self, at: Block::Hash) -> Result { self.state_at(at).map_err(Into::into) } + + fn initialize_extensions( + &self, + at: Block::Hash, + extensions: &mut sp_externalities::Extensions, + ) -> Result<(), sp_api::ApiError> { + let block_number = self.expect_block_number_from_id(&BlockId::Hash(at))?; + + extensions.merge(self.executor.execution_extensions().extensions(at, block_number)); + + Ok(()) + } } /// NOTE: only use this implementation when you are sure there are NO consensus-level BlockImport diff --git a/client/service/src/config.rs b/client/service/src/config.rs index 52e17c95e6783..39b7ee0507906 100644 --- a/client/service/src/config.rs +++ b/client/service/src/config.rs @@ -18,7 +18,6 @@ //! Service configuration. -pub use sc_client_api::execution_extensions::{ExecutionStrategies, ExecutionStrategy}; pub use sc_client_db::{BlocksPruning, Database, DatabaseSource, PruningMode}; pub use sc_executor::{WasmExecutionMethod, WasmtimeInstantiationStrategy}; pub use sc_network::{ @@ -81,8 +80,6 @@ pub struct Configuration { /// over on-chain runtimes when the spec version matches. Set to `None` to /// disable overrides (default). pub wasm_runtime_overrides: Option, - /// Execution strategies. - pub execution_strategies: ExecutionStrategies, /// JSON-RPC server binding address. pub rpc_addr: Option, /// Maximum number of connections for JSON-RPC server. diff --git a/client/service/src/lib.rs b/client/service/src/lib.rs index 4a896ecc87263..c987c2471907d 100644 --- a/client/service/src/lib.rs +++ b/client/service/src/lib.rs @@ -55,8 +55,8 @@ use sp_runtime::{ pub use self::{ builder::{ - build_network, build_offchain_workers, new_client, new_db_backend, new_full_client, - new_full_parts, new_full_parts_with_genesis_builder, new_native_or_wasm_executor, + build_network, new_client, new_db_backend, new_full_client, new_full_parts, + new_full_parts_with_genesis_builder, new_native_or_wasm_executor, new_wasm_executor, spawn_tasks, BuildNetworkParams, KeystoreContainer, NetworkStarter, SpawnTasksParams, TFullBackend, TFullCallExecutor, TFullClient, }, diff --git a/client/service/test/src/client/mod.rs b/client/service/test/src/client/mod.rs index 9c490a47a3b14..c40ac33da4bb9 100644 --- a/client/service/test/src/client/mod.rs +++ b/client/service/test/src/client/mod.rs @@ -37,9 +37,7 @@ use sp_runtime::{ traits::{BlakeTwo256, Block as BlockT, Header as HeaderT}, ConsensusEngineId, Justifications, StateVersion, }; -use sp_state_machine::{ - backend::Backend as _, ExecutionStrategy, InMemoryBackend, OverlayedChanges, StateMachine, -}; +use sp_state_machine::{backend::Backend as _, InMemoryBackend, OverlayedChanges, StateMachine}; use sp_storage::{ChildInfo, StorageKey}; use sp_trie::{LayoutV0, TrieConfiguration}; use std::{collections::HashSet, sync::Arc}; @@ -90,11 +88,11 @@ fn construct_block( &new_native_or_wasm_executor(), "Core_initialize_block", &header.encode(), - Default::default(), + &mut Default::default(), &runtime_code, CallContext::Onchain, ) - .execute(ExecutionStrategy::NativeElseWasm) + .execute() .unwrap(); for tx in transactions.iter() { @@ -104,11 +102,11 @@ fn construct_block( &new_native_or_wasm_executor(), "BlockBuilder_apply_extrinsic", &tx.encode(), - Default::default(), + &mut Default::default(), &runtime_code, CallContext::Onchain, ) - .execute(ExecutionStrategy::NativeElseWasm) + .execute() .unwrap(); } @@ -118,11 +116,11 @@ fn construct_block( &new_native_or_wasm_executor(), "BlockBuilder_finalize_block", &[], - Default::default(), + &mut Default::default(), &runtime_code, CallContext::Onchain, ) - .execute(ExecutionStrategy::NativeElseWasm) + .execute() .unwrap(); header = Header::decode(&mut &ret_data[..]).unwrap(); @@ -189,11 +187,11 @@ fn construct_genesis_should_work_with_native() { &new_native_or_wasm_executor(), "Core_execute_block", &b1data, - Default::default(), + &mut Default::default(), &runtime_code, CallContext::Onchain, ) - .execute(ExecutionStrategy::NativeElseWasm) + .execute() .unwrap(); } @@ -220,11 +218,11 @@ fn construct_genesis_should_work_with_wasm() { &new_native_or_wasm_executor(), "Core_execute_block", &b1data, - Default::default(), + &mut Default::default(), &runtime_code, CallContext::Onchain, ) - .execute(ExecutionStrategy::AlwaysWasm) + .execute() .unwrap(); } @@ -1670,22 +1668,21 @@ fn storage_keys_prefix_and_start_key_works() { let block_hash = client.info().best_hash; - let child_root = b":child_storage:default:child".to_vec(); + let child_root = array_bytes::bytes2hex("", b":child_storage:default:child"); let prefix = StorageKey(array_bytes::hex2bytes_unchecked("3a")); let child_prefix = StorageKey(b"sec".to_vec()); let res: Vec<_> = client .storage_keys(block_hash, Some(&prefix), None) .unwrap() - .map(|x| x.0) + .map(|x| array_bytes::bytes2hex("", &x.0)) .collect(); assert_eq!( res, [ - child_root.clone(), - array_bytes::hex2bytes_unchecked("3a636f6465"), //":code" - array_bytes::hex2bytes_unchecked("3a65787472696e7369635f696e646578"), //":extrinsic_index" - array_bytes::hex2bytes_unchecked("3a686561707061676573"), //":heappages" + &child_root, + "3a636f6465", //":code" + "3a65787472696e7369635f696e646578", //":extrinsic_index" ] ); @@ -1696,15 +1693,9 @@ fn storage_keys_prefix_and_start_key_works() { Some(&StorageKey(array_bytes::hex2bytes_unchecked("3a636f6465"))), ) .unwrap() - .map(|x| x.0) + .map(|x| array_bytes::bytes2hex("", &x.0)) .collect(); - assert_eq!( - res, - [ - array_bytes::hex2bytes_unchecked("3a65787472696e7369635f696e646578"), - array_bytes::hex2bytes_unchecked("3a686561707061676573") - ] - ); + assert_eq!(res, ["3a65787472696e7369635f696e646578",]); let res: Vec<_> = client .storage_keys( @@ -1737,7 +1728,7 @@ fn storage_keys_works() { sp_tracing::try_init_simple(); let expected_keys = - substrate_test_runtime::storage_key_generator::get_expected_storage_hashed_keys(); + substrate_test_runtime::storage_key_generator::get_expected_storage_hashed_keys(false); let client = substrate_test_runtime_client::new(); let block_hash = client.info().best_hash; @@ -1776,10 +1767,10 @@ fn storage_keys_works() { res, expected_keys .iter() - .filter(|&i| i > &"3a636f64".to_string()) + .filter(|&i| *i > "3a636f64") .take(8) .cloned() - .collect::>() + .collect::>() ); // Starting at a complete key the first key is skipped. @@ -1797,10 +1788,10 @@ fn storage_keys_works() { res, expected_keys .iter() - .filter(|&i| i > &"3a636f6465".to_string()) + .filter(|&i| *i > "3a636f6465") .take(8) .cloned() - .collect::>() + .collect::>() ); const SOME_BALANCE_KEY : &str = "26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9e2c1dc507e2035edbbd8776c440d870460c57f0008067cc01c5ff9eb2e2f9b3a94299a915a91198bd1021a6c55596f57"; @@ -1818,10 +1809,10 @@ fn storage_keys_works() { res, expected_keys .iter() - .filter(|&i| i > &SOME_BALANCE_KEY.to_string()) + .filter(|&i| *i > SOME_BALANCE_KEY) .take(8) .cloned() - .collect::>() + .collect::>() ); } @@ -1850,7 +1841,6 @@ fn cleans_up_closed_notification_sinks_on_block_import() { genesis_block_builder, None, None, - None, Box::new(TaskExecutor::new()), client_config, ) diff --git a/client/service/test/src/lib.rs b/client/service/test/src/lib.rs index 11c672db8cb90..38a811acc7401 100644 --- a/client/service/test/src/lib.rs +++ b/client/service/test/src/lib.rs @@ -245,7 +245,6 @@ fn node_config< chain_spec: Box::new((*spec).clone()), wasm_method: Default::default(), wasm_runtime_overrides: Default::default(), - execution_strategies: Default::default(), rpc_addr: Default::default(), rpc_max_connections: Default::default(), rpc_cors: None, diff --git a/client/statement-store/src/lib.rs b/client/statement-store/src/lib.rs index 4acb89a05f7d1..3b42641d9c5ab 100644 --- a/client/statement-store/src/lib.rs +++ b/client/statement-store/src/lib.rs @@ -59,7 +59,9 @@ use sp_blockchain::HeaderBackend; use sp_core::{hexdisplay::HexDisplay, traits::SpawnNamed, Decode, Encode}; use sp_runtime::traits::Block as BlockT; use sp_statement_store::{ - runtime_api::{InvalidStatement, StatementSource, ValidStatement, ValidateStatement}, + runtime_api::{ + InvalidStatement, StatementSource, StatementStoreExt, ValidStatement, ValidateStatement, + }, AccountId, BlockHash, Channel, DecryptionKey, Hash, NetworkPriority, Proof, Result, Statement, SubmitResult, Topic, }; @@ -491,8 +493,7 @@ impl Store { + 'static, Client::Api: ValidateStatement, { - let store = Arc::new(Self::new(path, options, client.clone(), prometheus)?); - client.execution_extensions().register_statement_store(store.clone()); + let store = Arc::new(Self::new(path, options, client, prometheus)?); // Perform periodic statement store maintenance let worker_store = store.clone(); @@ -696,6 +697,11 @@ impl Store { fn set_time(&mut self, time: u64) { self.time_override = Some(time); } + + /// Returns `self` as [`StatementStoreExt`]. + pub fn as_statement_store_ext(self: Arc) -> StatementStoreExt { + StatementStoreExt::new(self) + } } impl StatementStore for Store { diff --git a/client/transaction-pool/api/src/lib.rs b/client/transaction-pool/api/src/lib.rs index e7b3a9c5e16f8..32fe30f4584f0 100644 --- a/client/transaction-pool/api/src/lib.rs +++ b/client/transaction-pool/api/src/lib.rs @@ -29,12 +29,7 @@ use sp_runtime::{ generic::BlockId, traits::{Block as BlockT, Member, NumberFor}, }; -use std::{ - collections::HashMap, - hash::Hash, - pin::Pin, - sync::{Arc, Weak}, -}; +use std::{collections::HashMap, hash::Hash, marker::PhantomData, pin::Pin, sync::Arc}; const LOG_TARGET: &str = "txpool::api"; @@ -354,6 +349,22 @@ pub trait LocalTransactionPool: Send + Sync { ) -> Result; } +impl LocalTransactionPool for Arc { + type Block = T::Block; + + type Hash = T::Hash; + + type Error = T::Error; + + fn submit_local( + &self, + at: ::Hash, + xt: LocalTransactionFor, + ) -> Result { + (**self).submit_local(at, xt) + } +} + /// An abstraction for [`LocalTransactionPool`] /// /// We want to use a transaction pool in [`OffchainTransactionPoolFactory`] in a `Arc` without @@ -396,15 +407,13 @@ impl OffchainSubmitTransaction for TP /// the wasm execution environment to send transactions from an offchain call to the runtime. #[derive(Clone)] pub struct OffchainTransactionPoolFactory { - // To break retain cycle between `Client` and `TransactionPool` we require this - // extension to be a `Weak` reference. - pool: Weak>, + pool: Arc>, } impl OffchainTransactionPoolFactory { /// Creates a new instance using the given `tx_pool`. - pub fn new + 'static>(tx_pool: &Arc) -> Self { - Self { pool: Arc::downgrade(tx_pool) as Weak<_> } + pub fn new + 'static>(tx_pool: T) -> Self { + Self { pool: Arc::new(tx_pool) as Arc<_> } } /// Returns an instance of [`TransactionPoolExt`] bound to the given `block_hash`. @@ -419,7 +428,7 @@ impl OffchainTransactionPoolFactory { /// Wraps a `pool` and `block_hash` to implement [`sp_core::offchain::TransactionPool`]. struct OffchainTransactionPool { block_hash: Block::Hash, - pool: Weak>, + pool: Arc>, } impl sp_core::offchain::TransactionPool for OffchainTransactionPool { @@ -436,7 +445,7 @@ impl sp_core::offchain::TransactionPool for OffchainTransactionPo }, }; - self.pool.upgrade().ok_or(())?.submit_at(self.block_hash, extrinsic) + self.pool.submit_at(self.block_hash, extrinsic) } } @@ -463,6 +472,29 @@ mod v1_compatible { } } +/// Transaction pool that rejects all submitted transactions. +/// +/// Could be used for example in tests. +pub struct RejectAllTxPool(PhantomData); + +impl Default for RejectAllTxPool { + fn default() -> Self { + Self(PhantomData) + } +} + +impl LocalTransactionPool for RejectAllTxPool { + type Block = Block; + + type Hash = Block::Hash; + + type Error = error::Error; + + fn submit_local(&self, _: Block::Hash, _: Block::Extrinsic) -> Result { + Err(error::Error::ImmediatelyDropped) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/client/transaction-pool/src/lib.rs b/client/transaction-pool/src/lib.rs index 1b438bd7e4f2f..80e5925194c68 100644 --- a/client/transaction-pool/src/lib.rs +++ b/client/transaction-pool/src/lib.rs @@ -52,8 +52,8 @@ use std::{ use graph::{ExtrinsicHash, IsValidator}; use sc_transaction_pool_api::{ error::Error as TxPoolError, ChainEvent, ImportNotificationStream, MaintainedTransactionPool, - OffchainTransactionPoolFactory, PoolFuture, PoolStatus, ReadyTransactions, TransactionFor, - TransactionPool, TransactionSource, TransactionStatusStreamFor, TxHash, + PoolFuture, PoolStatus, ReadyTransactions, TransactionFor, TransactionPool, TransactionSource, + TransactionStatusStreamFor, TxHash, }; use sp_core::traits::SpawnEssentialNamed; use sp_runtime::{ @@ -396,11 +396,6 @@ where client.usage_info().chain.finalized_hash, )); - // make transaction pool available for off-chain runtime calls. - client - .execution_extensions() - .register_transaction_pool_factory(OffchainTransactionPoolFactory::new(&pool)); - pool } } diff --git a/client/transaction-pool/tests/pool.rs b/client/transaction-pool/tests/pool.rs index ac029d71700da..4adf811b42521 100644 --- a/client/transaction-pool/tests/pool.rs +++ b/client/transaction-pool/tests/pool.rs @@ -39,7 +39,7 @@ use sp_runtime::{ }; use std::{collections::BTreeSet, pin::Pin, sync::Arc}; use substrate_test_runtime_client::{ - runtime::{Block, Extrinsic, ExtrinsicBuilder, Hash, Header, Index, Transfer, TransferData}, + runtime::{Block, Extrinsic, ExtrinsicBuilder, Hash, Header, Nonce, Transfer, TransferData}, AccountKeyring::*, ClientBlockImportExt, }; @@ -119,7 +119,7 @@ fn early_nonce_should_be_culled() { .ready() .map(|a| TransferData::try_from(&a.data).unwrap().nonce) .collect(); - assert_eq!(pending, Vec::::new()); + assert_eq!(pending, Vec::::new()); } #[test] @@ -132,7 +132,7 @@ fn late_nonce_should_be_queued() { .ready() .map(|a| TransferData::try_from(&a.data).unwrap().nonce) .collect(); - assert_eq!(pending, Vec::::new()); + assert_eq!(pending, Vec::::new()); block_on(pool.submit_one(&BlockId::number(0), SOURCE, uxt(Alice, 209))).unwrap(); let pending: Vec<_> = pool @@ -182,7 +182,7 @@ fn should_ban_invalid_transactions() { .ready() .map(|a| TransferData::try_from(&a.data).unwrap().nonce) .collect(); - assert_eq!(pending, Vec::::new()); + assert_eq!(pending, Vec::::new()); // then block_on(pool.submit_one(&BlockId::number(0), SOURCE, uxt.clone())).unwrap_err(); diff --git a/frame/alliance/src/benchmarking.rs b/frame/alliance/src/benchmarking.rs index 92bf1ae4468df..eb32c6c466c91 100644 --- a/frame/alliance/src/benchmarking.rs +++ b/frame/alliance/src/benchmarking.rs @@ -27,7 +27,7 @@ use sp_std::{ use frame_benchmarking::v1::{account, benchmarks_instance_pallet, BenchmarkError}; use frame_support::traits::{EnsureOrigin, Get, UnfilteredDispatchable}; -use frame_system::{Pallet as System, RawOrigin as SystemOrigin}; +use frame_system::{pallet_prelude::BlockNumberFor, Pallet as System, RawOrigin as SystemOrigin}; use super::{Call as AllianceCall, Pallet as Alliance, *}; @@ -432,7 +432,7 @@ benchmarks_instance_pallet! { false, )?; - System::::set_block_number(T::BlockNumber::max_value()); + System::::set_block_number(BlockNumberFor::::max_value()); }: close(SystemOrigin::Signed(voter), last_hash.clone(), index, Weight::MAX, bytes_in_storage) verify { @@ -504,7 +504,7 @@ benchmarks_instance_pallet! { } // caller is prime, prime already votes aye by creating the proposal - System::::set_block_number(T::BlockNumber::max_value()); + System::::set_block_number(BlockNumberFor::::max_value()); }: close(SystemOrigin::Signed(voter), last_hash.clone(), index, Weight::MAX, bytes_in_storage) verify { diff --git a/frame/alliance/src/lib.rs b/frame/alliance/src/lib.rs index 6c034454cf7c0..c103f975f23be 100644 --- a/frame/alliance/src/lib.rs +++ b/frame/alliance/src/lib.rs @@ -309,7 +309,7 @@ pub mod pallet { /// The number of blocks a member must wait between giving a retirement notice and retiring. /// Supposed to be greater than time required to `kick_member`. - type RetirementPeriod: Get; + type RetirementPeriod: Get>; } #[pallet::error] @@ -405,11 +405,12 @@ pub mod pallet { pub struct GenesisConfig, I: 'static = ()> { pub fellows: Vec, pub allies: Vec, + #[serde(skip)] pub phantom: PhantomData<(T, I)>, } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { for m in self.fellows.iter().chain(self.allies.iter()) { assert!(Pallet::::has_identity(m).is_ok(), "Member does not set identity!"); @@ -476,7 +477,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn retiring_members)] pub type RetiringMembers, I: 'static = ()> = - StorageMap<_, Blake2_128Concat, T::AccountId, T::BlockNumber, OptionQuery>; + StorageMap<_, Blake2_128Concat, T::AccountId, BlockNumberFor, OptionQuery>; /// The current list of accounts deemed unscrupulous. These accounts non grata cannot submit /// candidacy. diff --git a/frame/alliance/src/mock.rs b/frame/alliance/src/mock.rs index e1da028f44576..f04e7e414ed94 100644 --- a/frame/alliance/src/mock.rs +++ b/frame/alliance/src/mock.rs @@ -20,7 +20,6 @@ pub use sp_core::H256; use sp_runtime::traits::Hash; pub use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; @@ -28,7 +27,7 @@ use sp_std::convert::{TryFrom, TryInto}; pub use frame_support::{ assert_noop, assert_ok, ord_parameter_types, parameter_types, - traits::{EitherOfDiverse, GenesisBuild, SortedMembers}, + traits::{EitherOfDiverse, SortedMembers}, BoundedVec, }; use frame_system::{EnsureRoot, EnsureSignedBy}; @@ -52,13 +51,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = (); @@ -238,14 +236,10 @@ impl Config for Test { type RetirementPeriod = RetirementPeriod; } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances, @@ -256,7 +250,7 @@ frame_support::construct_runtime!( ); pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![ @@ -274,14 +268,12 @@ pub fn new_test_ext() -> sp_io::TestExternalities { .assimilate_storage(&mut t) .unwrap(); - GenesisBuild::::assimilate_storage( - &pallet_alliance::GenesisConfig { - fellows: vec![], - allies: vec![], - phantom: Default::default(), - }, - &mut t, - ) + pallet_alliance::GenesisConfig:: { + fellows: vec![], + allies: vec![], + phantom: Default::default(), + } + .assimilate_storage(&mut t) .unwrap(); let mut ext = sp_io::TestExternalities::new(t); diff --git a/frame/asset-conversion/src/lib.rs b/frame/asset-conversion/src/lib.rs index 68a0210b40058..5887295f973c3 100644 --- a/frame/asset-conversion/src/lib.rs +++ b/frame/asset-conversion/src/lib.rs @@ -72,7 +72,10 @@ use frame_support::{ ensure, traits::tokens::{AssetId, Balance}, }; -use frame_system::{ensure_signed, pallet_prelude::OriginFor}; +use frame_system::{ + ensure_signed, + pallet_prelude::{BlockNumberFor, OriginFor}, +}; pub use pallet::*; use sp_arithmetic::traits::Unsigned; use sp_runtime::{ @@ -357,7 +360,7 @@ pub mod pallet { } #[pallet::hooks] - impl Hooks for Pallet { + impl Hooks> for Pallet { fn integrity_test() { assert!( T::MaxSwapPathLength::get() > 1, diff --git a/frame/asset-conversion/src/mock.rs b/frame/asset-conversion/src/mock.rs index 34d2eeb273ca8..2b587161f1544 100644 --- a/frame/asset-conversion/src/mock.rs +++ b/frame/asset-conversion/src/mock.rs @@ -31,18 +31,13 @@ use frame_system::{EnsureSigned, EnsureSignedBy}; use sp_arithmetic::Permill; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{AccountIdConversion, BlakeTwo256, IdentityLookup}, + BuildStorage, }; - -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances, @@ -58,13 +53,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u128; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); @@ -183,7 +177,7 @@ impl Config for Test { } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10000), (2, 20000), (3, 30000), (4, 40000)], diff --git a/frame/asset-rate/src/mock.rs b/frame/asset-rate/src/mock.rs index 2d90fcfecd79e..33a134628c863 100644 --- a/frame/asset-rate/src/mock.rs +++ b/frame/asset-rate/src/mock.rs @@ -21,18 +21,14 @@ use crate as pallet_asset_rate; use frame_support::traits::{ConstU16, ConstU64}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, AssetRate: pallet_asset_rate, @@ -47,13 +43,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -96,5 +91,5 @@ impl pallet_asset_rate::Config for Test { // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } diff --git a/frame/assets/src/lib.rs b/frame/assets/src/lib.rs index 4b91f5184299d..363a99701b56a 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -380,7 +380,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { for (id, owner, is_sufficient, min_balance) in &self.assets { assert!(!Asset::::contains_key(id), "Asset id already in use"); diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index 09d2bd2296088..32ad02da90412 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -23,25 +23,21 @@ use crate as pallet_assets; use codec::Encode; use frame_support::{ construct_runtime, parameter_types, - traits::{AsEnsureOriginWithArg, ConstU32, ConstU64, GenesisBuild}, + traits::{AsEnsureOriginWithArg, ConstU32, ConstU64}, }; use sp_core::H256; use sp_io::storage; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Assets: pallet_assets::{Pallet, Call, Storage, Event}, } @@ -56,13 +52,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); @@ -205,7 +200,7 @@ pub(crate) fn take_hooks() -> Vec { } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); let config: pallet_assets::GenesisConfig = pallet_assets::GenesisConfig { assets: vec![ diff --git a/frame/atomic-swap/src/lib.rs b/frame/atomic-swap/src/lib.rs index 2d93887b82596..8094c06030120 100644 --- a/frame/atomic-swap/src/lib.rs +++ b/frame/atomic-swap/src/lib.rs @@ -50,6 +50,7 @@ use frame_support::{ weights::Weight, RuntimeDebugNoBound, }; +use frame_system::pallet_prelude::BlockNumberFor; use scale_info::TypeInfo; use sp_io::hashing::blake2_256; use sp_runtime::RuntimeDebug; @@ -69,7 +70,7 @@ pub struct PendingSwap { /// Action of this swap. pub action: T::SwapAction, /// End block of the lock. - pub end_block: T::BlockNumber, + pub end_block: BlockNumberFor, } /// Hashed proof type. @@ -249,7 +250,7 @@ pub mod pallet { target: T::AccountId, hashed_proof: HashedProof, action: T::SwapAction, - duration: T::BlockNumber, + duration: BlockNumberFor, ) -> DispatchResult { let source = ensure_signed(origin)?; ensure!( diff --git a/frame/atomic-swap/src/tests.rs b/frame/atomic-swap/src/tests.rs index 53ccd64bb2731..858417e8007fb 100644 --- a/frame/atomic-swap/src/tests.rs +++ b/frame/atomic-swap/src/tests.rs @@ -6,20 +6,16 @@ use crate as pallet_atomic_swap; use frame_support::traits::{ConstU32, ConstU64}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, AtomicSwap: pallet_atomic_swap::{Pallet, Call, Event}, } @@ -31,14 +27,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -78,7 +73,7 @@ const A: u64 = 1; const B: u64 = 2; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let genesis = pallet_balances::GenesisConfig:: { balances: vec![(A, 100), (B, 200)] }; genesis.assimilate_storage(&mut t).unwrap(); t.into() diff --git a/frame/aura/src/lib.rs b/frame/aura/src/lib.rs index e02d24d7c237e..7a1969d905fcc 100644 --- a/frame/aura/src/lib.rs +++ b/frame/aura/src/lib.rs @@ -102,7 +102,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(_: T::BlockNumber) -> Weight { + fn on_initialize(_: BlockNumberFor) -> Weight { if let Some(new_slot) = Self::current_slot_from_digests() { let current_slot = CurrentSlot::::get(); @@ -134,7 +134,7 @@ pub mod pallet { } #[cfg(feature = "try-runtime")] - fn try_state(_: T::BlockNumber) -> Result<(), sp_runtime::TryRuntimeError> { + fn try_state(_: BlockNumberFor) -> Result<(), sp_runtime::TryRuntimeError> { Self::do_try_state() } } @@ -159,7 +159,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { Pallet::::initialize_authorities(&self.authorities); } diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index 5ae443b4f7685..53b87ff36ec60 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -22,25 +22,18 @@ use crate as pallet_aura; use frame_support::{ parameter_types, - traits::{ConstU32, ConstU64, DisabledValidators, GenesisBuild}, + traits::{ConstU32, ConstU64, DisabledValidators}, }; use sp_consensus_aura::{ed25519::AuthorityId, AuthorityIndex}; use sp_core::H256; -use sp_runtime::{ - testing::{Header, UintAuthorityId}, - traits::IdentityLookup, -}; +use sp_runtime::{testing::UintAuthorityId, traits::IdentityLookup, BuildStorage}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, Aura: pallet_aura::{Pallet, Storage, Config}, } @@ -52,14 +45,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -111,7 +103,7 @@ impl pallet_aura::Config for Test { } fn build_ext(authorities: Vec) -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_aura::GenesisConfig:: { authorities: authorities.into_iter().map(|a| UintAuthorityId(a).to_public_key()).collect(), } diff --git a/frame/authority-discovery/src/lib.rs b/frame/authority-discovery/src/lib.rs index 6365c95359472..87b743ae19677 100644 --- a/frame/authority-discovery/src/lib.rs +++ b/frame/authority-discovery/src/lib.rs @@ -59,14 +59,16 @@ pub mod pallet { pub(super) type NextKeys = StorageValue<_, WeakBoundedVec, ValueQuery>; - #[derive(Default)] + #[derive(frame_support::DefaultNoBound)] #[pallet::genesis_config] - pub struct GenesisConfig { + pub struct GenesisConfig { pub keys: Vec, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { Pallet::::initialize_keys(&self.keys) } @@ -168,30 +170,26 @@ mod tests { use crate as pallet_authority_discovery; use frame_support::{ parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild}, + traits::{ConstU32, ConstU64}, }; use sp_application_crypto::Pair; use sp_authority_discovery::AuthorityPair; use sp_core::{crypto::key_types, H256}; use sp_io::TestExternalities; use sp_runtime::{ - testing::{Header, UintAuthorityId}, + testing::UintAuthorityId, traits::{ConvertInto, IdentityLookup, OpaqueKeys}, - KeyTypeId, Perbill, + BuildStorage, KeyTypeId, Perbill, }; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, - AuthorityDiscovery: pallet_authority_discovery::{Pallet, Config}, + AuthorityDiscovery: pallet_authority_discovery::{Pallet, Config}, } ); @@ -233,14 +231,13 @@ mod tests { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AuthorityId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -308,13 +305,11 @@ mod tests { .collect::>(); // Build genesis. - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); - GenesisBuild::::assimilate_storage( - &pallet_authority_discovery::GenesisConfig { keys: vec![] }, - &mut t, - ) - .unwrap(); + pallet_authority_discovery::GenesisConfig:: { keys: vec![], ..Default::default() } + .assimilate_storage(&mut t) + .unwrap(); // Create externalities. let mut externalities = TestExternalities::new(t); diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index 4bb8ba587ac8b..a9bd0c38cb67c 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -45,7 +45,7 @@ pub mod pallet { /// Find the author of a block. type FindAuthor: FindAuthor; /// An event handler for authored blocks. - type EventHandler: EventHandler; + type EventHandler: EventHandler>; } #[pallet::pallet] @@ -53,7 +53,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(_: T::BlockNumber) -> Weight { + fn on_initialize(_: BlockNumberFor) -> Weight { if let Some(author) = Self::author() { T::EventHandler::note_author(author); } @@ -61,7 +61,7 @@ pub mod pallet { Weight::zero() } - fn on_finalize(_: T::BlockNumber) { + fn on_finalize(_: BlockNumberFor) { // ensure we never go to trie with these values. >::kill(); } @@ -106,18 +106,15 @@ mod tests { generic::DigestItem, testing::Header, traits::{BlakeTwo256, Header as HeaderT, IdentityLookup}, + BuildStorage, }; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Authorship: pallet_authorship::{Pallet, Storage}, } ); @@ -128,14 +125,13 @@ mod tests { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -188,7 +184,7 @@ mod tests { } fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); t.into() } diff --git a/frame/babe/src/equivocation.rs b/frame/babe/src/equivocation.rs index be38beb6e1682..ed1df640583b2 100644 --- a/frame/babe/src/equivocation.rs +++ b/frame/babe/src/equivocation.rs @@ -34,6 +34,7 @@ //! definition. use frame_support::traits::{Get, KeyOwnerProofSystem}; +use frame_system::pallet_prelude::HeaderFor; use log::{error, info}; use sp_consensus_babe::{AuthorityId, EquivocationProof, Slot, KEY_TYPE}; @@ -106,7 +107,7 @@ impl Offence for EquivocationOffence { pub struct EquivocationReportSystem(sp_std::marker::PhantomData<(T, R, P, L)>); impl - OffenceReportSystem, (EquivocationProof, T::KeyOwnerProof)> + OffenceReportSystem, (EquivocationProof>, T::KeyOwnerProof)> for EquivocationReportSystem where T: Config + pallet_authorship::Config + frame_system::offchain::SendTransactionTypes>, @@ -122,7 +123,7 @@ where type Longevity = L; fn publish_evidence( - evidence: (EquivocationProof, T::KeyOwnerProof), + evidence: (EquivocationProof>, T::KeyOwnerProof), ) -> Result<(), ()> { use frame_system::offchain::SubmitTransaction; let (equivocation_proof, key_owner_proof) = evidence; @@ -140,7 +141,7 @@ where } fn check_evidence( - evidence: (EquivocationProof, T::KeyOwnerProof), + evidence: (EquivocationProof>, T::KeyOwnerProof), ) -> Result<(), TransactionValidityError> { let (equivocation_proof, key_owner_proof) = evidence; @@ -159,7 +160,7 @@ where fn process_evidence( reporter: Option, - evidence: (EquivocationProof, T::KeyOwnerProof), + evidence: (EquivocationProof>, T::KeyOwnerProof), ) -> Result<(), DispatchError> { let (equivocation_proof, key_owner_proof) = evidence; let reporter = reporter.or_else(|| >::author()); diff --git a/frame/babe/src/lib.rs b/frame/babe/src/lib.rs index 8001450b43583..eff56515a38d0 100644 --- a/frame/babe/src/lib.rs +++ b/frame/babe/src/lib.rs @@ -29,6 +29,7 @@ use frame_support::{ weights::Weight, BoundedVec, WeakBoundedVec, }; +use frame_system::pallet_prelude::{BlockNumberFor, HeaderFor}; use sp_consensus_babe::{ digests::{NextConfigDescriptor, NextEpochDescriptor, PreDigest}, AllowedSlots, BabeAuthorityWeight, BabeEpochConfiguration, ConsensusLog, Epoch, @@ -78,7 +79,7 @@ pub trait WeightInfo { pub trait EpochChangeTrigger { /// Trigger an epoch change, if any should take place. This should be called /// during every block, after initialization is done. - fn trigger(now: T::BlockNumber); + fn trigger(now: BlockNumberFor); } /// A type signifying to BABE that an external trigger @@ -86,7 +87,7 @@ pub trait EpochChangeTrigger { pub struct ExternalTrigger; impl EpochChangeTrigger for ExternalTrigger { - fn trigger(_: T::BlockNumber) {} // nothing - trigger is external. + fn trigger(_: BlockNumberFor) {} // nothing - trigger is external. } /// A type signifying to BABE that it should perform epoch changes @@ -94,7 +95,7 @@ impl EpochChangeTrigger for ExternalTrigger { pub struct SameAuthoritiesForever; impl EpochChangeTrigger for SameAuthoritiesForever { - fn trigger(now: T::BlockNumber) { + fn trigger(now: BlockNumberFor) { if >::should_epoch_change(now) { let authorities = >::authorities(); let next_authorities = authorities.clone(); @@ -162,7 +163,7 @@ pub mod pallet { /// (from an offchain context). type EquivocationReportSystem: OffenceReportSystem< Option, - (EquivocationProof, Self::KeyOwnerProof), + (EquivocationProof>, Self::KeyOwnerProof), >; } @@ -279,7 +280,7 @@ pub mod pallet { /// slots, which may be skipped, the block numbers may not line up with the slot numbers. #[pallet::storage] pub(super) type EpochStart = - StorageValue<_, (T::BlockNumber, T::BlockNumber), ValueQuery>; + StorageValue<_, (BlockNumberFor, BlockNumberFor), ValueQuery>; /// How late the current block is compared to its parent. /// @@ -288,7 +289,7 @@ pub mod pallet { /// execution context should always yield zero. #[pallet::storage] #[pallet::getter(fn lateness)] - pub(super) type Lateness = StorageValue<_, T::BlockNumber, ValueQuery>; + pub(super) type Lateness = StorageValue<_, BlockNumberFor, ValueQuery>; /// The configuration for the current epoch. Should never be `None` as it is initialized in /// genesis. @@ -314,15 +315,17 @@ pub mod pallet { pub(super) type SkippedEpochs = StorageValue<_, BoundedVec<(u64, SessionIndex), ConstU32<100>>, ValueQuery>; - #[derive(Default)] + #[derive(frame_support::DefaultNoBound)] #[pallet::genesis_config] - pub struct GenesisConfig { + pub struct GenesisConfig { pub authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, pub epoch_config: Option, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { SegmentIndex::::put(0); Pallet::::initialize_genesis_authorities(&self.authorities); @@ -407,7 +410,7 @@ pub mod pallet { ))] pub fn report_equivocation( origin: OriginFor, - equivocation_proof: Box>, + equivocation_proof: Box>>, key_owner_proof: T::KeyOwnerProof, ) -> DispatchResultWithPostInfo { let reporter = ensure_signed(origin)?; @@ -433,7 +436,7 @@ pub mod pallet { ))] pub fn report_equivocation_unsigned( origin: OriginFor, - equivocation_proof: Box>, + equivocation_proof: Box>>, key_owner_proof: T::KeyOwnerProof, ) -> DispatchResultWithPostInfo { ensure_none(origin)?; @@ -503,8 +506,8 @@ impl IsMember for Pallet { } } -impl pallet_session::ShouldEndSession for Pallet { - fn should_end_session(now: T::BlockNumber) -> bool { +impl pallet_session::ShouldEndSession> for Pallet { + fn should_end_session(now: BlockNumberFor) -> bool { // it might be (and it is in current implementation) that session module is calling // `should_end_session` from it's own `on_initialize` handler, in which case it's // possible that babe's own `on_initialize` has not run yet, so let's ensure that we @@ -524,7 +527,7 @@ impl Pallet { /// Determine whether an epoch change should take place at this block. /// Assumes that initialization has already taken place. - pub fn should_epoch_change(now: T::BlockNumber) -> bool { + pub fn should_epoch_change(now: BlockNumberFor) -> bool { // The epoch has technically ended during the passage of time // between this block and the last, but we have to "end" the epoch now, // since there is no earlier possible block we could have done it. @@ -554,11 +557,11 @@ impl Pallet { // // WEIGHT NOTE: This function is tied to the weight of `EstimateNextSessionRotation`. If you // update this function, you must also update the corresponding weight. - pub fn next_expected_epoch_change(now: T::BlockNumber) -> Option { + pub fn next_expected_epoch_change(now: BlockNumberFor) -> Option> { let next_slot = Self::current_epoch_start().saturating_add(T::EpochDuration::get()); next_slot.checked_sub(*CurrentSlot::::get()).map(|slots_remaining| { // This is a best effort guess. Drifts in the slot/block ratio will cause errors here. - let blocks_remaining: T::BlockNumber = slots_remaining.saturated_into(); + let blocks_remaining: BlockNumberFor = slots_remaining.saturated_into(); now.saturating_add(blocks_remaining) }) } @@ -776,7 +779,7 @@ impl Pallet { Self::deposit_consensus(ConsensusLog::NextEpochData(next)); } - fn initialize(now: T::BlockNumber) { + fn initialize(now: BlockNumberFor) { // since `initialize` can be called twice (e.g. if session module is present) // let's ensure that we only do the initialization once per block let initialized = Self::initialized().is_some(); @@ -811,7 +814,7 @@ impl Pallet { // how many slots were skipped between current and last block let lateness = current_slot.saturating_sub(CurrentSlot::::get() + 1); - let lateness = T::BlockNumber::from(*lateness as u32); + let lateness = BlockNumberFor::::from(*lateness as u32); Lateness::::put(lateness); CurrentSlot::::put(current_slot); @@ -877,7 +880,7 @@ impl Pallet { /// will push the transaction to the pool. Only useful in an offchain /// context. pub fn submit_unsigned_equivocation_report( - equivocation_proof: EquivocationProof, + equivocation_proof: EquivocationProof>, key_owner_proof: T::KeyOwnerProof, ) -> Option<()> { T::EquivocationReportSystem::publish_evidence((equivocation_proof, key_owner_proof)).ok() @@ -899,12 +902,14 @@ impl OnTimestampSet for Pallet { } } -impl frame_support::traits::EstimateNextSessionRotation for Pallet { - fn average_session_length() -> T::BlockNumber { +impl frame_support::traits::EstimateNextSessionRotation> + for Pallet +{ + fn average_session_length() -> BlockNumberFor { T::EpochDuration::get().saturated_into() } - fn estimate_current_session_progress(_now: T::BlockNumber) -> (Option, Weight) { + fn estimate_current_session_progress(_now: BlockNumberFor) -> (Option, Weight) { let elapsed = CurrentSlot::::get().saturating_sub(Self::current_epoch_start()) + 1; ( @@ -914,7 +919,9 @@ impl frame_support::traits::EstimateNextSessionRotation (Option, Weight) { + fn estimate_next_session_rotation( + now: BlockNumberFor, + ) -> (Option>, Weight) { ( Self::next_expected_epoch_change(now), // Read: Current Slot, Epoch Index, Genesis Slot @@ -923,8 +930,8 @@ impl frame_support::traits::EstimateNextSessionRotation frame_support::traits::Lateness for Pallet { - fn lateness(&self) -> T::BlockNumber { +impl frame_support::traits::Lateness> for Pallet { + fn lateness(&self) -> BlockNumberFor { Self::lateness() } } diff --git a/frame/babe/src/mock.rs b/frame/babe/src/mock.rs index ccc24050d53ba..b4a7e89ceb04e 100644 --- a/frame/babe/src/mock.rs +++ b/frame/babe/src/mock.rs @@ -22,7 +22,7 @@ use codec::Encode; use frame_election_provider_support::{onchain, SequentialPhragmen}; use frame_support::{ parameter_types, - traits::{ConstU128, ConstU32, ConstU64, GenesisBuild, KeyOwnerProofSystem, OnInitialize}, + traits::{ConstU128, ConstU32, ConstU64, KeyOwnerProofSystem, OnInitialize}, }; use pallet_session::historical as pallet_session_historical; use sp_consensus_babe::{AuthorityId, AuthorityPair, Randomness, Slot, VrfSignature}; @@ -36,20 +36,16 @@ use sp_runtime::{ impl_opaque_keys, testing::{Digest, DigestItem, Header, TestXt}, traits::{Header as _, IdentityLookup, OpaqueKeys}, - Perbill, + BuildStorage, Perbill, }; use sp_staking::{EraIndex, SessionIndex}; type DummyValidatorId = u64; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Authorship: pallet_authorship, @@ -69,15 +65,14 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Version = (); type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = DummyValidatorId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type PalletInfo = PalletInfo; @@ -345,7 +340,7 @@ pub fn new_test_ext_with_pairs( } pub fn new_test_ext_raw_authorities(authorities: Vec) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let balances: Vec<_> = (0..authorities.len()).map(|i| (i as u64, 10_000_000)).collect(); diff --git a/frame/babe/src/randomness.rs b/frame/babe/src/randomness.rs index b9b24786b7a74..d3d1bea2292da 100644 --- a/frame/babe/src/randomness.rs +++ b/frame/babe/src/randomness.rs @@ -22,6 +22,7 @@ use super::{ AuthorVrfRandomness, Config, EpochStart, NextRandomness, Randomness, RANDOMNESS_LENGTH, }; use frame_support::traits::Randomness as RandomnessT; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::traits::{Hash, One, Saturating}; /// Randomness usable by consensus protocols that **depend** upon finality and take action @@ -129,8 +130,8 @@ pub struct ParentBlockRandomness(sp_std::marker::PhantomData); Please use `ParentBlockRandomness` instead.")] pub struct CurrentBlockRandomness(sp_std::marker::PhantomData); -impl RandomnessT for RandomnessFromTwoEpochsAgo { - fn random(subject: &[u8]) -> (T::Hash, T::BlockNumber) { +impl RandomnessT> for RandomnessFromTwoEpochsAgo { + fn random(subject: &[u8]) -> (T::Hash, BlockNumberFor) { let mut subject = subject.to_vec(); subject.reserve(RANDOMNESS_LENGTH); subject.extend_from_slice(&Randomness::::get()[..]); @@ -139,8 +140,8 @@ impl RandomnessT for RandomnessFromTwoEpochs } } -impl RandomnessT for RandomnessFromOneEpochAgo { - fn random(subject: &[u8]) -> (T::Hash, T::BlockNumber) { +impl RandomnessT> for RandomnessFromOneEpochAgo { + fn random(subject: &[u8]) -> (T::Hash, BlockNumberFor) { let mut subject = subject.to_vec(); subject.reserve(RANDOMNESS_LENGTH); subject.extend_from_slice(&NextRandomness::::get()[..]); @@ -149,8 +150,8 @@ impl RandomnessT for RandomnessFromOneEpochA } } -impl RandomnessT, T::BlockNumber> for ParentBlockRandomness { - fn random(subject: &[u8]) -> (Option, T::BlockNumber) { +impl RandomnessT, BlockNumberFor> for ParentBlockRandomness { + fn random(subject: &[u8]) -> (Option, BlockNumberFor) { let random = AuthorVrfRandomness::::get().map(|random| { let mut subject = subject.to_vec(); subject.reserve(RANDOMNESS_LENGTH); @@ -164,8 +165,8 @@ impl RandomnessT, T::BlockNumber> for ParentBlockRand } #[allow(deprecated)] -impl RandomnessT, T::BlockNumber> for CurrentBlockRandomness { - fn random(subject: &[u8]) -> (Option, T::BlockNumber) { +impl RandomnessT, BlockNumberFor> for CurrentBlockRandomness { + fn random(subject: &[u8]) -> (Option, BlockNumberFor) { let (random, _) = ParentBlockRandomness::::random(subject); (random, >::block_number()) } diff --git a/frame/bags-list/src/mock.rs b/frame/bags-list/src/mock.rs index efbb2ed94c49f..ae50adabd508a 100644 --- a/frame/bags-list/src/mock.rs +++ b/frame/bags-list/src/mock.rs @@ -21,6 +21,7 @@ use super::*; use crate::{self as bags_list}; use frame_election_provider_support::VoteWeight; use frame_support::parameter_types; +use sp_runtime::BuildStorage; use std::collections::HashMap; pub type AccountId = u32; @@ -51,14 +52,13 @@ impl frame_system::Config for Runtime { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type DbWeight = (); @@ -86,15 +86,11 @@ impl bags_list::Config for Runtime { type Score = VoteWeight; } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub struct Runtime { - System: frame_system::{Pallet, Call, Storage, Event, Config}, + System: frame_system::{Pallet, Call, Storage, Event, Config}, BagsList: bags_list::{Pallet, Call, Storage, Event}, } ); @@ -127,7 +123,7 @@ impl ExtBuilder { pub(crate) fn build(self) -> sp_io::TestExternalities { sp_tracing::try_init_simple(); - let storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); let ids_with_weight: Vec<_> = if self.skip_genesis_ids { self.ids.iter().collect() diff --git a/frame/balances/README.md b/frame/balances/README.md index dd56ab3fadfb5..fa1ee622d48ce 100644 --- a/frame/balances/README.md +++ b/frame/balances/README.md @@ -94,7 +94,7 @@ The Staking module uses the `LockableCurrency` trait to lock a stash account's f use frame_support::traits::{WithdrawReasons, LockableCurrency}; use sp_runtime::traits::Bounded; pub trait Config: frame_system::Config { - type Currency: LockableCurrency; + type Currency: LockableCurrency>; } fn update_ledger( diff --git a/frame/balances/src/impl_currency.rs b/frame/balances/src/impl_currency.rs index baa153c119b20..2cbe776c51297 100644 --- a/frame/balances/src/impl_currency.rs +++ b/frame/balances/src/impl_currency.rs @@ -32,6 +32,7 @@ use frame_support::{ ReservableCurrency, SignedImbalance, TryDrop, WithdrawReasons, }, }; +use frame_system::pallet_prelude::BlockNumberFor; pub use imbalances::{NegativeImbalance, PositiveImbalance}; // wrapping these imbalances in a private module is necessary to ensure absolute privacy @@ -842,7 +843,7 @@ impl, I: 'static> LockableCurrency for Pallet where T::Balance: MaybeSerializeDeserialize + Debug, { - type Moment = T::BlockNumber; + type Moment = BlockNumberFor; type MaxLocks = T::MaxLocks; diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 33a336e7c94e5..7d7f66ba1f28f 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -120,7 +120,7 @@ //! use frame_support::traits::{WithdrawReasons, LockableCurrency}; //! use sp_runtime::traits::Bounded; //! pub trait Config: frame_system::Config { -//! type Currency: LockableCurrency; +//! type Currency: LockableCurrency>; //! } //! # struct StakingLedger { //! # stash: ::AccountId, @@ -166,8 +166,6 @@ mod types; pub mod weights; use codec::{Codec, MaxEncodedLen}; -#[cfg(feature = "std")] -use frame_support::traits::GenesisBuild; use frame_support::{ ensure, pallet_prelude::DispatchResult, @@ -465,7 +463,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { let total = self.balances.iter().fold(Zero::zero(), |acc: T::Balance, &(_, n)| acc + n); @@ -499,25 +497,8 @@ pub mod pallet { } } - #[cfg(feature = "std")] - impl, I: 'static> GenesisConfig { - /// Direct implementation of `GenesisBuild::build_storage`. - /// - /// Kept in order not to break dependency. - pub fn build_storage(&self) -> Result { - >::build_storage(self) - } - - /// Direct implementation of `GenesisBuild::assimilate_storage`. - /// - /// Kept in order not to break dependency. - pub fn assimilate_storage(&self, storage: &mut sp_runtime::Storage) -> Result<(), String> { - >::assimilate_storage(self, storage) - } - } - #[pallet::hooks] - impl, I: 'static> Hooks for Pallet { + impl, I: 'static> Hooks> for Pallet { #[cfg(not(feature = "insecure_zero_ed"))] fn integrity_test() { assert!( diff --git a/frame/balances/src/tests/currency_tests.rs b/frame/balances/src/tests/currency_tests.rs index 0c6ab0dbbaad5..c9ad19f79e36d 100644 --- a/frame/balances/src/tests/currency_tests.rs +++ b/frame/balances/src/tests/currency_tests.rs @@ -666,7 +666,7 @@ fn burn_must_work() { #[should_panic = "the balance of any account should always be at least the existential deposit."] fn cannot_set_genesis_value_below_ed() { EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = 11); - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = crate::GenesisConfig:: { balances: vec![(1, 10)] } .assimilate_storage(&mut t) .unwrap(); @@ -675,7 +675,7 @@ fn cannot_set_genesis_value_below_ed() { #[test] #[should_panic = "duplicate balances in genesis."] fn cannot_set_genesis_value_twice() { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = crate::GenesisConfig:: { balances: vec![(1, 10), (2, 20), (1, 15)] } .assimilate_storage(&mut t) .unwrap(); diff --git a/frame/balances/src/tests/mod.rs b/frame/balances/src/tests/mod.rs index 6deb9885b79e5..45f34110a6e9e 100644 --- a/frame/balances/src/tests/mod.rs +++ b/frame/balances/src/tests/mod.rs @@ -38,9 +38,8 @@ use scale_info::TypeInfo; use sp_core::{hexdisplay::HexDisplay, H256}; use sp_io; use sp_runtime::{ - testing::Header, traits::{BadOrigin, IdentityLookup, SignedExtension, Zero}, - ArithmeticError, DispatchError, DispatchResult, FixedPointNumber, TokenError, + ArithmeticError, BuildStorage, DispatchError, DispatchResult, FixedPointNumber, TokenError, }; use std::collections::BTreeSet; @@ -50,7 +49,6 @@ mod fungible_conformance_tests; mod fungible_tests; mod reentrancy_tests; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; #[derive( @@ -73,12 +71,9 @@ pub enum TestId { } frame_support::construct_runtime!( - pub struct Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub struct Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event}, } @@ -97,14 +92,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -176,7 +170,7 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { self.set_associated_consts(); - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: if self.monied { vec![ diff --git a/frame/beefy-mmr/src/lib.rs b/frame/beefy-mmr/src/lib.rs index ba416922e2563..ec1519ac41bd3 100644 --- a/frame/beefy-mmr/src/lib.rs +++ b/frame/beefy-mmr/src/lib.rs @@ -43,6 +43,7 @@ use sp_consensus_beefy::{ }; use frame_support::{crypto::ecdsa::ECDSAExt, traits::Get}; +use frame_system::pallet_prelude::BlockNumberFor; pub use pallet::*; @@ -139,7 +140,7 @@ pub mod pallet { impl LeafDataProvider for Pallet { type LeafData = MmrLeaf< - ::BlockNumber, + BlockNumberFor, ::Hash, MerkleRootOf, T::LeafExtra, diff --git a/frame/beefy-mmr/src/mock.rs b/frame/beefy-mmr/src/mock.rs index 31484aaa6be70..8594184ad71ab 100644 --- a/frame/beefy-mmr/src/mock.rs +++ b/frame/beefy-mmr/src/mock.rs @@ -21,7 +21,7 @@ use codec::Encode; use frame_support::{ construct_runtime, parameter_types, sp_io::TestExternalities, - traits::{ConstU16, ConstU32, ConstU64, GenesisBuild}, + traits::{ConstU16, ConstU32, ConstU64}, BasicExternalities, }; use sp_consensus_beefy::mmr::MmrLeafVersion; @@ -29,8 +29,8 @@ use sp_core::H256; use sp_runtime::{ app_crypto::ecdsa::Public, impl_opaque_keys, - testing::Header, traits::{BlakeTwo256, ConvertInto, IdentityLookup, Keccak256, OpaqueKeys}, + BuildStorage, }; use crate as pallet_beefy_mmr; @@ -45,16 +45,12 @@ impl_opaque_keys! { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, Mmr: pallet_mmr::{Pallet, Storage}, Beefy: pallet_beefy::{Pallet, Config, Storage}, @@ -68,14 +64,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -102,7 +97,7 @@ impl pallet_session::Config for Test { } pub type MmrLeaf = sp_consensus_beefy::mmr::MmrLeaf< - ::BlockNumber, + frame_system::pallet_prelude::BlockNumberFor, ::Hash, crate::MerkleRootOf, Vec, @@ -193,7 +188,7 @@ pub fn new_test_ext(ids: Vec) -> TestExternalities { } pub fn new_test_ext_raw_authorities(authorities: Vec<(u64, BeefyId)>) -> TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let session_keys: Vec<_> = authorities .iter() diff --git a/frame/beefy/src/equivocation.rs b/frame/beefy/src/equivocation.rs index 96446cf1b8277..acbd3a2532d78 100644 --- a/frame/beefy/src/equivocation.rs +++ b/frame/beefy/src/equivocation.rs @@ -39,6 +39,7 @@ use frame_support::{ log, traits::{Get, KeyOwnerProofSystem}, }; +use frame_system::pallet_prelude::BlockNumberFor; use log::{error, info}; use sp_consensus_beefy::{EquivocationProof, ValidatorSetId, KEY_TYPE}; use sp_runtime::{ @@ -126,7 +127,7 @@ pub struct EquivocationReportSystem(sp_std::marker::PhantomData<(T, /// Equivocation evidence convenience alias. pub type EquivocationEvidenceFor = ( EquivocationProof< - ::BlockNumber, + BlockNumberFor, ::BeefyId, <::BeefyId as RuntimeAppPublic>::Signature, >, @@ -140,7 +141,7 @@ where R: ReportOffence< T::AccountId, P::IdentificationTuple, - EquivocationOffence, + EquivocationOffence>, >, P: KeyOwnerProofSystem<(KeyTypeId, T::BeefyId), Proof = T::KeyOwnerProof>, P::IdentificationTuple: Clone, diff --git a/frame/beefy/src/lib.rs b/frame/beefy/src/lib.rs index d56d5b32f8f36..da469c5b9ca02 100644 --- a/frame/beefy/src/lib.rs +++ b/frame/beefy/src/lib.rs @@ -176,7 +176,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { Pallet::::initialize(&self.authorities) // we panic here as runtime maintainers can simply reconfigure genesis and restart diff --git a/frame/beefy/src/mock.rs b/frame/beefy/src/mock.rs index 270097e346c8f..40dcf4d7e70d3 100644 --- a/frame/beefy/src/mock.rs +++ b/frame/beefy/src/mock.rs @@ -21,9 +21,7 @@ use frame_election_provider_support::{onchain, SequentialPhragmen}; use frame_support::{ construct_runtime, parameter_types, sp_io::TestExternalities, - traits::{ - ConstU16, ConstU32, ConstU64, GenesisBuild, KeyOwnerProofSystem, OnFinalize, OnInitialize, - }, + traits::{ConstU16, ConstU32, ConstU64, KeyOwnerProofSystem, OnFinalize, OnInitialize}, BasicExternalities, }; use pallet_session::historical as pallet_session_historical; @@ -32,9 +30,9 @@ use sp_runtime::{ app_crypto::ecdsa::Public, curve::PiecewiseLinear, impl_opaque_keys, - testing::{Header, TestXt}, + testing::TestXt, traits::{BlakeTwo256, IdentityLookup, OpaqueKeys}, - Perbill, + BuildStorage, Perbill, }; use sp_staking::{EraIndex, SessionIndex}; @@ -51,14 +49,10 @@ impl_opaque_keys! { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Authorship: pallet_authorship, @@ -78,14 +72,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -260,7 +253,7 @@ pub fn new_test_ext(ids: Vec) -> TestExternalities { } pub fn new_test_ext_raw_authorities(authorities: Vec) -> TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let balances: Vec<_> = (0..authorities.len()).map(|i| (i as u64, 10_000_000)).collect(); diff --git a/frame/benchmarking/README.md b/frame/benchmarking/README.md index 76673c5f69b33..dc6a184435df6 100644 --- a/frame/benchmarking/README.md +++ b/frame/benchmarking/README.md @@ -175,7 +175,6 @@ Then you can run a benchmark like so: ```bash ./target/production/substrate benchmark pallet \ --chain dev \ # Configurable Chain Spec - --execution=wasm \ # Always test with Wasm --wasm-execution=compiled \ # Always used `wasm-time` --pallet pallet_balances \ # Select the pallet --extrinsic transfer \ # Select the extrinsic diff --git a/frame/benchmarking/pov/src/benchmarking.rs b/frame/benchmarking/pov/src/benchmarking.rs index 27191e37219fd..473947b171ac5 100644 --- a/frame/benchmarking/pov/src/benchmarking.rs +++ b/frame/benchmarking/pov/src/benchmarking.rs @@ -339,22 +339,17 @@ frame_benchmarking::benchmarks! { #[cfg(test)] mod mock { - use sp_runtime::testing::H256; + use sp_runtime::{testing::H256, BuildStorage}; type AccountId = u64; - type AccountIndex = u32; - type BlockNumber = u64; + type Nonce = u32; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Baseline: crate::{Pallet, Call, Storage, Event}, } ); @@ -365,14 +360,13 @@ mod mock { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; - type BlockNumber = BlockNumber; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); @@ -391,6 +385,6 @@ mod mock { } pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } } diff --git a/frame/benchmarking/pov/src/tests.rs b/frame/benchmarking/pov/src/tests.rs index b908925cccd8e..f09e37a5288a9 100644 --- a/frame/benchmarking/pov/src/tests.rs +++ b/frame/benchmarking/pov/src/tests.rs @@ -164,16 +164,12 @@ fn noop_is_free() { mod mock { use sp_runtime::testing::H256; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Baseline: crate::{Pallet, Call, Storage, Event}, } ); @@ -184,14 +180,13 @@ mod mock { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u32; - type BlockNumber = u64; + type Nonce = u32; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = u32; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); diff --git a/frame/benchmarking/src/baseline.rs b/frame/benchmarking/src/baseline.rs index 25336b6974d9f..94c066269d91b 100644 --- a/frame/benchmarking/src/baseline.rs +++ b/frame/benchmarking/src/baseline.rs @@ -111,22 +111,17 @@ benchmarks! { #[cfg(test)] pub mod mock { use super::*; - use sp_runtime::testing::H256; + use sp_runtime::{testing::H256, BuildStorage}; type AccountId = u64; - type AccountIndex = u32; - type BlockNumber = u64; + type Nonce = u32; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, } ); @@ -136,14 +131,13 @@ pub mod mock { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; - type BlockNumber = BlockNumber; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); @@ -162,7 +156,7 @@ pub mod mock { pub fn new_test_ext() -> sp_io::TestExternalities { use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.register_extension(KeystoreExt::new(MemoryKeystore::new())); diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index c3f51aeb53d5a..4b8339f65913d 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -22,7 +22,7 @@ use super::*; use frame_support::{parameter_types, traits::ConstU32}; use sp_runtime::{ - testing::{Header, H256}, + testing::H256, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; @@ -66,16 +66,12 @@ mod pallet_test { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, TestPallet: pallet_test::{Pallet, Call, Storage}, } ); @@ -86,14 +82,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); diff --git a/frame/benchmarking/src/tests_instance.rs b/frame/benchmarking/src/tests_instance.rs index 7e02cbf834d08..822efa70a2597 100644 --- a/frame/benchmarking/src/tests_instance.rs +++ b/frame/benchmarking/src/tests_instance.rs @@ -22,7 +22,7 @@ use super::*; use frame_support::traits::ConstU32; use sp_runtime::{ - testing::{Header, H256}, + testing::H256, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; @@ -76,16 +76,12 @@ mod pallet_test { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, TestPallet: pallet_test::{Pallet, Call, Storage, Event}, } ); @@ -96,13 +92,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type DbWeight = (); diff --git a/frame/bounties/src/benchmarking.rs b/frame/bounties/src/benchmarking.rs index 0675328c3d3c2..6fff337cba450 100644 --- a/frame/bounties/src/benchmarking.rs +++ b/frame/bounties/src/benchmarking.rs @@ -24,7 +24,7 @@ use super::*; use frame_benchmarking::v1::{ account, benchmarks_instance_pallet, whitelisted_caller, BenchmarkError, }; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use sp_runtime::traits::Bounded; use crate::Pallet as Bounties; @@ -77,7 +77,7 @@ fn create_bounty, I: 'static>( let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; Bounties::::approve_bounty(approve_origin.clone(), bounty_id)?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); Bounties::::propose_curator(approve_origin, bounty_id, curator_lookup.clone(), fee)?; Bounties::::accept_curator(RawOrigin::Signed(curator).into(), bounty_id)?; Ok((curator_lookup, bounty_id)) @@ -115,14 +115,14 @@ benchmarks_instance_pallet! { let bounty_id = BountyCount::::get() - 1; let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; Bounties::::approve_bounty(approve_origin.clone(), bounty_id)?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); }: _(approve_origin, bounty_id, curator_lookup, fee) // Worst case when curator is inactive and any sender unassigns the curator. unassign_curator { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); let bounty_id = BountyCount::::get() - 1; frame_system::Pallet::::set_block_number(T::BountyUpdatePeriod::get() + 2u32.into()); let caller = whitelisted_caller(); @@ -136,14 +136,14 @@ benchmarks_instance_pallet! { let bounty_id = BountyCount::::get() - 1; let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; Bounties::::approve_bounty(approve_origin.clone(), bounty_id)?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); Bounties::::propose_curator(approve_origin, bounty_id, curator_lookup, fee)?; }: _(RawOrigin::Signed(curator), bounty_id) award_bounty { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); let bounty_id = BountyCount::::get() - 1; let curator = T::Lookup::lookup(curator_lookup).map_err(<&str>::from)?; @@ -154,7 +154,7 @@ benchmarks_instance_pallet! { claim_bounty { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); let bounty_id = BountyCount::::get() - 1; let curator = T::Lookup::lookup(curator_lookup).map_err(<&str>::from)?; @@ -183,7 +183,7 @@ benchmarks_instance_pallet! { close_bounty_active { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); let bounty_id = BountyCount::::get() - 1; let approve_origin = T::ApproveOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; @@ -195,7 +195,7 @@ benchmarks_instance_pallet! { extend_bounty_expiry { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); let bounty_id = BountyCount::::get() - 1; let curator = T::Lookup::lookup(curator_lookup).map_err(<&str>::from)?; diff --git a/frame/bounties/src/lib.rs b/frame/bounties/src/lib.rs index 07ac23a9d8010..c64a35672c7f7 100644 --- a/frame/bounties/src/lib.rs +++ b/frame/bounties/src/lib.rs @@ -201,11 +201,11 @@ pub mod pallet { /// The delay period for which a bounty beneficiary need to wait before claim the payout. #[pallet::constant] - type BountyDepositPayoutDelay: Get; + type BountyDepositPayoutDelay: Get>; /// Bounty duration in blocks. #[pallet::constant] - type BountyUpdatePeriod: Get; + type BountyUpdatePeriod: Get>; /// The curator deposit is calculated as a percentage of the curator fee. /// @@ -305,7 +305,7 @@ pub mod pallet { _, Twox64Concat, BountyIndex, - Bounty, T::BlockNumber>, + Bounty, BlockNumberFor>, >; /// The description of each bounty. diff --git a/frame/bounties/src/tests.rs b/frame/bounties/src/tests.rs index 9fe34b16029cb..355483ddac94d 100644 --- a/frame/bounties/src/tests.rs +++ b/frame/bounties/src/tests.rs @@ -23,37 +23,30 @@ use super::*; use crate as pallet_bounties; use frame_support::{ - assert_noop, assert_ok, - pallet_prelude::GenesisBuild, - parameter_types, + assert_noop, assert_ok, parameter_types, traits::{ConstU32, ConstU64, OnInitialize}, PalletId, }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, BuildStorage, Perbill, Storage, }; use super::Event as BountiesEvent; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Bounties: pallet_bounties::{Pallet, Call, Storage, Event}, Bounties1: pallet_bounties::::{Pallet, Call, Storage, Event}, - Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event}, - Treasury1: pallet_treasury::::{Pallet, Call, Storage, Config, Event}, + Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event}, + Treasury1: pallet_treasury::::{Pallet, Call, Storage, Config, Event}, } ); @@ -69,14 +62,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u128; // u64 is not enough to hold bytes used to generate bounty account type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -412,7 +404,7 @@ fn treasury_account_doesnt_get_deleted() { // This is useful for chain that will just update runtime. #[test] fn inexistent_account_works() { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(0, 100), (1, 99), (2, 1)] } .assimilate_storage(&mut t) .unwrap(); @@ -1073,7 +1065,7 @@ fn test_migration_v4() { #[test] fn genesis_funding_works() { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let initial_funding = 100; pallet_balances::GenesisConfig:: { // Total issuance will be 200 with treasury account initialized with 100. @@ -1081,7 +1073,9 @@ fn genesis_funding_works() { } .assimilate_storage(&mut t) .unwrap(); - GenesisBuild::::assimilate_storage(&pallet_treasury::GenesisConfig, &mut t).unwrap(); + pallet_treasury::GenesisConfig::::default() + .assimilate_storage(&mut t) + .unwrap(); let mut t: sp_io::TestExternalities = t.into(); t.execute_with(|| { diff --git a/frame/child-bounties/src/benchmarking.rs b/frame/child-bounties/src/benchmarking.rs index e49d9c836125d..1973564d0dc1d 100644 --- a/frame/child-bounties/src/benchmarking.rs +++ b/frame/child-bounties/src/benchmarking.rs @@ -22,7 +22,7 @@ use super::*; use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller, BenchmarkError}; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use crate::Pallet as ChildBounties; use pallet_bounties::Pallet as Bounties; @@ -114,7 +114,7 @@ fn activate_bounty( let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; Bounties::::approve_bounty(approve_origin, child_bounty_setup.bounty_id)?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); Bounties::::propose_curator( RawOrigin::Root.into(), child_bounty_setup.bounty_id, @@ -229,7 +229,7 @@ benchmarks! { unassign_curator { setup_pot_account::(); let bounty_setup = activate_child_bounty::(0, T::MaximumReasonLength::get())?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); frame_system::Pallet::::set_block_number(T::BountyUpdatePeriod::get() + 1u32.into()); let caller = whitelisted_caller(); }: _(RawOrigin::Signed(caller), bounty_setup.bounty_id, @@ -303,7 +303,7 @@ benchmarks! { close_child_bounty_active { setup_pot_account::(); let bounty_setup = activate_child_bounty::(0, T::MaximumReasonLength::get())?; - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(BlockNumberFor::::zero()); }: close_child_bounty(RawOrigin::Root, bounty_setup.bounty_id, bounty_setup.child_bounty_id) verify { assert_last_event::(Event::Canceled { diff --git a/frame/child-bounties/src/lib.rs b/frame/child-bounties/src/lib.rs index 14c1907af2c46..1eedeaa5a1ae3 100644 --- a/frame/child-bounties/src/lib.rs +++ b/frame/child-bounties/src/lib.rs @@ -200,7 +200,7 @@ pub mod pallet { BountyIndex, Twox64Concat, BountyIndex, - ChildBounty, T::BlockNumber>, + ChildBounty, BlockNumberFor>, >; /// The description of each child-bounty. @@ -816,7 +816,7 @@ impl Pallet { fn ensure_bounty_active( bounty_id: BountyIndex, - ) -> Result<(T::AccountId, T::BlockNumber), DispatchError> { + ) -> Result<(T::AccountId, BlockNumberFor), DispatchError> { let parent_bounty = pallet_bounties::Pallet::::bounties(bounty_id) .ok_or(BountiesError::::InvalidIndex)?; if let BountyStatus::Active { curator, update_due } = parent_bounty.get_status() { diff --git a/frame/child-bounties/src/tests.rs b/frame/child-bounties/src/tests.rs index a8f0e16ea2136..24a6410f29f78 100644 --- a/frame/child-bounties/src/tests.rs +++ b/frame/child-bounties/src/tests.rs @@ -23,9 +23,7 @@ use super::*; use crate as pallet_child_bounties; use frame_support::{ - assert_noop, assert_ok, - pallet_prelude::GenesisBuild, - parameter_types, + assert_noop, assert_ok, parameter_types, traits::{ConstU32, ConstU64, OnInitialize}, weights::Weight, PalletId, @@ -33,27 +31,22 @@ use frame_support::{ use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, - Perbill, Permill, TokenError, + BuildStorage, Perbill, Permill, TokenError, }; use super::Event as ChildBountiesEvent; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type BountiesError = pallet_bounties::Error; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Bounties: pallet_bounties::{Pallet, Call, Storage, Event}, - Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event}, + Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event}, ChildBounties: pallet_child_bounties::{Pallet, Call, Storage, Event}, } ); @@ -72,14 +65,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u128; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -162,14 +154,16 @@ impl pallet_child_bounties::Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { // Total issuance will be 200 with treasury account initialized at ED. balances: vec![(0, 100), (1, 98), (2, 1)], } .assimilate_storage(&mut t) .unwrap(); - GenesisBuild::::assimilate_storage(&pallet_treasury::GenesisConfig, &mut t).unwrap(); + pallet_treasury::GenesisConfig::::default() + .assimilate_storage(&mut t) + .unwrap(); t.into() } diff --git a/frame/collective/src/benchmarking.rs b/frame/collective/src/benchmarking.rs index 8a4495ef4095b..503d725105309 100644 --- a/frame/collective/src/benchmarking.rs +++ b/frame/collective/src/benchmarking.rs @@ -24,7 +24,9 @@ use sp_runtime::traits::Bounded; use sp_std::mem::size_of; use frame_benchmarking::v1::{account, benchmarks_instance_pallet, whitelisted_caller}; -use frame_system::{Call as SystemCall, Pallet as System, RawOrigin as SystemOrigin}; +use frame_system::{ + pallet_prelude::BlockNumberFor, Call as SystemCall, Pallet as System, RawOrigin as SystemOrigin, +}; const SEED: u32 = 0; @@ -516,7 +518,7 @@ benchmarks_instance_pallet! { false, )?; - System::::set_block_number(T::BlockNumber::max_value()); + System::::set_block_number(BlockNumberFor::::max_value()); assert_eq!(Collective::::proposals().len(), p as usize); // Prime nay will close it as disapproved @@ -588,7 +590,7 @@ benchmarks_instance_pallet! { } // caller is prime, prime already votes aye by creating the proposal - System::::set_block_number(T::BlockNumber::max_value()); + System::::set_block_number(BlockNumberFor::::max_value()); assert_eq!(Collective::::proposals().len(), p as usize); // Prime aye will close it as approved @@ -637,7 +639,7 @@ benchmarks_instance_pallet! { last_hash = T::Hashing::hash_of(&proposal); } - System::::set_block_number(T::BlockNumber::max_value()); + System::::set_block_number(BlockNumberFor::::max_value()); assert_eq!(Collective::::proposals().len(), p as usize); }: _(SystemOrigin::Root, last_hash) diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index fc4ab0c4f1bbd..f99a37e6218ac 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -201,7 +201,7 @@ pub mod pallet { + IsType<::RuntimeEvent>; /// The time-out for council motions. - type MotionDuration: Get; + type MotionDuration: Get>; /// Maximum number of proposals allowed to be active in parallel. type MaxProposals: Get; @@ -230,12 +230,13 @@ pub mod pallet { #[pallet::genesis_config] #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig, I: 'static = ()> { + #[serde(skip)] pub phantom: PhantomData, pub members: Vec, } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { use sp_std::collections::btree_set::BTreeSet; let members_set: BTreeSet<_> = self.members.iter().collect(); @@ -273,7 +274,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn voting)] pub type Voting, I: 'static = ()> = - StorageMap<_, Identity, T::Hash, Votes, OptionQuery>; + StorageMap<_, Identity, T::Hash, Votes>, OptionQuery>; /// Proposals so far. #[pallet::storage] diff --git a/frame/collective/src/tests.rs b/frame/collective/src/tests.rs index 8d4e0a4a82cd7..faf7b74399bde 100644 --- a/frame/collective/src/tests.rs +++ b/frame/collective/src/tests.rs @@ -21,7 +21,7 @@ use frame_support::{ assert_noop, assert_ok, dispatch::Pays, parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild, StorageVersion}, + traits::{ConstU32, ConstU64, StorageVersion}, Hashable, }; use frame_system::{EnsureRoot, EventRecord, Phase}; @@ -36,10 +36,7 @@ pub type Block = sp_runtime::generic::Block; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub enum Test { System: frame_system::{Pallet, Call, Event}, Collective: pallet_collective::::{Pallet, Call, Event, Origin, Config}, @@ -99,14 +96,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/contracts/src/exec.rs b/frame/contracts/src/exec.rs index 2c38f68b3ce08..cf37b132ddc27 100644 --- a/frame/contracts/src/exec.rs +++ b/frame/contracts/src/exec.rs @@ -34,7 +34,7 @@ use frame_support::{ weights::Weight, Blake2_128Concat, BoundedVec, StorageHasher, }; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use pallet_contracts_primitives::ExecReturnValue; use smallvec::{Array, SmallVec}; use sp_core::{ @@ -48,7 +48,6 @@ use sp_std::{marker::PhantomData, mem, prelude::*, vec::Vec}; pub type AccountIdOf = ::AccountId; pub type MomentOf = <::Time as Time>::Moment; pub type SeedOf = ::Hash; -pub type BlockNumberOf = ::BlockNumber; pub type ExecResult = Result; /// A type that represents a topic of an event. At the moment a hash is used. @@ -244,7 +243,7 @@ pub trait Ext: sealing::Sealed { fn minimum_balance(&self) -> BalanceOf; /// Returns a random number for the current block with the given subject. - fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberOf); + fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberFor); /// Deposit an event with the given topics. /// @@ -252,7 +251,7 @@ pub trait Ext: sealing::Sealed { fn deposit_event(&mut self, topics: Vec>, data: Vec); /// Returns the current block number. - fn block_number(&self) -> BlockNumberOf; + fn block_number(&self) -> BlockNumberFor; /// Returns the maximum allowed size of a storage item. fn max_value_size(&self) -> u32; @@ -400,7 +399,7 @@ pub struct Stack<'a, T: Config, E> { /// The timestamp at the point of call stack instantiation. timestamp: MomentOf, /// The block number at the time of call stack instantiation. - block_number: T::BlockNumber, + block_number: BlockNumberFor, /// The nonce is cached here when accessed. It is written back when the call stack /// finishes executing. Please refer to [`Nonce`] to a description of /// the nonce itself. @@ -1341,7 +1340,7 @@ where self.top_frame().value_transferred } - fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberOf) { + fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberFor) { T::Randomness::random(subject) } @@ -1360,7 +1359,7 @@ where ); } - fn block_number(&self) -> T::BlockNumber { + fn block_number(&self) -> BlockNumberFor { self.block_number } diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index d36a0f93f339b..03db5c5ba0aab 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -209,7 +209,7 @@ pub mod pallet { /// be instantiated from existing codes that use this deprecated functionality. It will /// be removed eventually. Hence for new `pallet-contracts` deployments it is okay /// to supply a dummy implementation for this type (because it is never used). - type Randomness: Randomness; + type Randomness: Randomness>; /// The currency in which fees are paid and contract balances are held. type Currency: ReservableCurrency // TODO: Move to fungible traits @@ -341,7 +341,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_idle(_block: T::BlockNumber, mut remaining_weight: Weight) -> Weight { + fn on_idle(_block: BlockNumberFor, mut remaining_weight: Weight) -> Weight { use migration::MigrateResult::*; loop { diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index d5c7cc6f5a04a..b25487469ba0e 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -51,22 +51,18 @@ use sp_core::ByteArray; use sp_io::hashing::blake2_256; use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; use sp_runtime::{ - testing::{Header, H256}, + testing::H256, traits::{BlakeTwo256, Convert, Hash, IdentityLookup}, - AccountId32, TokenError, + AccountId32, BuildStorage, TokenError, }; use std::ops::Deref; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, Randomness: pallet_insecure_randomness_collective_flip::{Pallet, Storage}, @@ -315,14 +311,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = AccountId32; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -490,7 +485,7 @@ impl ExtBuilder { let env = Env::new().default_filter_or("runtime=debug"); let _ = Builder::from_env(env).is_test(true).try_init(); self.set_associated_consts(); - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![] } .assimilate_storage(&mut t) .unwrap(); diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index 076905567a98f..b975a39a81052 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -409,7 +409,7 @@ impl Executable for WasmBlob { mod tests { use super::*; use crate::{ - exec::{AccountIdOf, BlockNumberOf, ErrorOrigin, ExecError, Executable, Ext, Key, SeedOf}, + exec::{AccountIdOf, ErrorOrigin, ExecError, Executable, Ext, Key, SeedOf}, gas::GasMeter, storage::WriteOutcome, tests::{RuntimeCall, Test, ALICE, BOB}, @@ -419,6 +419,7 @@ mod tests { use frame_support::{ assert_err, assert_ok, dispatch::DispatchResultWithPostInfo, weights::Weight, }; + use frame_system::pallet_prelude::BlockNumberFor; use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags}; use pretty_assertions::assert_eq; use sp_core::H256; @@ -624,7 +625,7 @@ mod tests { fn minimum_balance(&self) -> u64 { 666 } - fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberOf) { + fn random(&self, subject: &[u8]) -> (SeedOf, BlockNumberFor) { (H256::from_slice(subject), 42) } fn deposit_event(&mut self, topics: Vec, data: Vec) { diff --git a/frame/contracts/src/wasm/runtime.rs b/frame/contracts/src/wasm/runtime.rs index b2e2ed0e5401e..4c5b98d8786d0 100644 --- a/frame/contracts/src/wasm/runtime.rs +++ b/frame/contracts/src/wasm/runtime.rs @@ -2091,7 +2091,7 @@ pub mod env { /// `out_ptr`. This call overwrites it with the size of the value. If the available /// space at `out_ptr` is less than the size of the value a trap is triggered. /// - /// The data is encoded as (T::Hash, T::BlockNumber). + /// The data is encoded as (T::Hash, frame_system::pallet_prelude::BlockNumberFor::). /// /// # Changes from v0 /// diff --git a/frame/conviction-voting/src/lib.rs b/frame/conviction-voting/src/lib.rs index 3ad81486ed26d..9c2993fc5cae1 100644 --- a/frame/conviction-voting/src/lib.rs +++ b/frame/conviction-voting/src/lib.rs @@ -35,6 +35,7 @@ use frame_support::{ ReservableCurrency, WithdrawReasons, }, }; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::{ traits::{AtLeast32BitUnsigned, Saturating, StaticLookup, Zero}, ArithmeticError, Perbill, @@ -68,16 +69,13 @@ type BalanceOf = type VotingOf = Voting< BalanceOf, ::AccountId, - ::BlockNumber, + BlockNumberFor, PollIndexOf, >::MaxVotes, >; #[allow(dead_code)] -type DelegatingOf = Delegating< - BalanceOf, - ::AccountId, - ::BlockNumber, ->; +type DelegatingOf = + Delegating, ::AccountId, BlockNumberFor>; pub type TallyOf = Tally, >::MaxTurnout>; pub type VotesOf = BalanceOf; type PollIndexOf = <>::Polls as Polling>>::Index; @@ -103,14 +101,14 @@ pub mod pallet { type WeightInfo: WeightInfo; /// Currency type with which voting happens. type Currency: ReservableCurrency - + LockableCurrency + + LockableCurrency> + fungible::Inspect; /// The implementation of the logic which conducts polls. type Polls: Polling< TallyOf, Votes = BalanceOf, - Moment = Self::BlockNumber, + Moment = BlockNumberFor, >; /// The maximum amount of tokens which may be used for voting. May just be @@ -130,7 +128,7 @@ pub mod pallet { /// It should be no shorter than enactment period to ensure that in the case of an approval, /// those successful voters are locked into the consequences that their votes entail. #[pallet::constant] - type VoteLockingPeriod: Get; + type VoteLockingPeriod: Get>; } /// All voting for a particular voter in a particular voting class. We store the balance for the diff --git a/frame/conviction-voting/src/tests.rs b/frame/conviction-voting/src/tests.rs index 1ea3a56adacb7..656112deebfbb 100644 --- a/frame/conviction-voting/src/tests.rs +++ b/frame/conviction-voting/src/tests.rs @@ -25,23 +25,19 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use super::*; use crate as pallet_conviction_voting; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Voting: pallet_conviction_voting::{Pallet, Call, Storage, Event}, } @@ -61,14 +57,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -196,7 +191,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)], } diff --git a/frame/core-fellowship/src/benchmarking.rs b/frame/core-fellowship/src/benchmarking.rs index c49f50d4cc115..ea0b5c6d4495f 100644 --- a/frame/core-fellowship/src/benchmarking.rs +++ b/frame/core-fellowship/src/benchmarking.rs @@ -23,7 +23,7 @@ use super::*; use crate::Pallet as CoreFellowship; use frame_benchmarking::v2::*; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use sp_arithmetic::traits::Bounded; const SEED: u32 = 0; @@ -75,7 +75,7 @@ mod benchmarks { let member = make_member::(0)?; // Set it to the max value to ensure that any possible auto-demotion period has passed. - frame_system::Pallet::::set_block_number(T::BlockNumber::max_value()); + frame_system::Pallet::::set_block_number(BlockNumberFor::::max_value()); ensure_evidence::(&member)?; assert!(Member::::contains_key(&member)); @@ -92,7 +92,7 @@ mod benchmarks { let member = make_member::(2)?; // Set it to the max value to ensure that any possible auto-demotion period has passed. - frame_system::Pallet::::set_block_number(T::BlockNumber::max_value()); + frame_system::Pallet::::set_block_number(BlockNumberFor::::max_value()); ensure_evidence::(&member)?; assert!(Member::::contains_key(&member)); assert_eq!(T::Members::rank_of(&member), Some(2)); diff --git a/frame/core-fellowship/src/lib.rs b/frame/core-fellowship/src/lib.rs index ba02627ec11b9..8f3d9633fcf22 100644 --- a/frame/core-fellowship/src/lib.rs +++ b/frame/core-fellowship/src/lib.rs @@ -193,9 +193,8 @@ pub mod pallet { type EvidenceSize: Get; } - pub type ParamsOf = - ParamsType<>::Balance, ::BlockNumber, RANK_COUNT>; - pub type MemberStatusOf = MemberStatus<::BlockNumber>; + pub type ParamsOf = ParamsType<>::Balance, BlockNumberFor, RANK_COUNT>; + pub type MemberStatusOf = MemberStatus>; pub type RankOf = <>::Members as RankedMembers>::Rank; /// The overall status of the system. diff --git a/frame/core-fellowship/src/tests.rs b/frame/core-fellowship/src/tests.rs index 87c0de112ac33..c95699e66e41b 100644 --- a/frame/core-fellowship/src/tests.rs +++ b/frame/core-fellowship/src/tests.rs @@ -28,25 +28,20 @@ use frame_support::{ use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup, TryMorphInto}, - DispatchError, DispatchResult, + BuildStorage, DispatchError, DispatchResult, }; use sp_std::cell::RefCell; use super::*; use crate as pallet_core_fellowship; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, CoreFellowship: pallet_core_fellowship::{Pallet, Call, Storage, Event}, } ); @@ -61,14 +56,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -149,7 +143,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| { let params = ParamsType { diff --git a/frame/democracy/src/benchmarking.rs b/frame/democracy/src/benchmarking.rs index 9a67ba698a662..e4a21a4e1d9b8 100644 --- a/frame/democracy/src/benchmarking.rs +++ b/frame/democracy/src/benchmarking.rs @@ -24,7 +24,7 @@ use frame_support::{ assert_noop, assert_ok, traits::{Currency, EnsureOrigin, Get, OnInitialize, UnfilteredDispatchable}, }; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use sp_core::H256; use sp_runtime::{traits::Bounded, BoundedVec}; @@ -258,7 +258,7 @@ benchmarks! { .collect::>() .try_into() .unwrap(); - Blacklist::::insert(proposal.hash(), (T::BlockNumber::zero(), addresses)); + Blacklist::::insert(proposal.hash(), (BlockNumberFor::::zero(), addresses)); }: _(origin, proposal) verify { // External proposal created @@ -332,7 +332,7 @@ benchmarks! { vetoers.try_push(account::("vetoer", i, SEED)).unwrap(); } vetoers.sort(); - Blacklist::::insert(proposal_hash, (T::BlockNumber::zero(), vetoers)); + Blacklist::::insert(proposal_hash, (BlockNumberFor::::zero(), vetoers)); let origin = T::VetoOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; ensure!(NextExternal::::get().is_some(), "no external proposal"); @@ -816,7 +816,7 @@ benchmarks! { // create not ongoing referendum. ReferendumInfoOf::::insert( 0, - ReferendumInfo::Finished { end: T::BlockNumber::zero(), approved: true }, + ReferendumInfo::Finished { end: BlockNumberFor::::zero(), approved: true }, ); let owner = MetadataOwner::Referendum(0); let caller = funded_account::("caller", 0); @@ -833,7 +833,7 @@ benchmarks! { // create not ongoing referendum. ReferendumInfoOf::::insert( 0, - ReferendumInfo::Finished { end: T::BlockNumber::zero(), approved: true }, + ReferendumInfo::Finished { end: BlockNumberFor::::zero(), approved: true }, ); let owner = MetadataOwner::Referendum(0); let hash = note_preimage::(); diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index 7ce3bb5611915..e538d31c6ad03 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -165,7 +165,7 @@ use frame_support::{ }, weights::Weight, }; -use frame_system::pallet_prelude::OriginFor; +use frame_system::pallet_prelude::{BlockNumberFor, OriginFor}; use sp_runtime::{ traits::{Bounded as ArithBounded, One, Saturating, StaticLookup, Zero}, ArithmeticError, DispatchError, DispatchResult, @@ -226,14 +226,14 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// The Scheduler. - type Scheduler: ScheduleNamed, Self::PalletsOrigin>; + type Scheduler: ScheduleNamed, CallOf, Self::PalletsOrigin>; /// The Preimage provider. type Preimages: QueryPreimage + StorePreimage; /// Currency type for this pallet. type Currency: ReservableCurrency - + LockableCurrency; + + LockableCurrency>; /// The period between a proposal being approved and enacted. /// @@ -241,22 +241,22 @@ pub mod pallet { /// voting stakers have an opportunity to remove themselves from the system in the case /// where they are on the losing side of a vote. #[pallet::constant] - type EnactmentPeriod: Get; + type EnactmentPeriod: Get>; /// How often (in blocks) new public referenda are launched. #[pallet::constant] - type LaunchPeriod: Get; + type LaunchPeriod: Get>; /// How often (in blocks) to check for new votes. #[pallet::constant] - type VotingPeriod: Get; + type VotingPeriod: Get>; /// The minimum period of vote locking. /// /// It should be no shorter than enactment period to ensure that in the case of an approval, /// those successful voters are locked into the consequences that their votes entail. #[pallet::constant] - type VoteLockingPeriod: Get; + type VoteLockingPeriod: Get>; /// The minimum amount to be used as a deposit for a public referendum proposal. #[pallet::constant] @@ -270,11 +270,11 @@ pub mod pallet { /// Minimum voting period allowed for a fast-track referendum. #[pallet::constant] - type FastTrackVotingPeriod: Get; + type FastTrackVotingPeriod: Get>; /// Period in blocks where an external proposal may not be re-submitted after being vetoed. #[pallet::constant] - type CooloffPeriod: Get; + type CooloffPeriod: Get>; /// The maximum number of votes for an account. /// @@ -387,7 +387,7 @@ pub mod pallet { _, Twox64Concat, ReferendumIndex, - ReferendumInfo, BalanceOf>, + ReferendumInfo, BoundedCallOf, BalanceOf>, >; /// All votes for a particular voter. We store the balance for the number of votes that we @@ -399,7 +399,7 @@ pub mod pallet { _, Twox64Concat, T::AccountId, - Voting, T::AccountId, T::BlockNumber, T::MaxVotes>, + Voting, T::AccountId, BlockNumberFor, T::MaxVotes>, ValueQuery, >; @@ -422,7 +422,7 @@ pub mod pallet { _, Identity, H256, - (T::BlockNumber, BoundedVec), + (BlockNumberFor, BoundedVec), >; /// Record of all proposals that have been subject to emergency cancellation. @@ -441,11 +441,12 @@ pub mod pallet { #[pallet::genesis_config] #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { - _phantom: sp_std::marker::PhantomData, + #[serde(skip)] + _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { PublicPropCount::::put(0 as PropIndex); ReferendumCount::::put(0 as ReferendumIndex); @@ -475,7 +476,7 @@ pub mod pallet { /// An account has cancelled a previous delegation operation. Undelegated { account: T::AccountId }, /// An external proposal has been vetoed. - Vetoed { who: T::AccountId, proposal_hash: H256, until: T::BlockNumber }, + Vetoed { who: T::AccountId, proposal_hash: H256, until: BlockNumberFor }, /// A proposal_hash has been blacklisted permanently. Blacklisted { proposal_hash: H256 }, /// An account has voted in a referendum @@ -565,7 +566,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { /// Weight: see `begin_block` - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { Self::begin_block(n) } } @@ -775,8 +776,8 @@ pub mod pallet { pub fn fast_track( origin: OriginFor, proposal_hash: H256, - voting_period: T::BlockNumber, - delay: T::BlockNumber, + voting_period: BlockNumberFor, + delay: BlockNumberFor, ) -> DispatchResult { // Rather complicated bit of code to ensure that either: // - `voting_period` is at least `FastTrackVotingPeriod` and `origin` is @@ -794,7 +795,7 @@ pub mod pallet { ensure!(T::InstantAllowed::get(), Error::::InstantNotAllowed); } - ensure!(voting_period > T::BlockNumber::zero(), Error::::VotingPeriodLow); + ensure!(voting_period > Zero::zero(), Error::::VotingPeriodLow); let (ext_proposal, threshold) = >::get().ok_or(Error::::ProposalMissing)?; ensure!( @@ -1047,7 +1048,8 @@ pub mod pallet { T::BlacklistOrigin::ensure_origin(origin)?; // Insert the proposal into the blacklist. - let permanent = (T::BlockNumber::max_value(), BoundedVec::::default()); + let permanent = + (BlockNumberFor::::max_value(), BoundedVec::::default()); Blacklist::::insert(&proposal_hash, permanent); // Remove the queued proposal, if it's there. @@ -1200,17 +1202,19 @@ impl Pallet { /// Get all referenda ready for tally at block `n`. pub fn maturing_referenda_at( - n: T::BlockNumber, - ) -> Vec<(ReferendumIndex, ReferendumStatus, BalanceOf>)> { + n: BlockNumberFor, + ) -> Vec<(ReferendumIndex, ReferendumStatus, BoundedCallOf, BalanceOf>)> + { let next = Self::lowest_unbaked(); let last = Self::referendum_count(); Self::maturing_referenda_at_inner(n, next..last) } fn maturing_referenda_at_inner( - n: T::BlockNumber, + n: BlockNumberFor, range: core::ops::Range, - ) -> Vec<(ReferendumIndex, ReferendumStatus, BalanceOf>)> { + ) -> Vec<(ReferendumIndex, ReferendumStatus, BoundedCallOf, BalanceOf>)> + { range .into_iter() .map(|i| (i, Self::referendum_info(i))) @@ -1228,7 +1232,7 @@ impl Pallet { pub fn internal_start_referendum( proposal: BoundedCallOf, threshold: VoteThreshold, - delay: T::BlockNumber, + delay: BlockNumberFor, ) -> ReferendumIndex { >::inject_referendum( >::block_number().saturating_add(T::VotingPeriod::get()), @@ -1249,8 +1253,9 @@ impl Pallet { /// Ok if the given referendum is active, Err otherwise fn ensure_ongoing( - r: ReferendumInfo, BalanceOf>, - ) -> Result, BalanceOf>, DispatchError> { + r: ReferendumInfo, BoundedCallOf, BalanceOf>, + ) -> Result, BoundedCallOf, BalanceOf>, DispatchError> + { match r { ReferendumInfo::Ongoing(s) => Ok(s), _ => Err(Error::::ReferendumInvalid.into()), @@ -1259,7 +1264,8 @@ impl Pallet { fn referendum_status( ref_index: ReferendumIndex, - ) -> Result, BalanceOf>, DispatchError> { + ) -> Result, BoundedCallOf, BalanceOf>, DispatchError> + { let info = ReferendumInfoOf::::get(ref_index).ok_or(Error::::ReferendumInvalid)?; Self::ensure_ongoing(info) } @@ -1514,10 +1520,10 @@ impl Pallet { /// Start a referendum fn inject_referendum( - end: T::BlockNumber, + end: BlockNumberFor, proposal: BoundedCallOf, threshold: VoteThreshold, - delay: T::BlockNumber, + delay: BlockNumberFor, ) -> ReferendumIndex { let ref_index = Self::referendum_count(); ReferendumCount::::put(ref_index + 1); @@ -1530,7 +1536,7 @@ impl Pallet { } /// Table the next waiting proposal for a vote. - fn launch_next(now: T::BlockNumber) -> DispatchResult { + fn launch_next(now: BlockNumberFor) -> DispatchResult { if LastTabledWasExternal::::take() { Self::launch_public(now).or_else(|_| Self::launch_external(now)) } else { @@ -1540,7 +1546,7 @@ impl Pallet { } /// Table the waiting external proposal for a vote, if there is one. - fn launch_external(now: T::BlockNumber) -> DispatchResult { + fn launch_external(now: BlockNumberFor) -> DispatchResult { if let Some((proposal, threshold)) = >::take() { LastTabledWasExternal::::put(true); Self::deposit_event(Event::::ExternalTabled); @@ -1558,7 +1564,7 @@ impl Pallet { } /// Table the waiting public proposal with the highest backing for a vote. - fn launch_public(now: T::BlockNumber) -> DispatchResult { + fn launch_public(now: BlockNumberFor) -> DispatchResult { let mut public_props = Self::public_props(); if let Some((winner_index, _)) = public_props.iter().enumerate().max_by_key( // defensive only: All current public proposals have an amount locked @@ -1591,9 +1597,9 @@ impl Pallet { } fn bake_referendum( - now: T::BlockNumber, + now: BlockNumberFor, index: ReferendumIndex, - status: ReferendumStatus, BalanceOf>, + status: ReferendumStatus, BoundedCallOf, BalanceOf>, ) -> bool { let total_issuance = T::Currency::total_issuance(); let approved = status.threshold.approved(status.tally, total_issuance); @@ -1628,7 +1634,7 @@ impl Pallet { /// ## Complexity: /// If a referendum is launched or maturing, this will take full block weight if queue is not /// empty. Otherwise, `O(R)` where `R` is the number of unbaked referenda. - fn begin_block(now: T::BlockNumber) -> Weight { + fn begin_block(now: BlockNumberFor) -> Weight { let max_block_weight = T::BlockWeights::get().max_block; let mut weight = Weight::zero(); diff --git a/frame/democracy/src/migrations/v1.rs b/frame/democracy/src/migrations/v1.rs index f3d29511ff659..27a500a615cff 100644 --- a/frame/democracy/src/migrations/v1.rs +++ b/frame/democracy/src/migrations/v1.rs @@ -19,6 +19,7 @@ use crate::*; use frame_support::{pallet_prelude::*, storage_alias, traits::OnRuntimeUpgrade, BoundedVec}; +use frame_system::pallet_prelude::BlockNumberFor; use sp_core::H256; /// The log target. @@ -45,11 +46,7 @@ mod v0 { Pallet, frame_support::Twox64Concat, ReferendumIndex, - ReferendumInfo< - ::BlockNumber, - ::Hash, - BalanceOf, - >, + ReferendumInfo, ::Hash, BalanceOf>, >; } @@ -87,7 +84,7 @@ pub mod v1 { } ReferendumInfoOf::::translate( - |index, old: ReferendumInfo>| { + |index, old: ReferendumInfo, T::Hash, BalanceOf>| { weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); log::info!(target: TARGET, "migrating referendum #{:?}", &index); Some(match old { diff --git a/frame/democracy/src/tests.rs b/frame/democracy/src/tests.rs index dd726004648ef..e5cfcc5b40029 100644 --- a/frame/democracy/src/tests.rs +++ b/frame/democracy/src/tests.rs @@ -22,8 +22,8 @@ use crate as pallet_democracy; use frame_support::{ assert_noop, assert_ok, ord_parameter_types, parameter_types, traits::{ - ConstU32, ConstU64, Contains, EqualPrivilegeOnly, GenesisBuild, OnInitialize, - SortedMembers, StorePreimage, + ConstU32, ConstU64, Contains, EqualPrivilegeOnly, OnInitialize, SortedMembers, + StorePreimage, }, weights::Weight, }; @@ -31,9 +31,8 @@ use frame_system::{EnsureRoot, EnsureSigned, EnsureSignedBy}; use pallet_balances::{BalanceLock, Error as BalancesError}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, Hash, IdentityLookup}, - Perbill, + BuildStorage, Perbill, }; mod cancellation; mod decoders; @@ -51,16 +50,12 @@ const NAY: Vote = Vote { aye: false, conviction: Conviction::None }; const BIG_AYE: Vote = Vote { aye: true, conviction: Conviction::Locked1x }; const BIG_NAY: Vote = Vote { aye: false, conviction: Conviction::Locked1x }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Preimage: pallet_preimage, Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event}, @@ -88,14 +83,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -203,7 +197,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)], } diff --git a/frame/election-provider-multi-phase/src/benchmarking.rs b/frame/election-provider-multi-phase/src/benchmarking.rs index a5946c6a1d3c1..1284d0b873ea6 100644 --- a/frame/election-provider-multi-phase/src/benchmarking.rs +++ b/frame/election-provider-multi-phase/src/benchmarking.rs @@ -313,7 +313,7 @@ frame_benchmarking::benchmarks! { assert!(>::get().is_none()); assert!(>::get().is_none()); assert!(>::get().is_none()); - assert_eq!(>::get(), >::Off); + assert_eq!(>::get(), >>::Off); } submit { diff --git a/frame/election-provider-multi-phase/src/lib.rs b/frame/election-provider-multi-phase/src/lib.rs index 1960c458b983e..03ab5574a2180 100644 --- a/frame/election-provider-multi-phase/src/lib.rs +++ b/frame/election-provider-multi-phase/src/lib.rs @@ -241,7 +241,7 @@ use frame_support::{ weights::Weight, DefaultNoBound, EqNoBound, PartialEqNoBound, }; -use frame_system::{ensure_none, offchain::SendTransactionTypes}; +use frame_system::{ensure_none, offchain::SendTransactionTypes, pallet_prelude::BlockNumberFor}; use scale_info::TypeInfo; use sp_arithmetic::{ traits::{CheckedAdd, Zero}, @@ -585,10 +585,10 @@ pub mod pallet { /// Duration of the unsigned phase. #[pallet::constant] - type UnsignedPhase: Get; + type UnsignedPhase: Get>; /// Duration of the signed phase. #[pallet::constant] - type SignedPhase: Get; + type SignedPhase: Get>; /// The minimum amount of improvement to the solution score that defines a solution as /// "better" in the Signed phase. @@ -605,7 +605,7 @@ pub mod pallet { /// For example, if it is 5, that means that at least 5 blocks will elapse between attempts /// to submit the worker's solution. #[pallet::constant] - type OffchainRepeat: Get; + type OffchainRepeat: Get>; /// The priority of the unsigned transaction submitted in the unsigned-phase #[pallet::constant] @@ -685,13 +685,13 @@ pub mod pallet { /// Something that will provide the election data. type DataProvider: ElectionDataProvider< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, >; /// Configuration for the fallback. type Fallback: InstantElectionProvider< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, DataProvider = Self::DataProvider, MaxWinners = Self::MaxWinners, >; @@ -702,7 +702,7 @@ pub mod pallet { /// BoundedExecution<_>` if the test-net is not expected to have thousands of nominators. type GovernanceFallback: InstantElectionProvider< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, DataProvider = Self::DataProvider, MaxWinners = Self::MaxWinners, >; @@ -747,7 +747,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(now: T::BlockNumber) -> Weight { + fn on_initialize(now: BlockNumberFor) -> Weight { let next_election = T::DataProvider::next_election_prediction(now).max(now); let signed_deadline = T::SignedPhase::get() + T::UnsignedPhase::get(); @@ -824,7 +824,7 @@ pub mod pallet { } } - fn offchain_worker(now: T::BlockNumber) { + fn offchain_worker(now: BlockNumberFor) { use sp_runtime::offchain::storage_lock::{BlockAndTime, StorageLock}; // Create a lock with the maximum deadline of number of blocks in the unsigned phase. @@ -886,7 +886,7 @@ pub mod pallet { } #[cfg(feature = "try-runtime")] - fn try_state(_n: T::BlockNumber) -> Result<(), TryRuntimeError> { + fn try_state(_n: BlockNumberFor) -> Result<(), TryRuntimeError> { Self::do_try_state() } } @@ -1155,7 +1155,11 @@ pub mod pallet { /// An account has been slashed for submitting an invalid signed submission. Slashed { account: ::AccountId, value: BalanceOf }, /// There was a phase transition in a given round. - PhaseTransitioned { from: Phase, to: Phase, round: u32 }, + PhaseTransitioned { + from: Phase>, + to: Phase>, + round: u32, + }, } /// Error of the pallet that can be returned in response to dispatches. @@ -1257,7 +1261,7 @@ pub mod pallet { /// Current phase. #[pallet::storage] #[pallet::getter(fn current_phase)] - pub type CurrentPhase = StorageValue<_, Phase, ValueQuery>; + pub type CurrentPhase = StorageValue<_, Phase>, ValueQuery>; /// Current best solution, signed or unsigned, queued to be returned upon `elect`. /// @@ -1349,7 +1353,7 @@ pub mod pallet { impl Pallet { /// Internal logic of the offchain worker, to be executed only when the offchain lock is /// acquired with success. - fn do_synchronized_offchain_worker(now: T::BlockNumber) { + fn do_synchronized_offchain_worker(now: BlockNumberFor) { let current_phase = Self::current_phase(); log!(trace, "lock for offchain worker acquired. Phase = {:?}", current_phase); match current_phase { @@ -1375,7 +1379,7 @@ impl Pallet { } /// Phase transition helper. - pub(crate) fn phase_transition(to: Phase) { + pub(crate) fn phase_transition(to: Phase>) { log!(info, "Starting phase {:?}, round {}.", to, Self::round()); Self::deposit_event(Event::PhaseTransitioned { from: >::get(), @@ -1672,7 +1676,7 @@ impl Pallet { impl ElectionProviderBase for Pallet { type AccountId = T::AccountId; - type BlockNumber = T::BlockNumber; + type BlockNumber = BlockNumberFor; type Error = ElectionError; type MaxWinners = T::MaxWinners; type DataProvider = T::DataProvider; diff --git a/frame/election-provider-multi-phase/src/mock.rs b/frame/election-provider-multi-phase/src/mock.rs index cf797aea845f4..911e93d35860e 100644 --- a/frame/election-provider-multi-phase/src/mock.rs +++ b/frame/election-provider-multi-phase/src/mock.rs @@ -45,7 +45,7 @@ use sp_npos_elections::{ use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, - PerU16, + BuildStorage, PerU16, }; use std::sync::Arc; @@ -54,12 +54,9 @@ pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { - System: frame_system::{Pallet, Call, Event, Config}, + System: frame_system::{Pallet, Call, Event, Config}, Balances: pallet_balances::{Pallet, Call, Event, Config}, MultiPhase: multi_phase::{Pallet, Call, Event}, } @@ -211,14 +208,13 @@ impl frame_system::Config for Runtime { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type DbWeight = (); @@ -322,8 +318,8 @@ impl onchain::Config for OnChainSeqPhragmen { pub struct MockFallback; impl ElectionProviderBase for MockFallback { + type BlockNumber = BlockNumber; type AccountId = AccountId; - type BlockNumber = u64; type Error = &'static str; type DataProvider = StakingMock; type MaxWinners = MaxWinners; @@ -436,8 +432,8 @@ pub struct ExtBuilder {} pub struct StakingMock; impl ElectionDataProvider for StakingMock { + type BlockNumber = BlockNumber; type AccountId = AccountId; - type BlockNumber = u64; type MaxVotesPerVoter = MaxNominations; fn electable_targets(maybe_max_len: Option) -> data_provider::Result> { @@ -574,7 +570,7 @@ impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { sp_tracing::try_init_simple(); let mut storage = - frame_system::GenesisConfig::default().build_storage::().unwrap(); + frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = pallet_balances::GenesisConfig:: { balances: vec![ diff --git a/frame/election-provider-multi-phase/src/signed.rs b/frame/election-provider-multi-phase/src/signed.rs index bde985518d53e..226404e4afc1a 100644 --- a/frame/election-provider-multi-phase/src/signed.rs +++ b/frame/election-provider-multi-phase/src/signed.rs @@ -27,6 +27,7 @@ use frame_election_provider_support::NposSolution; use frame_support::traits::{ defensive_prelude::*, Currency, Get, OnUnbalanced, ReservableCurrency, }; +use frame_system::pallet_prelude::BlockNumberFor; use sp_arithmetic::traits::SaturatedConversion; use sp_core::bounded::BoundedVec; use sp_npos_elections::ElectionScore; @@ -100,10 +101,8 @@ pub type SignedSubmissionOf = SignedSubmission< /// Always sorted vector of a score, submitted at the given block number, which can be found at the /// given index (`u32`) of the `SignedSubmissionsMap`. -pub type SubmissionIndicesOf = BoundedVec< - (ElectionScore, ::BlockNumber, u32), - ::SignedMaxSubmissions, ->; +pub type SubmissionIndicesOf = + BoundedVec<(ElectionScore, BlockNumberFor, u32), ::SignedMaxSubmissions>; /// Outcome of [`SignedSubmissions::insert`]. pub enum InsertResult { @@ -216,7 +215,7 @@ impl SignedSubmissions { fn swap_out_submission( &mut self, remove_pos: usize, - insert: Option<(ElectionScore, T::BlockNumber, u32)>, + insert: Option<(ElectionScore, BlockNumberFor, u32)>, ) -> Option> { if remove_pos >= self.indices.len() { return None diff --git a/frame/election-provider-multi-phase/src/unsigned.rs b/frame/election-provider-multi-phase/src/unsigned.rs index 9c09cb48c7c05..e21e6c5e6d229 100644 --- a/frame/election-provider-multi-phase/src/unsigned.rs +++ b/frame/election-provider-multi-phase/src/unsigned.rs @@ -29,7 +29,7 @@ use frame_support::{ traits::{DefensiveResult, Get}, BoundedVec, }; -use frame_system::offchain::SubmitTransaction; +use frame_system::{offchain::SubmitTransaction, pallet_prelude::BlockNumberFor}; use scale_info::TypeInfo; use sp_npos_elections::{ assignment_ratio_to_staked_normalized, assignment_staked_to_ratio_normalized, ElectionResult, @@ -298,12 +298,12 @@ impl Pallet { /// /// Returns `Ok(())` if offchain worker limit is respected, `Err(reason)` otherwise. If `Ok()` /// is returned, `now` is written in storage and will be used in further calls as the baseline. - pub fn ensure_offchain_repeat_frequency(now: T::BlockNumber) -> Result<(), MinerError> { + pub fn ensure_offchain_repeat_frequency(now: BlockNumberFor) -> Result<(), MinerError> { let threshold = T::OffchainRepeat::get(); let last_block = StorageValueRef::persistent(OFFCHAIN_LAST_BLOCK); let mutate_stat = last_block.mutate::<_, &'static str, _>( - |maybe_head: Result, _>| { + |maybe_head: Result>, _>| { match maybe_head { Ok(Some(head)) if now < head => Err("fork."), Ok(Some(head)) if now >= head && now <= head + threshold => diff --git a/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs b/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs index 8c641d6137c53..b04f863668ec3 100644 --- a/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs +++ b/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs @@ -18,18 +18,14 @@ #![allow(dead_code)] use _feps::ExtendedBalance; -use frame_support::{ - parameter_types, traits, - traits::{GenesisBuild, Hooks}, - weights::constants, -}; +use frame_support::{parameter_types, traits, traits::Hooks, weights::constants}; use frame_system::EnsureRoot; use sp_core::{ConstU32, Get, H256}; use sp_npos_elections::{ElectionScore, VoteWeight}; use sp_runtime::{ testing, traits::{IdentityLookup, Zero}, - transaction_validity, PerU16, Perbill, + transaction_validity, BuildStorage, PerU16, Perbill, }; use sp_staking::{ offence::{DisableStrategy, OffenceDetails, OnOffenceHandler}, @@ -50,14 +46,11 @@ pub const INIT_TIMESTAMP: u64 = 30_000; pub const BLOCK_TIME: u64 = 1000; type Block = frame_system::mocking::MockBlock; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; + type Extrinsic = testing::TestXt; frame_support::construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub enum Runtime { System: frame_system, ElectionProviderMultiPhase: pallet_election_provider_multi_phase, @@ -71,7 +64,7 @@ frame_support::construct_runtime!( ); pub(crate) type AccountId = u128; -pub(crate) type AccountIndex = u32; +pub(crate) type Nonce = u32; pub(crate) type BlockNumber = u64; pub(crate) type Balance = u64; pub(crate) type VoterIndex = u32; @@ -84,14 +77,13 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; - type BlockNumber = BlockNumber; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); @@ -490,7 +482,7 @@ impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { sp_tracing::try_init_simple(); let mut storage = - frame_system::GenesisConfig::default().build_storage::().unwrap(); + frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = pallet_balances::GenesisConfig:: { balances: self.balances_builder.balances } diff --git a/frame/election-provider-support/src/onchain.rs b/frame/election-provider-support/src/onchain.rs index a312562d4944c..bfdc21a8fe2d6 100644 --- a/frame/election-provider-support/src/onchain.rs +++ b/frame/election-provider-support/src/onchain.rs @@ -73,7 +73,7 @@ pub trait Config { /// Something that provides the data for election. type DataProvider: ElectionDataProvider< AccountId = ::AccountId, - BlockNumber = ::BlockNumber, + BlockNumber = frame_system::pallet_prelude::BlockNumberFor, >; /// Weight information for extrinsics in this pallet. @@ -151,7 +151,7 @@ fn elect_with_input_bounds( impl ElectionProviderBase for OnChainExecution { type AccountId = ::AccountId; - type BlockNumber = ::BlockNumber; + type BlockNumber = frame_system::pallet_prelude::BlockNumberFor; type Error = Error; type MaxWinners = T::MaxWinners; type DataProvider = T::DataProvider; @@ -190,6 +190,7 @@ mod tests { use sp_npos_elections::Support; use sp_runtime::Perbill; type AccountId = u64; + type Nonce = u64; type BlockNumber = u64; pub type Header = sp_runtime::generic::Header; @@ -197,10 +198,7 @@ mod tests { pub type Block = sp_runtime::generic::Block; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system::{Pallet, Call, Event}, } @@ -210,14 +208,13 @@ mod tests { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = AccountId; - type BlockNumber = BlockNumber; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = (); type BlockHashCount = (); type DbWeight = (); diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 7a4fb61970215..b23ddda4e8d1c 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -204,7 +204,7 @@ pub mod pallet { type PalletId: Get; /// The currency that people are electing with. - type Currency: LockableCurrency + type Currency: LockableCurrency> + ReservableCurrency; /// What to do when the members change. @@ -250,7 +250,7 @@ pub mod pallet { /// round will happen. If set to zero, no elections are ever triggered and the module will /// be in passive mode. #[pallet::constant] - type TermDuration: Get; + type TermDuration: Get>; /// The maximum number of candidates in a phragmen election. /// @@ -286,7 +286,7 @@ pub mod pallet { /// What to do at the end of each block. /// /// Checks if an election needs to happen or not. - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { let term_duration = T::TermDuration::get(); if !term_duration.is_zero() && (n % term_duration).is_zero() { Self::do_phragmen() @@ -331,7 +331,7 @@ pub mod pallet { } #[cfg(feature = "try-runtime")] - fn try_state(_n: T::BlockNumber) -> Result<(), TryRuntimeError> { + fn try_state(_n: BlockNumberFor) -> Result<(), TryRuntimeError> { Self::do_try_state() } } @@ -721,7 +721,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { assert!( self.members.len() as u32 <= T::DesiredMembers::get(), @@ -1323,14 +1323,13 @@ mod tests { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -1447,10 +1446,7 @@ mod tests { sp_runtime::generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub enum Test { System: frame_system::{Pallet, Call, Event}, Balances: pallet_balances::{Pallet, Call, Event, Config}, diff --git a/frame/examples/basic/src/lib.rs b/frame/examples/basic/src/lib.rs index af159c0f4bc98..426e9b7ec648c 100644 --- a/frame/examples/basic/src/lib.rs +++ b/frame/examples/basic/src/lib.rs @@ -388,21 +388,21 @@ pub mod pallet { // dispatched. // // This function must return the weight consumed by `on_initialize` and `on_finalize`. - fn on_initialize(_n: T::BlockNumber) -> Weight { + fn on_initialize(_n: BlockNumberFor) -> Weight { // Anything that needs to be done at the start of the block. // We don't do anything here. Weight::zero() } // `on_finalize` is executed at the end of block after all extrinsic are dispatched. - fn on_finalize(_n: T::BlockNumber) { + fn on_finalize(_n: BlockNumberFor) { // Perform necessary data/state clean up here. } // A runtime code run after every block and have access to extended set of APIs. // // For instance you can generate extrinsics for the upcoming produced block. - fn offchain_worker(_n: T::BlockNumber) { + fn offchain_worker(_n: BlockNumberFor) { // We don't do anything here. // but we could dispatch extrinsic (transaction/unsigned/inherent) using // sp_io::submit_extrinsic. @@ -627,7 +627,7 @@ pub mod pallet { // The build of genesis for the pallet. #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { >::put(&self.dummy); for (a, b) in &self.bar { diff --git a/frame/examples/basic/src/tests.rs b/frame/examples/basic/src/tests.rs index 621d93b97cd01..addf219dc3c39 100644 --- a/frame/examples/basic/src/tests.rs +++ b/frame/examples/basic/src/tests.rs @@ -27,24 +27,19 @@ use sp_core::H256; // The testing primitives are very useful for avoiding having to work with signatures // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; // Reexport crate as its pallet name for construct_runtime. use crate as pallet_example_basic; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; // For testing the pallet, we construct a mock runtime. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Example: pallet_example_basic::{Pallet, Call, Storage, Config, Event}, } @@ -56,14 +51,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/examples/default-config/src/lib.rs b/frame/examples/default-config/src/lib.rs index 5112f3d72d59e..63a6a941b829f 100644 --- a/frame/examples/default-config/src/lib.rs +++ b/frame/examples/default-config/src/lib.rs @@ -107,17 +107,14 @@ pub mod pallet { pub mod tests { use super::*; use frame_support::derive_impl; + use sp_runtime::traits::ConstU64; use super::pallet as pallet_default_config_example; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, DefaultPallet: pallet_default_config_example, @@ -129,6 +126,8 @@ pub mod tests { // these items are defined by frame-system as `no_default`, so we must specify them here. // Note that these are types that actually rely on the outer runtime, and can't sensibly // have an _independent_ default. + type Block = Block; + type BlockHashCount = ConstU64<10>; type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; @@ -138,9 +137,11 @@ pub mod tests { // all of this is coming from `frame_system::config_preludes::TestDefaultConfig`. - // type Index = u32; + // type Nonce = u32; // type BlockNumber = u32; - // type Header = sp_runtime::generic::Header; + // type Header = + // sp_runtime::generic::Header, + // Self::Hashing>; // type Hash = sp_core::hash::H256; // type Hashing = sp_runtime::traits::BlakeTwo256; // type AccountId = u64; diff --git a/frame/examples/dev-mode/src/tests.rs b/frame/examples/dev-mode/src/tests.rs index 8a1ca6628b91c..ba98f5174ce20 100644 --- a/frame/examples/dev-mode/src/tests.rs +++ b/frame/examples/dev-mode/src/tests.rs @@ -21,24 +21,19 @@ use crate::*; use frame_support::{assert_ok, traits::ConstU64}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; // Reexport crate as its pallet name for construct_runtime. use crate as pallet_dev_mode; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; // For testing the pallet, we construct a mock runtime. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Example: pallet_dev_mode::{Pallet, Call, Storage, Event}, } @@ -50,14 +45,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/examples/kitchensink/src/lib.rs b/frame/examples/kitchensink/src/lib.rs index c60e126181a95..0fbffc971da62 100644 --- a/frame/examples/kitchensink/src/lib.rs +++ b/frame/examples/kitchensink/src/lib.rs @@ -183,7 +183,7 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig { pub foo: u32, - pub bar: T::BlockNumber, + pub bar: BlockNumberFor, } impl Default for GenesisConfig { @@ -194,7 +194,7 @@ pub mod pallet { /// Allows you to define how `genesis_configuration is built. #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { Foo::::put(self.foo); } @@ -249,22 +249,22 @@ pub mod pallet { /// All the possible hooks that a pallet can have. See [`frame_support::traits::Hooks`] for more /// info. #[pallet::hooks] - impl Hooks for Pallet { + impl Hooks> for Pallet { fn integrity_test() {} - fn offchain_worker(_n: T::BlockNumber) { + fn offchain_worker(_n: BlockNumberFor) { unimplemented!() } - fn on_initialize(_n: T::BlockNumber) -> Weight { + fn on_initialize(_n: BlockNumberFor) -> Weight { unimplemented!() } - fn on_finalize(_n: T::BlockNumber) { + fn on_finalize(_n: BlockNumberFor) { unimplemented!() } - fn on_idle(_n: T::BlockNumber, _remaining_weight: Weight) -> Weight { + fn on_idle(_n: BlockNumberFor, _remaining_weight: Weight) -> Weight { unimplemented!() } @@ -283,7 +283,7 @@ pub mod pallet { } #[cfg(feature = "try-runtime")] - fn try_state(_n: T::BlockNumber) -> Result<(), TryRuntimeError> { + fn try_state(_n: BlockNumberFor) -> Result<(), TryRuntimeError> { unimplemented!() } } diff --git a/frame/examples/kitchensink/src/tests.rs b/frame/examples/kitchensink/src/tests.rs index 9f1cdda9ea228..b2af7c8983f56 100644 --- a/frame/examples/kitchensink/src/tests.rs +++ b/frame/examples/kitchensink/src/tests.rs @@ -23,17 +23,13 @@ use sp_runtime::BuildStorage; // Reexport crate as its pallet name for construct_runtime. use crate as pallet_example_kitchensink; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; // For testing the pallet, we construct a mock runtime. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Kitchensink: pallet_example_kitchensink::{Pallet, Call, Storage, Config, Event}, } @@ -44,6 +40,8 @@ frame_support::construct_runtime!( #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU64<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; diff --git a/frame/examples/offchain-worker/src/lib.rs b/frame/examples/offchain-worker/src/lib.rs index 6ce8524174200..6c1fa6ea8ec42 100644 --- a/frame/examples/offchain-worker/src/lib.rs +++ b/frame/examples/offchain-worker/src/lib.rs @@ -53,6 +53,7 @@ use frame_system::{ AppCrypto, CreateSignedTransaction, SendSignedTransaction, SendUnsignedTransaction, SignedPayload, Signer, SigningTypes, SubmitTransaction, }, + pallet_prelude::BlockNumberFor, }; use lite_json::json::JsonValue; use sp_core::crypto::KeyTypeId; @@ -136,14 +137,14 @@ pub mod pallet { /// every `GRACE_PERIOD` blocks. We use Local Storage to coordinate /// sending between distinct runs of this offchain worker. #[pallet::constant] - type GracePeriod: Get; + type GracePeriod: Get>; /// Number of blocks of cooldown after unsigned transaction is included. /// /// This ensures that we only accept unsigned transactions once, every `UnsignedInterval` /// blocks. #[pallet::constant] - type UnsignedInterval: Get; + type UnsignedInterval: Get>; /// A configuration for base priority of unsigned transactions. /// @@ -171,7 +172,7 @@ pub mod pallet { /// be cases where some blocks are skipped, or for some the worker runs twice (re-orgs), /// so the code should be able to handle that. /// You can use `Local Storage` API to coordinate runs of the worker. - fn offchain_worker(block_number: T::BlockNumber) { + fn offchain_worker(block_number: BlockNumberFor) { // Note that having logs compiled to WASM may cause the size of the blob to increase // significantly. You can use `RuntimeDebug` custom derive to hide details of the types // in WASM. The `sp-api` crate also provides a feature `disable-logging` to disable @@ -258,7 +259,7 @@ pub mod pallet { #[pallet::weight({0})] pub fn submit_price_unsigned( origin: OriginFor, - _block_number: T::BlockNumber, + _block_number: BlockNumberFor, price: u32, ) -> DispatchResultWithPostInfo { // This ensures that the function can only be called via unsigned transaction. @@ -275,7 +276,7 @@ pub mod pallet { #[pallet::weight({0})] pub fn submit_price_unsigned_with_signed_payload( origin: OriginFor, - price_payload: PricePayload, + price_payload: PricePayload>, _signature: T::Signature, ) -> DispatchResultWithPostInfo { // This ensures that the function can only be called via unsigned transaction. @@ -341,7 +342,7 @@ pub mod pallet { /// This storage entry defines when new transaction is going to be accepted. #[pallet::storage] #[pallet::getter(fn next_unsigned_at)] - pub(super) type NextUnsignedAt = StorageValue<_, T::BlockNumber, ValueQuery>; + pub(super) type NextUnsignedAt = StorageValue<_, BlockNumberFor, ValueQuery>; } /// Payload used by this example crate to hold price @@ -353,7 +354,7 @@ pub struct PricePayload { public: Public, } -impl SignedPayload for PricePayload { +impl SignedPayload for PricePayload> { fn public(&self) -> T::Public { self.public.clone() } @@ -374,7 +375,7 @@ impl Pallet { /// and local storage usage. /// /// Returns a type of transaction that should be produced in current run. - fn choose_transaction_type(block_number: T::BlockNumber) -> TransactionType { + fn choose_transaction_type(block_number: BlockNumberFor) -> TransactionType { /// A friendlier name for the error that is going to be returned in case we are in the grace /// period. const RECENTLY_SENT: () = (); @@ -389,16 +390,17 @@ impl Pallet { // low-level method of local storage API, which means that only one worker // will be able to "acquire a lock" and send a transaction if multiple workers // happen to be executed concurrently. - let res = val.mutate(|last_send: Result, StorageRetrievalError>| { - match last_send { - // If we already have a value in storage and the block number is recent enough - // we avoid sending another transaction at this time. - Ok(Some(block)) if block_number < block + T::GracePeriod::get() => - Err(RECENTLY_SENT), - // In every other case we attempt to acquire the lock and send a transaction. - _ => Ok(block_number), - } - }); + let res = + val.mutate(|last_send: Result>, StorageRetrievalError>| { + match last_send { + // If we already have a value in storage and the block number is recent enough + // we avoid sending another transaction at this time. + Ok(Some(block)) if block_number < block + T::GracePeriod::get() => + Err(RECENTLY_SENT), + // In every other case we attempt to acquire the lock and send a transaction. + _ => Ok(block_number), + } + }); // The result of `mutate` call will give us a nested `Result` type. // The first one matches the return of the closure passed to `mutate`, i.e. @@ -419,9 +421,9 @@ impl Pallet { let transaction_type = block_number % 4u32.into(); if transaction_type == Zero::zero() { TransactionType::Signed - } else if transaction_type == T::BlockNumber::from(1u32) { + } else if transaction_type == BlockNumberFor::::from(1u32) { TransactionType::UnsignedForAny - } else if transaction_type == T::BlockNumber::from(2u32) { + } else if transaction_type == BlockNumberFor::::from(2u32) { TransactionType::UnsignedForAll } else { TransactionType::Raw @@ -472,7 +474,9 @@ impl Pallet { } /// A helper function to fetch the price and send a raw unsigned transaction. - fn fetch_price_and_send_raw_unsigned(block_number: T::BlockNumber) -> Result<(), &'static str> { + fn fetch_price_and_send_raw_unsigned( + block_number: BlockNumberFor, + ) -> Result<(), &'static str> { // Make sure we don't fetch the price if unsigned transaction is going to be rejected // anyway. let next_unsigned_at = >::get(); @@ -505,7 +509,7 @@ impl Pallet { /// A helper function to fetch the price, sign payload and send an unsigned transaction fn fetch_price_and_send_unsigned_for_any_account( - block_number: T::BlockNumber, + block_number: BlockNumberFor, ) -> Result<(), &'static str> { // Make sure we don't fetch the price if unsigned transaction is going to be rejected // anyway. @@ -535,7 +539,7 @@ impl Pallet { /// A helper function to fetch the price, sign payload and send an unsigned transaction fn fetch_price_and_send_unsigned_for_all_accounts( - block_number: T::BlockNumber, + block_number: BlockNumberFor, ) -> Result<(), &'static str> { // Make sure we don't fetch the price if unsigned transaction is going to be rejected // anyway. @@ -669,7 +673,7 @@ impl Pallet { } fn validate_transaction_parameters( - block_number: &T::BlockNumber, + block_number: &BlockNumberFor, new_price: &u32, ) -> TransactionValidity { // Now let's check if the transaction has any chance to succeed. diff --git a/frame/examples/offchain-worker/src/tests.rs b/frame/examples/offchain-worker/src/tests.rs index 3df7f4a8d5439..203a59a8af03c 100644 --- a/frame/examples/offchain-worker/src/tests.rs +++ b/frame/examples/offchain-worker/src/tests.rs @@ -30,22 +30,18 @@ use sp_core::{ use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt}; use sp_runtime::{ - testing::{Header, TestXt}, + testing::TestXt, traits::{BlakeTwo256, Extrinsic as ExtrinsicT, IdentifyAccount, IdentityLookup, Verify}, RuntimeAppPublic, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; // For testing the module, we construct a mock runtime. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Example: example_offchain_worker::{Pallet, Call, Storage, Event, ValidateUnsigned}, } ); @@ -57,13 +53,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = sp_core::sr25519::Public; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -274,7 +269,7 @@ fn should_submit_unsigned_transaction_on_chain_for_any_account() { let signature_valid = ::Public, - ::BlockNumber, + frame_system::pallet_prelude::BlockNumberFor, > as SignedPayload>::verify::(&price_payload, signature); assert!(signature_valid); @@ -328,7 +323,7 @@ fn should_submit_unsigned_transaction_on_chain_for_all_accounts() { let signature_valid = ::Public, - ::BlockNumber, + frame_system::pallet_prelude::BlockNumberFor, > as SignedPayload>::verify::(&price_payload, signature); assert!(signature_valid); diff --git a/frame/examples/split/src/mock.rs b/frame/examples/split/src/mock.rs index e479e821f4262..bee3633ef68f2 100644 --- a/frame/examples/split/src/mock.rs +++ b/frame/examples/split/src/mock.rs @@ -16,17 +16,14 @@ // limitations under the License. use crate as pallet_template; -use frame_support::derive_impl; +use frame_support::{derive_impl, sp_runtime::BuildStorage}; +use sp_core::ConstU64; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, TemplatePallet: pallet_template, @@ -37,6 +34,8 @@ frame_support::construct_runtime!( /// details. #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { + type Block = Block; + type BlockHashCount = ConstU64<10>; type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; @@ -52,5 +51,5 @@ impl pallet_template::Config for Test { // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index 2aed177578a01..4e24717a39e93 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -126,6 +126,7 @@ use frame_support::{ }, weights::Weight, }; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::{ generic::Digest, traits::{ @@ -178,14 +179,17 @@ pub struct Executive< impl< System: frame_system::Config + EnsureInherentsAreFirst, - Block: traits::Block
, + Block: traits::Block< + Header = frame_system::pallet_prelude::HeaderFor, + Hash = System::Hash, + >, Context: Default, UnsignedValidator, AllPalletsWithSystem: OnRuntimeUpgrade - + OnInitialize - + OnIdle - + OnFinalize - + OffchainWorker, + + OnInitialize> + + OnIdle> + + OnFinalize> + + OffchainWorker>, COnRuntimeUpgrade: OnRuntimeUpgrade, > ExecuteBlock for Executive @@ -212,15 +216,18 @@ where #[cfg(feature = "try-runtime")] impl< System: frame_system::Config + EnsureInherentsAreFirst, - Block: traits::Block
, + Block: traits::Block< + Header = frame_system::pallet_prelude::HeaderFor, + Hash = System::Hash, + >, Context: Default, UnsignedValidator, AllPalletsWithSystem: OnRuntimeUpgrade - + OnInitialize - + OnIdle - + OnFinalize - + OffchainWorker - + frame_support::traits::TryState, + + OnInitialize> + + OnIdle> + + OnFinalize> + + OffchainWorker> + + frame_support::traits::TryState>, COnRuntimeUpgrade: OnRuntimeUpgrade, > Executive where @@ -297,10 +304,9 @@ where // run the try-state checks of all pallets, ensuring they don't alter any state. let _guard = frame_support::StorageNoopGuard::default(); - >::try_state( - *header.number(), - select, - ) + , + >>::try_state(*header.number(), select) .map_err(|e| { frame_support::log::error!(target: LOG_TARGET, "failure: {:?}", e); e @@ -350,7 +356,9 @@ where ) -> Result { if checks.try_state() { let _guard = frame_support::StorageNoopGuard::default(); - >::try_state( + , + >>::try_state( frame_system::Pallet::::block_number(), frame_try_runtime::TryStateSelect::All, )?; @@ -363,7 +371,9 @@ where if checks.try_state() { let _guard = frame_support::StorageNoopGuard::default(); - >::try_state( + , + >>::try_state( frame_system::Pallet::::block_number(), frame_try_runtime::TryStateSelect::All, )?; @@ -375,14 +385,17 @@ where impl< System: frame_system::Config + EnsureInherentsAreFirst, - Block: traits::Block
, + Block: traits::Block< + Header = frame_system::pallet_prelude::HeaderFor, + Hash = System::Hash, + >, Context: Default, UnsignedValidator, AllPalletsWithSystem: OnRuntimeUpgrade - + OnInitialize - + OnIdle - + OnFinalize - + OffchainWorker, + + OnInitialize> + + OnIdle> + + OnFinalize> + + OffchainWorker>, COnRuntimeUpgrade: OnRuntimeUpgrade, > Executive where @@ -399,14 +412,14 @@ where } /// Start the execution of a particular block. - pub fn initialize_block(header: &System::Header) { + pub fn initialize_block(header: &frame_system::pallet_prelude::HeaderFor) { sp_io::init_tracing(); sp_tracing::enter_span!(sp_tracing::Level::TRACE, "init_block"); let digests = Self::extract_pre_digest(header); Self::initialize_block_impl(header.number(), header.parent_hash(), &digests); } - fn extract_pre_digest(header: &System::Header) -> Digest { + fn extract_pre_digest(header: &frame_system::pallet_prelude::HeaderFor) -> Digest { let mut digest = ::default(); header.digest().logs().iter().for_each(|d| { if d.as_pre_runtime().is_some() { @@ -417,7 +430,7 @@ where } fn initialize_block_impl( - block_number: &System::BlockNumber, + block_number: &BlockNumberFor, parent_hash: &System::Hash, digest: &Digest, ) { @@ -432,7 +445,7 @@ where } >::initialize(block_number, parent_hash, digest); weight = weight.saturating_add(, >>::on_initialize(*block_number)); weight = weight.saturating_add( >::get().base_block, @@ -467,8 +480,8 @@ where // Check that `parent_hash` is correct. let n = *header.number(); assert!( - n > System::BlockNumber::zero() && - >::block_hash(n - System::BlockNumber::one()) == + n > BlockNumberFor::::zero() && + >::block_hash(n - BlockNumberFor::::one()) == *header.parent_hash(), "Parent hash should be valid.", ); @@ -518,7 +531,7 @@ where /// Finalize the block - it is up the caller to ensure that all header fields are valid /// except state-root. - pub fn finalize_block() -> System::Header { + pub fn finalize_block() -> frame_system::pallet_prelude::HeaderFor { sp_io::init_tracing(); sp_tracing::enter_span!(sp_tracing::Level::TRACE, "finalize_block"); >::note_finished_extrinsics(); @@ -535,7 +548,7 @@ where let remaining_weight = max_weight.saturating_sub(weight.total()); if remaining_weight.all_gt(Weight::zero()) { - let used_weight = >::on_idle( + let used_weight = >>::on_idle( block_number, remaining_weight, ); @@ -545,7 +558,7 @@ where ); } - >::on_finalize(block_number); + >>::on_finalize(block_number); } /// Apply extrinsic outside of the block execution function. @@ -585,7 +598,7 @@ where Ok(r.map(|_| ()).map_err(|e| e.error)) } - fn final_checks(header: &System::Header) { + fn final_checks(header: &frame_system::pallet_prelude::HeaderFor) { sp_tracing::enter_span!(sp_tracing::Level::TRACE, "final_checks"); // remove temporaries let new_header = >::finalize(); @@ -657,7 +670,7 @@ where } /// Start an offchain worker and generate extrinsics. - pub fn offchain_worker(header: &System::Header) { + pub fn offchain_worker(header: &frame_system::pallet_prelude::HeaderFor) { sp_io::init_tracing(); // We need to keep events available for offchain workers, // hence we initialize the block manually. @@ -671,7 +684,7 @@ where // as well. frame_system::BlockHash::::insert(header.number(), header.hash()); - >::offchain_worker( + >>::offchain_worker( *header.number(), ) } @@ -689,7 +702,7 @@ mod tests { transaction_validity::{ InvalidTransaction, TransactionValidityError, UnknownTransaction, ValidTransaction, }, - DispatchError, + BuildStorage, DispatchError, }; use frame_support::{ @@ -718,17 +731,17 @@ mod tests { impl Hooks> for Pallet { // module hooks. // one with block number arg and one without - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { println!("on_initialize({})", n); Weight::from_parts(175, 0) } - fn on_idle(n: T::BlockNumber, remaining_weight: Weight) -> Weight { + fn on_idle(n: BlockNumberFor, remaining_weight: Weight) -> Weight { println!("on_idle{}, {})", n, remaining_weight); Weight::from_parts(175, 0) } - fn on_finalize(n: T::BlockNumber) { + fn on_finalize(n: BlockNumberFor) { println!("on_finalize({})", n); } @@ -737,8 +750,8 @@ mod tests { Weight::from_parts(200, 0) } - fn offchain_worker(n: T::BlockNumber) { - assert_eq!(T::BlockNumber::from(1u32), n); + fn offchain_worker(n: BlockNumberFor) { + assert_eq!(BlockNumberFor::::from(1u32), n); } } @@ -828,12 +841,9 @@ mod tests { } frame_support::construct_runtime!( - pub struct Runtime where - Block = TestBlock, - NodeBlock = TestBlock, - UncheckedExtrinsic = TestUncheckedExtrinsic + pub struct Runtime { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event}, Custom: custom::{Pallet, Call, ValidateUnsigned, Inherent}, @@ -858,14 +868,13 @@ mod tests { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; - type BlockNumber = u64; type Hash = sp_core::H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = TestBlock; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = RuntimeVersion; @@ -929,7 +938,6 @@ mod tests { ); type TestXt = sp_runtime::testing::TestXt; type TestBlock = Block; - type TestUncheckedExtrinsic = TestXt; // Will contain `true` when the custom runtime logic was called. const CUSTOM_ON_RUNTIME_KEY: &[u8] = b":custom:on_runtime"; @@ -972,7 +980,7 @@ mod tests { #[test] fn balance_transfer_dispatch_works() { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 211)] } .assimilate_storage(&mut t) .unwrap(); @@ -1000,7 +1008,7 @@ mod tests { } fn new_test_ext(balance_factor: Balance) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 111 * balance_factor)] } .assimilate_storage(&mut t) .unwrap(); @@ -1008,7 +1016,7 @@ mod tests { } fn new_test_ext_v0(balance_factor: Balance) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 111 * balance_factor)] } .assimilate_storage(&mut t) .unwrap(); diff --git a/frame/fast-unstake/src/lib.rs b/frame/fast-unstake/src/lib.rs index 9be5878f2e199..ca282a1615d66 100644 --- a/frame/fast-unstake/src/lib.rs +++ b/frame/fast-unstake/src/lib.rs @@ -272,8 +272,8 @@ pub mod pallet { } #[pallet::hooks] - impl Hooks for Pallet { - fn on_idle(_: T::BlockNumber, remaining_weight: Weight) -> Weight { + impl Hooks> for Pallet { + fn on_idle(_: BlockNumberFor, remaining_weight: Weight) -> Weight { if remaining_weight.any_lt(T::DbWeight::get().reads(2)) { return Weight::from_parts(0, 0) } @@ -295,7 +295,7 @@ pub mod pallet { } #[cfg(feature = "try-runtime")] - fn try_state(_n: T::BlockNumber) -> Result<(), TryRuntimeError> { + fn try_state(_n: BlockNumberFor) -> Result<(), TryRuntimeError> { // ensure that the value of `ErasToCheckPerBlock` is less than // `T::MaxErasToCheckPerBlock`. ensure!( diff --git a/frame/fast-unstake/src/mock.rs b/frame/fast-unstake/src/mock.rs index ecdbad9ff7745..192d525e278d7 100644 --- a/frame/fast-unstake/src/mock.rs +++ b/frame/fast-unstake/src/mock.rs @@ -23,13 +23,16 @@ use frame_support::{ traits::{ConstU64, Currency}, weights::constants::WEIGHT_REF_TIME_PER_SECOND, }; -use sp_runtime::traits::{Convert, IdentityLookup}; +use sp_runtime::{ + traits::{Convert, IdentityLookup}, + BuildStorage, +}; use pallet_staking::{Exposure, IndividualExposure, StakerStatus}; use sp_std::prelude::*; pub type AccountId = u128; -pub type AccountIndex = u32; +pub type Nonce = u32; pub type BlockNumber = u64; pub type Balance = u128; pub type T = Runtime; @@ -47,14 +50,13 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; - type BlockNumber = BlockNumber; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); @@ -195,14 +197,9 @@ impl fast_unstake::Config for Runtime { } type Block = frame_system::mocking::MockBlock; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; + frame_support::construct_runtime!( - pub struct Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub struct Runtime { System: frame_system, Timestamp: pallet_timestamp, Balances: pallet_balances, @@ -278,7 +275,7 @@ impl ExtBuilder { pub(crate) fn build(self) -> sp_io::TestExternalities { sp_tracing::try_init_simple(); let mut storage = - frame_system::GenesisConfig::default().build_storage::().unwrap(); + frame_system::GenesisConfig::::default().build_storage().unwrap(); let validators_range = VALIDATOR_PREFIX..VALIDATOR_PREFIX + VALIDATORS_PER_ERA; let nominators_range = diff --git a/frame/glutton/src/lib.rs b/frame/glutton/src/lib.rs index c02a14810d0b2..ae3e4f87f0e80 100644 --- a/frame/glutton/src/lib.rs +++ b/frame/glutton/src/lib.rs @@ -130,14 +130,16 @@ pub mod pallet { #[pallet::genesis_config] #[derive(DefaultNoBound)] - pub struct GenesisConfig { + pub struct GenesisConfig { pub compute: FixedU64, pub storage: FixedU64, pub trash_data_count: u32, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { assert!( self.trash_data_count <= MAX_TRASH_DATA_ENTRIES, diff --git a/frame/glutton/src/mock.rs b/frame/glutton/src/mock.rs index f2ce53b206fa8..c79ddd53718eb 100644 --- a/frame/glutton/src/mock.rs +++ b/frame/glutton/src/mock.rs @@ -24,20 +24,16 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Glutton: pallet_glutton::{Pallet, Event}, } ); @@ -48,14 +44,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -76,7 +71,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); diff --git a/frame/grandpa/src/equivocation.rs b/frame/grandpa/src/equivocation.rs index 5cc5cd9bd3d70..16727f79a58d5 100644 --- a/frame/grandpa/src/equivocation.rs +++ b/frame/grandpa/src/equivocation.rs @@ -37,6 +37,7 @@ use codec::{self as codec, Decode, Encode}; use frame_support::traits::{Get, KeyOwnerProofSystem}; +use frame_system::pallet_prelude::BlockNumberFor; use log::{error, info}; use sp_consensus_grandpa::{AuthorityId, EquivocationProof, RoundNumber, SetId, KEY_TYPE}; use sp_runtime::{ @@ -118,7 +119,7 @@ pub struct EquivocationReportSystem(sp_std::marker::PhantomData<(T, impl OffenceReportSystem< Option, - (EquivocationProof, T::KeyOwnerProof), + (EquivocationProof>, T::KeyOwnerProof), > for EquivocationReportSystem where T: Config + pallet_authorship::Config + frame_system::offchain::SendTransactionTypes>, @@ -134,7 +135,7 @@ where type Longevity = L; fn publish_evidence( - evidence: (EquivocationProof, T::KeyOwnerProof), + evidence: (EquivocationProof>, T::KeyOwnerProof), ) -> Result<(), ()> { use frame_system::offchain::SubmitTransaction; let (equivocation_proof, key_owner_proof) = evidence; @@ -152,7 +153,7 @@ where } fn check_evidence( - evidence: (EquivocationProof, T::KeyOwnerProof), + evidence: (EquivocationProof>, T::KeyOwnerProof), ) -> Result<(), TransactionValidityError> { let (equivocation_proof, key_owner_proof) = evidence; @@ -172,7 +173,7 @@ where fn process_evidence( reporter: Option, - evidence: (EquivocationProof, T::KeyOwnerProof), + evidence: (EquivocationProof>, T::KeyOwnerProof), ) -> Result<(), DispatchError> { let (equivocation_proof, key_owner_proof) = evidence; let reporter = reporter.or_else(|| >::author()); diff --git a/frame/grandpa/src/lib.rs b/frame/grandpa/src/lib.rs index 8311131e97347..204bcfa826b77 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -42,6 +42,7 @@ use frame_support::{ weights::Weight, WeakBoundedVec, }; +use frame_system::pallet_prelude::BlockNumberFor; use scale_info::TypeInfo; use sp_consensus_grandpa::{ ConsensusLog, EquivocationProof, ScheduledChange, SetId, GRANDPA_AUTHORITIES_KEY, @@ -113,13 +114,13 @@ pub mod pallet { /// (from an offchain context). type EquivocationReportSystem: OffenceReportSystem< Option, - (EquivocationProof, Self::KeyOwnerProof), + (EquivocationProof>, Self::KeyOwnerProof), >; } #[pallet::hooks] impl Hooks> for Pallet { - fn on_finalize(block_number: T::BlockNumber) { + fn on_finalize(block_number: BlockNumberFor) { // check for scheduled pending authority set changes if let Some(pending_change) = >::get() { // emit signal if we're at the block that scheduled the change @@ -191,7 +192,7 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::report_equivocation(key_owner_proof.validator_count()))] pub fn report_equivocation( origin: OriginFor, - equivocation_proof: Box>, + equivocation_proof: Box>>, key_owner_proof: T::KeyOwnerProof, ) -> DispatchResultWithPostInfo { let reporter = ensure_signed(origin)?; @@ -217,7 +218,7 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::report_equivocation(key_owner_proof.validator_count()))] pub fn report_equivocation_unsigned( origin: OriginFor, - equivocation_proof: Box>, + equivocation_proof: Box>>, key_owner_proof: T::KeyOwnerProof, ) -> DispatchResultWithPostInfo { ensure_none(origin)?; @@ -245,8 +246,8 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::note_stalled())] pub fn note_stalled( origin: OriginFor, - delay: T::BlockNumber, - best_finalized_block_number: T::BlockNumber, + delay: BlockNumberFor, + best_finalized_block_number: BlockNumberFor, ) -> DispatchResult { ensure_root(origin)?; @@ -287,7 +288,7 @@ pub mod pallet { } #[pallet::type_value] - pub(super) fn DefaultForState() -> StoredState { + pub(super) fn DefaultForState() -> StoredState> { StoredState::Live } @@ -295,23 +296,23 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn state)] pub(super) type State = - StorageValue<_, StoredState, ValueQuery, DefaultForState>; + StorageValue<_, StoredState>, ValueQuery, DefaultForState>; /// Pending change: (signaled at, scheduled change). #[pallet::storage] #[pallet::getter(fn pending_change)] pub(super) type PendingChange = - StorageValue<_, StoredPendingChange>; + StorageValue<_, StoredPendingChange, T::MaxAuthorities>>; /// next block number where we can force a change. #[pallet::storage] #[pallet::getter(fn next_forced)] - pub(super) type NextForced = StorageValue<_, T::BlockNumber>; + pub(super) type NextForced = StorageValue<_, BlockNumberFor>; /// `true` if we are currently stalled. #[pallet::storage] #[pallet::getter(fn stalled)] - pub(super) type Stalled = StorageValue<_, (T::BlockNumber, T::BlockNumber)>; + pub(super) type Stalled = StorageValue<_, (BlockNumberFor, BlockNumberFor)>; /// The number of changes (both in terms of keys and underlying economic responsibilities) /// in the "set" of Grandpa validators from genesis. @@ -333,14 +334,16 @@ pub mod pallet { #[pallet::getter(fn session_for_set)] pub(super) type SetIdSession = StorageMap<_, Twox64Concat, SetId, SessionIndex>; - #[derive(Default)] + #[derive(frame_support::DefaultNoBound)] #[pallet::genesis_config] - pub struct GenesisConfig { + pub struct GenesisConfig { pub authorities: AuthorityList, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { CurrentSetId::::put(SetId::default()); Pallet::::initialize(&self.authorities) @@ -427,7 +430,7 @@ impl Pallet { /// Schedule GRANDPA to pause starting in the given number of blocks. /// Cannot be done when already paused. - pub fn schedule_pause(in_blocks: T::BlockNumber) -> DispatchResult { + pub fn schedule_pause(in_blocks: BlockNumberFor) -> DispatchResult { if let StoredState::Live = >::get() { let scheduled_at = >::block_number(); >::put(StoredState::PendingPause { delay: in_blocks, scheduled_at }); @@ -439,7 +442,7 @@ impl Pallet { } /// Schedule a resume of GRANDPA after pausing. - pub fn schedule_resume(in_blocks: T::BlockNumber) -> DispatchResult { + pub fn schedule_resume(in_blocks: BlockNumberFor) -> DispatchResult { if let StoredState::Paused = >::get() { let scheduled_at = >::block_number(); >::put(StoredState::PendingResume { delay: in_blocks, scheduled_at }); @@ -466,8 +469,8 @@ impl Pallet { /// an error if a change is already pending. pub fn schedule_change( next_authorities: AuthorityList, - in_blocks: T::BlockNumber, - forced: Option, + in_blocks: BlockNumberFor, + forced: Option>, ) -> DispatchResult { if !>::exists() { let scheduled_at = >::block_number(); @@ -504,7 +507,7 @@ impl Pallet { } /// Deposit one of this module's logs. - fn deposit_log(log: ConsensusLog) { + fn deposit_log(log: ConsensusLog>) { let log = DigestItem::Consensus(GRANDPA_ENGINE_ID, log.encode()); >::deposit_log(log); } @@ -528,13 +531,13 @@ impl Pallet { /// will push the transaction to the pool. Only useful in an offchain /// context. pub fn submit_unsigned_equivocation_report( - equivocation_proof: EquivocationProof, + equivocation_proof: EquivocationProof>, key_owner_proof: T::KeyOwnerProof, ) -> Option<()> { T::EquivocationReportSystem::publish_evidence((equivocation_proof, key_owner_proof)).ok() } - fn on_stalled(further_wait: T::BlockNumber, median: T::BlockNumber) { + fn on_stalled(further_wait: BlockNumberFor, median: BlockNumberFor) { // when we record old authority sets we could try to figure out _who_ // failed. until then, we can't meaningfully guard against // `next == last` the way that normal session changes do. diff --git a/frame/grandpa/src/mock.rs b/frame/grandpa/src/mock.rs index 3a13385d35320..35a0d99c566c0 100644 --- a/frame/grandpa/src/mock.rs +++ b/frame/grandpa/src/mock.rs @@ -25,9 +25,7 @@ use codec::Encode; use frame_election_provider_support::{onchain, SequentialPhragmen}; use frame_support::{ parameter_types, - traits::{ - ConstU128, ConstU32, ConstU64, GenesisBuild, KeyOwnerProofSystem, OnFinalize, OnInitialize, - }, + traits::{ConstU128, ConstU32, ConstU64, KeyOwnerProofSystem, OnFinalize, OnInitialize}, }; use pallet_session::historical as pallet_session_historical; use sp_consensus_grandpa::{RoundNumber, SetId, GRANDPA_ENGINE_ID}; @@ -36,20 +34,16 @@ use sp_keyring::Ed25519Keyring; use sp_runtime::{ curve::PiecewiseLinear, impl_opaque_keys, - testing::{Header, TestXt, UintAuthorityId}, + testing::{TestXt, UintAuthorityId}, traits::{IdentityLookup, OpaqueKeys}, - DigestItem, Perbill, + BuildStorage, DigestItem, Perbill, }; use sp_staking::{EraIndex, SessionIndex}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Authorship: pallet_authorship, @@ -75,14 +69,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -257,7 +250,7 @@ pub fn new_test_ext(vec: Vec<(u64, u64)>) -> sp_io::TestExternalities { } pub fn new_test_ext_raw_authorities(authorities: AuthorityList) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let balances: Vec<_> = (0..authorities.len()).map(|i| (i as u64, 10_000_000)).collect(); diff --git a/frame/identity/src/tests.rs b/frame/identity/src/tests.rs index 83035c402a7dc..1532980574c2a 100644 --- a/frame/identity/src/tests.rs +++ b/frame/identity/src/tests.rs @@ -29,20 +29,16 @@ use frame_support::{ use frame_system::{EnsureRoot, EnsureSignedBy}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, + BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Identity: pallet_identity::{Pallet, Call, Storage, Event}, } @@ -53,14 +49,13 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); @@ -118,7 +113,7 @@ impl pallet_identity::Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 10), (3, 10), (10, 100), (20, 100), (30, 100)], } diff --git a/frame/im-online/src/benchmarking.rs b/frame/im-online/src/benchmarking.rs index 4766e5edaadcf..d8170d4817e3e 100644 --- a/frame/im-online/src/benchmarking.rs +++ b/frame/im-online/src/benchmarking.rs @@ -36,7 +36,10 @@ const MAX_KEYS: u32 = 1000; pub fn create_heartbeat( k: u32, ) -> Result< - (crate::Heartbeat, ::Signature), + ( + crate::Heartbeat>, + ::Signature, + ), &'static str, > { let mut keys = Vec::new(); @@ -48,7 +51,7 @@ pub fn create_heartbeat( Keys::::put(bounded_keys); let input_heartbeat = Heartbeat { - block_number: T::BlockNumber::zero(), + block_number: frame_system::pallet_prelude::BlockNumberFor::::zero(), session_index: 0, authority_index: k - 1, validators_len: keys.len() as u32, diff --git a/frame/im-online/src/lib.rs b/frame/im-online/src/lib.rs index e1adbc062424f..1de89dd00c812 100644 --- a/frame/im-online/src/lib.rs +++ b/frame/im-online/src/lib.rs @@ -245,7 +245,7 @@ pub type IdentificationTuple = ( >>::Identification, ); -type OffchainResult = Result::BlockNumber>>; +type OffchainResult = Result>>; #[frame_support::pallet] pub mod pallet { @@ -287,7 +287,7 @@ pub mod pallet { /// rough time when we should start considering sending heartbeats, since the workers /// avoids sending them at the very beginning of the session, assuming there is a /// chance the authority will produce a block and they won't be necessary. - type NextSessionRotation: EstimateNextSessionRotation; + type NextSessionRotation: EstimateNextSessionRotation>; /// A type that gives us the ability to submit unresponsiveness offence reports. type ReportUnresponsiveness: ReportOffence< @@ -339,7 +339,7 @@ pub mod pallet { /// more accurate then the value we calculate for `HeartbeatAfter`. #[pallet::storage] #[pallet::getter(fn heartbeat_after)] - pub(super) type HeartbeatAfter = StorageValue<_, T::BlockNumber, ValueQuery>; + pub(super) type HeartbeatAfter = StorageValue<_, BlockNumberFor, ValueQuery>; /// The current set of keys that may issue a heartbeat. #[pallet::storage] @@ -374,7 +374,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { Pallet::::initialize_keys(&self.keys); } @@ -393,7 +393,7 @@ pub mod pallet { ))] pub fn heartbeat( origin: OriginFor, - heartbeat: Heartbeat, + heartbeat: Heartbeat>, // since signature verification is done in `validate_unsigned` // we can skip doing it here again. _signature: ::Signature, @@ -505,7 +505,7 @@ pub mod pallet { /// Keep track of number of authored blocks per authority, uncles are counted as /// well since they're a valid proof of being online. impl - pallet_authorship::EventHandler, T::BlockNumber> for Pallet + pallet_authorship::EventHandler, BlockNumberFor> for Pallet { fn note_author(author: ValidatorId) { Self::note_authorship(author); @@ -551,7 +551,7 @@ impl Pallet { } pub(crate) fn send_heartbeats( - block_number: T::BlockNumber, + block_number: BlockNumberFor, ) -> OffchainResult>> { const START_HEARTBEAT_RANDOM_PERIOD: Permill = Permill::from_percent(10); const START_HEARTBEAT_FINAL_PERIOD: Permill = Permill::from_percent(80); @@ -614,7 +614,7 @@ impl Pallet { authority_index: u32, key: T::AuthorityId, session_index: SessionIndex, - block_number: T::BlockNumber, + block_number: BlockNumberFor, validators_len: u32, ) -> OffchainResult { // A helper function to prepare heartbeat call. @@ -677,7 +677,7 @@ impl Pallet { fn with_heartbeat_lock( authority_index: u32, session_index: SessionIndex, - now: T::BlockNumber, + now: BlockNumberFor, f: impl FnOnce() -> OffchainResult, ) -> OffchainResult { let key = { @@ -687,7 +687,7 @@ impl Pallet { }; let storage = StorageValueRef::persistent(&key); let res = storage.mutate( - |status: Result>, StorageRetrievalError>| { + |status: Result>>, StorageRetrievalError>| { // Check if there is already a lock for that particular block. // This means that the heartbeat has already been sent, and we are just waiting // for it to be included. However if it doesn't get included for INCLUDE_THRESHOLD diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index 78a86edf54598..85da061fe904a 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -27,9 +27,9 @@ use frame_support::{ use pallet_session::historical as pallet_session_historical; use sp_core::H256; use sp_runtime::{ - testing::{Header, TestXt, UintAuthorityId}, + testing::{TestXt, UintAuthorityId}, traits::{BlakeTwo256, ConvertInto, IdentityLookup}, - Permill, + BuildStorage, Permill, }; use sp_staking::{ offence::{OffenceError, ReportOffence}, @@ -39,16 +39,12 @@ use sp_staking::{ use crate as imonline; use crate::Config; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub struct Runtime { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, ImOnline: imonline::{Pallet, Call, Storage, Config, Event}, Historical: pallet_session_historical::{Pallet}, @@ -105,7 +101,7 @@ impl ReportOffence for OffenceHandler { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut result: sp_io::TestExternalities = t.into(); // Set the default keys, otherwise session will discard the validator. result.execute_with(|| { @@ -123,14 +119,13 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/indices/src/lib.rs b/frame/indices/src/lib.rs index bcc47c0089bb8..3c0b49304131f 100644 --- a/frame/indices/src/lib.rs +++ b/frame/indices/src/lib.rs @@ -269,7 +269,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { for (a, b) in &self.indices { >::insert(a, (b, >::zero(), false)) diff --git a/frame/indices/src/mock.rs b/frame/indices/src/mock.rs index f54e4dfa088dc..d63081e0b73f8 100644 --- a/frame/indices/src/mock.rs +++ b/frame/indices/src/mock.rs @@ -22,18 +22,14 @@ use crate::{self as pallet_indices, Config}; use frame_support::traits::{ConstU32, ConstU64}; use sp_core::H256; -use sp_runtime::testing::Header; +use sp_runtime::BuildStorage; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Indices: pallet_indices::{Pallet, Call, Storage, Config, Event}, } @@ -46,13 +42,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = Indices; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -91,7 +86,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)], } diff --git a/frame/insecure-randomness-collective-flip/src/lib.rs b/frame/insecure-randomness-collective-flip/src/lib.rs index ad39c4c4fd885..474087777c46e 100644 --- a/frame/insecure-randomness-collective-flip/src/lib.rs +++ b/frame/insecure-randomness-collective-flip/src/lib.rs @@ -74,11 +74,12 @@ use safe_mix::TripletMix; use codec::Encode; use frame_support::{pallet_prelude::Weight, traits::Randomness}; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::traits::{Hash, Saturating}; const RANDOM_MATERIAL_LEN: u32 = 81; -fn block_number_to_index(block_number: T::BlockNumber) -> usize { +fn block_number_to_index(block_number: BlockNumberFor) -> usize { // on_initialize is called on the first block after genesis let index = (block_number - 1u32.into()) % RANDOM_MATERIAL_LEN.into(); index.try_into().ok().expect("Something % 81 is always smaller than usize; qed") @@ -90,7 +91,6 @@ pub use pallet::*; pub mod pallet { use super::*; use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -100,7 +100,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(block_number: T::BlockNumber) -> Weight { + fn on_initialize(block_number: BlockNumberFor) -> Weight { let parent_hash = >::parent_hash(); >::mutate(|ref mut values| { @@ -123,7 +123,7 @@ pub mod pallet { StorageValue<_, BoundedVec>, ValueQuery>; } -impl Randomness for Pallet { +impl Randomness> for Pallet { /// This randomness uses a low-influence function, drawing upon the block hashes from the /// previous 81 blocks. Its result for any given subject will be known far in advance by anyone /// observing the chain. Any block producer has significant influence over their block hashes @@ -134,7 +134,7 @@ impl Randomness for Pallet { /// WARNING: Hashing the result of this function will remove any low-influence properties it has /// and mean that all bits of the resulting value are entirely manipulatable by the author of /// the parent block, who can determine the value of `parent_hash`. - fn random(subject: &[u8]) -> (T::Hash, T::BlockNumber) { + fn random(subject: &[u8]) -> (T::Hash, BlockNumberFor) { let block_number = >::block_number(); let index = block_number_to_index::(block_number); @@ -164,8 +164,8 @@ mod tests { use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, Header as _, IdentityLookup}, + BuildStorage, }; use frame_support::{ @@ -174,16 +174,12 @@ mod tests { }; use frame_system::limits; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, CollectiveFlip: pallet_insecure_randomness_collective_flip::{Pallet, Storage}, } ); @@ -199,14 +195,13 @@ mod tests { type BlockLength = BlockLength; type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -223,7 +218,7 @@ mod tests { impl pallet_insecure_randomness_collective_flip::Config for Test {} fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); t.into() } diff --git a/frame/lottery/src/lib.rs b/frame/lottery/src/lib.rs index 178f221a8946f..a6a94b4ab19af 100644 --- a/frame/lottery/src/lib.rs +++ b/frame/lottery/src/lib.rs @@ -142,7 +142,7 @@ pub mod pallet { type Currency: ReservableCurrency; /// Something that provides randomness in the runtime. - type Randomness: Randomness; + type Randomness: Randomness>; /// The overarching event type. type RuntimeEvent: From> + IsType<::RuntimeEvent>; @@ -208,7 +208,7 @@ pub mod pallet { /// The configuration for the current lottery. #[pallet::storage] pub(crate) type Lottery = - StorageValue<_, LotteryConfig>>; + StorageValue<_, LotteryConfig, BalanceOf>>; /// Users who have purchased a ticket. (Lottery Index, Tickets Purchased) #[pallet::storage] @@ -239,7 +239,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { Lottery::::mutate(|mut lottery| -> Weight { if let Some(config) = &mut lottery { let payout_block = @@ -350,8 +350,8 @@ pub mod pallet { pub fn start_lottery( origin: OriginFor, price: BalanceOf, - length: T::BlockNumber, - delay: T::BlockNumber, + length: BlockNumberFor, + delay: BlockNumberFor, repeat: bool, ) -> DispatchResult { T::ManagerOrigin::ensure_origin(origin)?; diff --git a/frame/lottery/src/mock.rs b/frame/lottery/src/mock.rs index d89c9d6890ee2..aefb6a1cce2bf 100644 --- a/frame/lottery/src/mock.rs +++ b/frame/lottery/src/mock.rs @@ -28,21 +28,16 @@ use frame_support_test::TestRandomness; use frame_system::EnsureRoot; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, - Perbill, + BuildStorage, Perbill, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Lottery: pallet_lottery::{Pallet, Call, Storage, Event}, } @@ -58,14 +53,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; - type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -116,7 +110,7 @@ pub type SystemCall = frame_system::Call; pub type BalancesCall = pallet_balances::Call; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)], } diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index 74891186a4e22..24b9fb5fe9069 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -108,11 +108,12 @@ pub mod pallet { #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig, I: 'static = ()> { pub members: BoundedVec, + #[serde(skip)] pub phantom: PhantomData, } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { use sp_std::collections::btree_set::BTreeSet; let members_set: BTreeSet<_> = self.members.iter().collect(); @@ -524,26 +525,22 @@ mod tests { use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, + BuildStorage, }; use frame_support::{ assert_noop, assert_ok, bounded_vec, ord_parameter_types, parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild, StorageVersion}, + traits::{ConstU32, ConstU64, StorageVersion}, }; use frame_system::EnsureSignedBy; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Membership: pallet_membership::{Pallet, Call, Storage, Config, Event}, } ); @@ -559,14 +556,13 @@ mod tests { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -629,7 +625,7 @@ mod tests { } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // We use default for brevity, but you can configure as desired if needed. pallet_membership::GenesisConfig:: { members: bounded_vec![10, 20, 30], @@ -642,7 +638,7 @@ mod tests { #[cfg(feature = "runtime-benchmarks")] pub(crate) fn new_bench_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } #[cfg(feature = "runtime-benchmarks")] diff --git a/frame/merkle-mountain-range/src/lib.rs b/frame/merkle-mountain-range/src/lib.rs index 3adad1e955481..2edef9a35d57a 100644 --- a/frame/merkle-mountain-range/src/lib.rs +++ b/frame/merkle-mountain-range/src/lib.rs @@ -57,6 +57,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use frame_support::{log, weights::Weight}; +use frame_system::pallet_prelude::{BlockNumberFor, HeaderFor}; use sp_mmr_primitives::utils; use sp_runtime::{ traits::{self, One, Saturating}, @@ -91,7 +92,7 @@ pub struct ParentNumberAndHash { } impl LeafDataProvider for ParentNumberAndHash { - type LeafData = (::BlockNumber, ::Hash); + type LeafData = (BlockNumberFor, ::Hash); fn leaf_data() -> Self::LeafData { ( @@ -120,7 +121,6 @@ pub(crate) type HashOf = <>::Hashing as traits::Hash>::Outp pub mod pallet { use super::*; use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(PhantomData<(T, I)>); @@ -201,7 +201,7 @@ pub mod pallet { #[pallet::hooks] impl, I: 'static> Hooks> for Pallet { - fn on_initialize(_n: T::BlockNumber) -> Weight { + fn on_initialize(_n: BlockNumberFor) -> Weight { use primitives::LeafDataProvider; let leaves = Self::mmr_leaves(); let peaks_before = sp_mmr_primitives::utils::NodesUtils::new(leaves).number_of_peaks(); @@ -266,11 +266,7 @@ impl, I: 'static> Pallet { pos: NodeIndex, parent_hash: ::Hash, ) -> sp_std::prelude::Vec { - NodesUtils::node_temp_offchain_key::<::Header>( - &T::INDEXING_PREFIX, - pos, - parent_hash, - ) + NodesUtils::node_temp_offchain_key::>(&T::INDEXING_PREFIX, pos, parent_hash) } /// Build canonical offchain key for node `pos` in MMR. @@ -286,7 +282,7 @@ impl, I: 'static> Pallet { fn leaf_index_to_parent_block_num( leaf_index: LeafIndex, leaves_count: LeafIndex, - ) -> ::BlockNumber { + ) -> BlockNumberFor { // leaves are zero-indexed and were added one per block since pallet activation, // while block numbers are one-indexed, so block number that added `leaf_idx` is: // `block_num = block_num_when_pallet_activated + leaf_idx + 1` @@ -298,16 +294,16 @@ impl, I: 'static> Pallet { } /// Convert a block number into a leaf index. - fn block_num_to_leaf_index(block_num: T::BlockNumber) -> Result + fn block_num_to_leaf_index(block_num: BlockNumberFor) -> Result where T: frame_system::Config, { - let first_mmr_block = utils::first_mmr_block_num::( + let first_mmr_block = utils::first_mmr_block_num::>( >::block_number(), Self::mmr_leaves(), )?; - utils::block_num_to_leaf_index::(block_num, first_mmr_block) + utils::block_num_to_leaf_index::>(block_num, first_mmr_block) } /// Generate an MMR proof for the given `block_numbers`. @@ -320,8 +316,8 @@ impl, I: 'static> Pallet { /// all the leaves to be present. /// It may return an error or panic if used incorrectly. pub fn generate_proof( - block_numbers: Vec, - best_known_block_number: Option, + block_numbers: Vec>, + best_known_block_number: Option>, ) -> Result<(Vec>, primitives::Proof>), primitives::Error> { // check whether best_known_block_number provided, else use current best block let best_known_block_number = diff --git a/frame/merkle-mountain-range/src/mock.rs b/frame/merkle-mountain-range/src/mock.rs index cea426368c35c..ecc254278bf0f 100644 --- a/frame/merkle-mountain-range/src/mock.rs +++ b/frame/merkle-mountain-range/src/mock.rs @@ -25,21 +25,14 @@ use frame_support::{ }; use sp_core::H256; use sp_mmr_primitives::{Compact, LeafDataProvider}; -use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, IdentityLookup, Keccak256}, -}; +use sp_runtime::traits::{BlakeTwo256, IdentityLookup, Keccak256}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, MMR: pallet_mmr::{Pallet, Storage}, } ); @@ -48,13 +41,12 @@ impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = sp_core::sr25519::Public; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); diff --git a/frame/merkle-mountain-range/src/tests.rs b/frame/merkle-mountain-range/src/tests.rs index b628b51d2938b..429df75182eee 100644 --- a/frame/merkle-mountain-range/src/tests.rs +++ b/frame/merkle-mountain-range/src/tests.rs @@ -23,9 +23,10 @@ use sp_core::{ H256, }; use sp_mmr_primitives::{mmr_lib::helper, utils, Compact, Proof}; +use sp_runtime::BuildStorage; pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } fn register_offchain_ext(ext: &mut sp_io::TestExternalities) { @@ -53,7 +54,7 @@ pub(crate) fn hex(s: &str) -> H256 { s.parse().unwrap() } -type BlockNumber = ::BlockNumber; +type BlockNumber = frame_system::pallet_prelude::BlockNumberFor; fn decode_node( v: Vec, diff --git a/frame/message-queue/src/integration_test.rs b/frame/message-queue/src/integration_test.rs index 9371fa7c7c291..4fc639101a01f 100644 --- a/frame/message-queue/src/integration_test.rs +++ b/frame/message-queue/src/integration_test.rs @@ -37,22 +37,15 @@ use frame_support::{ use rand::{rngs::StdRng, Rng, SeedableRng}; use rand_distr::Pareto; use sp_core::H256; -use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, IdentityLookup}, -}; +use sp_runtime::traits::{BlakeTwo256, IdentityLookup}; use std::collections::{BTreeMap, BTreeSet}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event}, } ); @@ -63,14 +56,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/message-queue/src/mock.rs b/frame/message-queue/src/mock.rs index f03ab8130952b..5a68a161eb374 100644 --- a/frame/message-queue/src/mock.rs +++ b/frame/message-queue/src/mock.rs @@ -29,21 +29,17 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use sp_std::collections::btree_map::BTreeMap; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event}, } ); @@ -53,14 +49,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -288,13 +283,13 @@ impl QueuePausedQuery for MockedQueuePauser { /// Is generic since it is used by the unit test, integration tests and benchmarks. pub fn new_test_ext() -> sp_io::TestExternalities where - ::BlockNumber: From, + frame_system::pallet_prelude::BlockNumberFor: From, { sp_tracing::try_init_simple(); WeightForCall::take(); QueueChanges::take(); NumMessagesErrored::take(); - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| frame_system::Pallet::::set_block_number(1.into())); ext diff --git a/frame/multisig/src/lib.rs b/frame/multisig/src/lib.rs index 64058be9c8fbf..ab117315f8985 100644 --- a/frame/multisig/src/lib.rs +++ b/frame/multisig/src/lib.rs @@ -59,7 +59,7 @@ use frame_support::{ weights::Weight, BoundedVec, RuntimeDebug, }; -use frame_system::{self as system, RawOrigin}; +use frame_system::{self as system, pallet_prelude::BlockNumberFor, RawOrigin}; use scale_info::TypeInfo; use sp_io::hashing::blake2_256; use sp_runtime::{ @@ -183,7 +183,7 @@ pub mod pallet { T::AccountId, Blake2_128Concat, [u8; 32], - Multisig, T::AccountId, T::MaxSignatories>, + Multisig, BalanceOf, T::AccountId, T::MaxSignatories>, >; #[pallet::error] @@ -226,14 +226,14 @@ pub mod pallet { /// A multisig operation has been approved by someone. MultisigApproval { approving: T::AccountId, - timepoint: Timepoint, + timepoint: Timepoint>, multisig: T::AccountId, call_hash: CallHash, }, /// A multisig operation has been executed. MultisigExecuted { approving: T::AccountId, - timepoint: Timepoint, + timepoint: Timepoint>, multisig: T::AccountId, call_hash: CallHash, result: DispatchResult, @@ -241,7 +241,7 @@ pub mod pallet { /// A multisig operation has been cancelled. MultisigCancelled { cancelling: T::AccountId, - timepoint: Timepoint, + timepoint: Timepoint>, multisig: T::AccountId, call_hash: CallHash, }, @@ -366,7 +366,7 @@ pub mod pallet { origin: OriginFor, threshold: u16, other_signatories: Vec, - maybe_timepoint: Option>, + maybe_timepoint: Option>>, call: Box<::RuntimeCall>, max_weight: Weight, ) -> DispatchResultWithPostInfo { @@ -423,7 +423,7 @@ pub mod pallet { origin: OriginFor, threshold: u16, other_signatories: Vec, - maybe_timepoint: Option>, + maybe_timepoint: Option>>, call_hash: [u8; 32], max_weight: Weight, ) -> DispatchResultWithPostInfo { @@ -465,7 +465,7 @@ pub mod pallet { origin: OriginFor, threshold: u16, other_signatories: Vec, - timepoint: Timepoint, + timepoint: Timepoint>, call_hash: [u8; 32], ) -> DispatchResult { let who = ensure_signed(origin)?; @@ -511,7 +511,7 @@ impl Pallet { who: T::AccountId, threshold: u16, other_signatories: Vec, - maybe_timepoint: Option>, + maybe_timepoint: Option>>, call_or_hash: CallOrHash, max_weight: Weight, ) -> DispatchResultWithPostInfo { @@ -637,7 +637,7 @@ impl Pallet { } /// The current `Timepoint`. - pub fn timepoint() -> Timepoint { + pub fn timepoint() -> Timepoint> { Timepoint { height: >::block_number(), index: >::extrinsic_index().unwrap_or_default(), diff --git a/frame/multisig/src/tests.rs b/frame/multisig/src/tests.rs index cc0fbc8098936..8e704b923742a 100644 --- a/frame/multisig/src/tests.rs +++ b/frame/multisig/src/tests.rs @@ -28,21 +28,16 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, - TokenError, + BuildStorage, TokenError, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Multisig: pallet_multisig::{Pallet, Call, Storage, Event}, } @@ -54,14 +49,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -115,7 +109,7 @@ impl Config for Test { use pallet_balances::Call as BalancesCall; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 10), (3, 10), (4, 10), (5, 2)], } diff --git a/frame/nft-fractionalization/src/benchmarking.rs b/frame/nft-fractionalization/src/benchmarking.rs index 50bb6039eb6ec..0b54acdab49ea 100644 --- a/frame/nft-fractionalization/src/benchmarking.rs +++ b/frame/nft-fractionalization/src/benchmarking.rs @@ -29,7 +29,7 @@ use frame_support::{ Get, }, }; -use frame_system::RawOrigin as SystemOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin as SystemOrigin}; use pallet_nfts::{CollectionConfig, CollectionSettings, ItemConfig, MintSettings}; use sp_runtime::traits::StaticLookup; use sp_std::prelude::*; @@ -39,11 +39,8 @@ use crate::Pallet as NftFractionalization; type BalanceOf = <::Currency as InspectFungible<::AccountId>>::Balance; -type CollectionConfigOf = CollectionConfig< - BalanceOf, - ::BlockNumber, - ::NftCollectionId, ->; +type CollectionConfigOf = + CollectionConfig, BlockNumberFor, ::NftCollectionId>; fn default_collection_config() -> CollectionConfigOf where @@ -58,7 +55,7 @@ where fn mint_nft(nft_id: T::NftId) -> (T::AccountId, AccountIdLookupOf) where - T::Nfts: Create, T::BlockNumber, T::NftCollectionId>> + T::Nfts: Create, BlockNumberFor, T::NftCollectionId>> + Mutate, { let caller: T::AccountId = whitelisted_caller(); @@ -84,7 +81,7 @@ fn assert_last_event(generic_event: ::RuntimeEvent) { benchmarks! { where_clause { where - T::Nfts: Create, T::BlockNumber, T::NftCollectionId>> + T::Nfts: Create, frame_system::pallet_prelude::BlockNumberFor::, T::NftCollectionId>> + Mutate, } diff --git a/frame/nft-fractionalization/src/mock.rs b/frame/nft-fractionalization/src/mock.rs index 62ff3df5b1a0f..6565adaf6fc7e 100644 --- a/frame/nft-fractionalization/src/mock.rs +++ b/frame/nft-fractionalization/src/mock.rs @@ -29,12 +29,10 @@ use frame_system::EnsureSigned; use pallet_nfts::PalletFeatures; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, - MultiSignature, + BuildStorage, MultiSignature, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type Signature = MultiSignature; type AccountPublic = ::Signer; @@ -42,10 +40,7 @@ type AccountId = ::AccountId; // Configure a mock runtime to test the pallet. construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, NftFractionalization: pallet_nft_fractionalization, @@ -60,13 +55,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); @@ -184,7 +178,7 @@ impl Config for Test { // Build genesis storage according to the mock runtime. pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); diff --git a/frame/nfts/src/benchmarking.rs b/frame/nfts/src/benchmarking.rs index 45390bf032bd6..67ba29266245a 100644 --- a/frame/nfts/src/benchmarking.rs +++ b/frame/nfts/src/benchmarking.rs @@ -30,7 +30,7 @@ use frame_support::{ traits::{EnsureOrigin, Get}, BoundedVec, }; -use frame_system::RawOrigin as SystemOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin as SystemOrigin}; use sp_io::crypto::{sr25519_generate, sr25519_sign}; use sp_runtime::{ traits::{Bounded, IdentifyAccount, One}, @@ -589,7 +589,7 @@ benchmarks_instance_pallet! { let (item, ..) = mint_item::(0); let delegate: T::AccountId = account("delegate", 0, SEED); let delegate_lookup = T::Lookup::unlookup(delegate.clone()); - let deadline = T::BlockNumber::max_value(); + let deadline = BlockNumberFor::::max_value(); }: _(SystemOrigin::Signed(caller.clone()), collection, item, delegate_lookup, Some(deadline)) verify { assert_last_event::(Event::TransferApproved { collection, item, owner: caller, delegate, deadline: Some(deadline) }.into()); @@ -601,7 +601,7 @@ benchmarks_instance_pallet! { let delegate: T::AccountId = account("delegate", 0, SEED); let delegate_lookup = T::Lookup::unlookup(delegate.clone()); let origin = SystemOrigin::Signed(caller.clone()).into(); - let deadline = T::BlockNumber::max_value(); + let deadline = BlockNumberFor::::max_value(); Nfts::::approve_transfer(origin, collection, item, delegate_lookup.clone(), Some(deadline))?; }: _(SystemOrigin::Signed(caller.clone()), collection, item, delegate_lookup) verify { @@ -614,7 +614,7 @@ benchmarks_instance_pallet! { let delegate: T::AccountId = account("delegate", 0, SEED); let delegate_lookup = T::Lookup::unlookup(delegate.clone()); let origin = SystemOrigin::Signed(caller.clone()).into(); - let deadline = T::BlockNumber::max_value(); + let deadline = BlockNumberFor::::max_value(); Nfts::::approve_transfer(origin, collection, item, delegate_lookup.clone(), Some(deadline))?; }: _(SystemOrigin::Signed(caller.clone()), collection, item) verify { diff --git a/frame/nfts/src/features/approvals.rs b/frame/nfts/src/features/approvals.rs index 634436a8562d8..c78dd2d96b089 100644 --- a/frame/nfts/src/features/approvals.rs +++ b/frame/nfts/src/features/approvals.rs @@ -24,7 +24,7 @@ impl, I: 'static> Pallet { collection: T::CollectionId, item: T::ItemId, delegate: T::AccountId, - maybe_deadline: Option<::BlockNumber>, + maybe_deadline: Option>, ) -> DispatchResult { ensure!( Self::is_pallet_feature_enabled(PalletFeature::Approvals), diff --git a/frame/nfts/src/features/atomic_swap.rs b/frame/nfts/src/features/atomic_swap.rs index 505056be95353..5b0096d72a3d6 100644 --- a/frame/nfts/src/features/atomic_swap.rs +++ b/frame/nfts/src/features/atomic_swap.rs @@ -29,7 +29,7 @@ impl, I: 'static> Pallet { desired_collection_id: T::CollectionId, maybe_desired_item_id: Option, maybe_price: Option>>, - duration: ::BlockNumber, + duration: frame_system::pallet_prelude::BlockNumberFor, ) -> DispatchResult { ensure!( Self::is_pallet_feature_enabled(PalletFeature::Swaps), diff --git a/frame/nfts/src/features/settings.rs b/frame/nfts/src/features/settings.rs index 080d7b97f13b1..3d96a411ae708 100644 --- a/frame/nfts/src/features/settings.rs +++ b/frame/nfts/src/features/settings.rs @@ -61,7 +61,7 @@ impl, I: 'static> Pallet { collection: T::CollectionId, mint_settings: MintSettings< BalanceOf, - ::BlockNumber, + frame_system::pallet_prelude::BlockNumberFor, T::CollectionId, >, ) -> DispatchResult { diff --git a/frame/nfts/src/lib.rs b/frame/nfts/src/lib.rs index f2812674a5408..8124c71682451 100644 --- a/frame/nfts/src/lib.rs +++ b/frame/nfts/src/lib.rs @@ -171,7 +171,7 @@ pub mod pallet { /// The max duration in blocks for deadlines. #[pallet::constant] - type MaxDeadlineDuration: Get<::BlockNumber>; + type MaxDeadlineDuration: Get>; /// The max number of attributes a user could set per call. #[pallet::constant] @@ -343,7 +343,7 @@ pub mod pallet { T::CollectionId, T::ItemId, PriceWithDirection>, - ::BlockNumber, + BlockNumberFor, >, OptionQuery, >; @@ -414,7 +414,7 @@ pub mod pallet { item: T::ItemId, owner: T::AccountId, delegate: T::AccountId, - deadline: Option<::BlockNumber>, + deadline: Option>, }, /// An approval for a `delegate` account to transfer the `item` of an item /// `collection` was cancelled by its `owner`. @@ -509,7 +509,7 @@ pub mod pallet { desired_collection: T::CollectionId, desired_item: Option, price: Option>>, - deadline: ::BlockNumber, + deadline: BlockNumberFor, }, /// The swap was cancelled. SwapCancelled { @@ -518,7 +518,7 @@ pub mod pallet { desired_collection: T::CollectionId, desired_item: Option, price: Option>>, - deadline: ::BlockNumber, + deadline: BlockNumberFor, }, /// The swap has been claimed. SwapClaimed { @@ -529,7 +529,7 @@ pub mod pallet { received_item: T::ItemId, received_item_owner: T::AccountId, price: Option>>, - deadline: ::BlockNumber, + deadline: BlockNumberFor, }, /// New attributes have been set for an `item` of the `collection`. PreSignedAttributesSet { @@ -1236,7 +1236,7 @@ pub mod pallet { collection: T::CollectionId, item: T::ItemId, delegate: AccountIdLookupOf, - maybe_deadline: Option<::BlockNumber>, + maybe_deadline: Option>, ) -> DispatchResult { let maybe_check_origin = T::ForceOrigin::try_origin(origin) .map(|_| None) @@ -1659,11 +1659,7 @@ pub mod pallet { pub fn update_mint_settings( origin: OriginFor, collection: T::CollectionId, - mint_settings: MintSettings< - BalanceOf, - ::BlockNumber, - T::CollectionId, - >, + mint_settings: MintSettings, BlockNumberFor, T::CollectionId>, ) -> DispatchResult { let maybe_check_origin = T::ForceOrigin::try_origin(origin) .map(|_| None) @@ -1759,7 +1755,7 @@ pub mod pallet { desired_collection: T::CollectionId, maybe_desired_item: Option, maybe_price: Option>>, - duration: ::BlockNumber, + duration: BlockNumberFor, ) -> DispatchResult { let origin = ensure_signed(origin)?; Self::do_create_swap( diff --git a/frame/nfts/src/mock.rs b/frame/nfts/src/mock.rs index 79f0b341e9fd3..f091a53f8d7c7 100644 --- a/frame/nfts/src/mock.rs +++ b/frame/nfts/src/mock.rs @@ -27,21 +27,16 @@ use frame_support::{ use sp_core::H256; use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, - MultiSignature, + BuildStorage, MultiSignature, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Nfts: pallet_nfts::{Pallet, Call, Storage, Event}, } @@ -57,13 +52,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); @@ -131,7 +125,7 @@ impl Config for Test { } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.register_extension(KeystoreExt::new(MemoryKeystore::new())); diff --git a/frame/nfts/src/types.rs b/frame/nfts/src/types.rs index ab966f0d73828..e4e6165774627 100644 --- a/frame/nfts/src/types.rs +++ b/frame/nfts/src/types.rs @@ -26,6 +26,7 @@ use frame_support::{ traits::Get, BoundedBTreeMap, BoundedBTreeSet, }; +use frame_system::pallet_prelude::BlockNumberFor; use scale_info::{build::Fields, meta_type, Path, Type, TypeInfo, TypeParameter}; pub(super) type DepositBalanceOf = @@ -34,7 +35,7 @@ pub(super) type CollectionDetailsFor = CollectionDetails<::AccountId, DepositBalanceOf>; pub(super) type ApprovalsOf = BoundedBTreeMap< ::AccountId, - Option<::BlockNumber>, + Option>, >::ApprovalsLimit, >; pub(super) type ItemAttributesApprovals = @@ -56,23 +57,20 @@ pub(super) type ItemTipOf = ItemTip< ::AccountId, BalanceOf, >; -pub(super) type CollectionConfigFor = CollectionConfig< - BalanceOf, - ::BlockNumber, - >::CollectionId, ->; +pub(super) type CollectionConfigFor = + CollectionConfig, BlockNumberFor, >::CollectionId>; pub(super) type PreSignedMintOf = PreSignedMint< >::CollectionId, >::ItemId, ::AccountId, - ::BlockNumber, + BlockNumberFor, BalanceOf, >; pub(super) type PreSignedAttributesOf = PreSignedAttributes< >::CollectionId, >::ItemId, ::AccountId, - ::BlockNumber, + BlockNumberFor, >; /// Information about a collection. diff --git a/frame/nfts/src/weights.rs b/frame/nfts/src/weights.rs index 686fabb2a70b5..6b8c577bb12e5 100644 --- a/frame/nfts/src/weights.rs +++ b/frame/nfts/src/weights.rs @@ -35,7 +35,6 @@ // --no-median-slopes // --no-min-squares // --extrinsic=* -// --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/nfts/src/weights.rs diff --git a/frame/nicks/src/lib.rs b/frame/nicks/src/lib.rs index 7a7b33051b22e..612443f5dfd56 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -239,18 +239,14 @@ mod tests { use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, + BuildStorage, }; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances, @@ -264,14 +260,13 @@ mod tests { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -315,7 +310,7 @@ mod tests { } fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 10)] } .assimilate_storage(&mut t) .unwrap(); diff --git a/frame/nis/src/lib.rs b/frame/nis/src/lib.rs index 48d322545a635..1bf052a39d1ed 100644 --- a/frame/nis/src/lib.rs +++ b/frame/nis/src/lib.rs @@ -186,13 +186,10 @@ pub mod pallet { <::Currency as FunInspect<::AccountId>>::Balance; type DebtOf = fungible::Debt<::AccountId, ::Currency>; - type ReceiptRecordOf = ReceiptRecord< - ::AccountId, - ::BlockNumber, - BalanceOf, - >; + type ReceiptRecordOf = + ReceiptRecord<::AccountId, BlockNumberFor, BalanceOf>; type IssuanceInfoOf = IssuanceInfo>; - type SummaryRecordOf = SummaryRecord<::BlockNumber, BalanceOf>; + type SummaryRecordOf = SummaryRecord, BalanceOf>; type BidOf = Bid, ::AccountId>; type QueueTotalsTypeOf = BoundedVec<(u32, BalanceOf), ::QueueCount>; @@ -275,7 +272,7 @@ pub mod pallet { /// The base period for the duration queues. This is the common multiple across all /// supported freezing durations that can be bid upon. #[pallet::constant] - type BasePeriod: Get; + type BasePeriod: Get>; /// The minimum amount of funds that may be placed in a bid. Note that this /// does not actually limit the amount which may be represented in a receipt since bids may @@ -296,7 +293,7 @@ pub mod pallet { /// A larger value results in fewer storage hits each block, but a slower period to get to /// the target. #[pallet::constant] - type IntakePeriod: Get; + type IntakePeriod: Get>; /// The maximum amount of bids that can consolidated into receipts in a single intake. A /// larger value here means less of the block available for transactions should there be a @@ -306,7 +303,7 @@ pub mod pallet { /// The maximum proportion which may be thawed and the period over which it is reset. #[pallet::constant] - type ThawThrottle: Get<(Perquintill, Self::BlockNumber)>; + type ThawThrottle: Get<(Perquintill, BlockNumberFor)>; } #[pallet::pallet] @@ -413,7 +410,7 @@ pub mod pallet { /// The identity of the receipt. index: ReceiptIndex, /// The block number at which the receipt may be thawed. - expiry: T::BlockNumber, + expiry: BlockNumberFor, /// The owner of the receipt. who: T::AccountId, /// The proportion of the effective total issuance which the receipt represents. @@ -508,7 +505,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { let mut weight_counter = WeightCounter { used: Weight::zero(), limit: T::MaxIntakeWeight::get() }; if T::IntakePeriod::get().is_zero() || (n % T::IntakePeriod::get()).is_zero() { @@ -1062,7 +1059,7 @@ pub mod pallet { pub(crate) fn process_queue( duration: u32, - now: T::BlockNumber, + now: BlockNumberFor, our_account: &T::AccountId, issuance: &IssuanceInfo>, max_bids: u32, @@ -1106,7 +1103,7 @@ pub mod pallet { pub(crate) fn process_bid( mut bid: BidOf, - expiry: T::BlockNumber, + expiry: BlockNumberFor, _our_account: &T::AccountId, issuance: &IssuanceInfo>, remaining: &mut BalanceOf, diff --git a/frame/nis/src/mock.rs b/frame/nis/src/mock.rs index 60aa0f756e9c6..76fdf5f3f0693 100644 --- a/frame/nis/src/mock.rs +++ b/frame/nis/src/mock.rs @@ -31,21 +31,17 @@ use frame_support::{ use pallet_balances::{Instance1, Instance2}; use sp_core::{ConstU128, H256}; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; pub type Balance = u64; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances::, @@ -60,13 +56,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); @@ -157,7 +152,7 @@ impl pallet_nis::Config for Test { // This function basically just builds a genesis storage key/value store according to // our desired mockup. pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 100), (2, 100), (3, 100), (4, 100)], } @@ -170,7 +165,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { // our desired mockup, but without any balances. #[cfg(feature = "runtime-benchmarks")] pub fn new_test_ext_empty() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } pub fn run_to_block(n: u64) { diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index 6ccc142431e61..8a823d29f2355 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -115,7 +115,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { Pallet::::initialize_nodes(&self.nodes); } @@ -169,7 +169,7 @@ pub mod pallet { impl Hooks> for Pallet { /// Set reserved node every block. It may not be enabled depends on the offchain /// worker settings when starting the node. - fn offchain_worker(now: T::BlockNumber) { + fn offchain_worker(now: frame_system::pallet_prelude::BlockNumberFor) { let network_state = sp_io::offchain::network_state(); match network_state { Err(_) => log::error!( diff --git a/frame/node-authorization/src/mock.rs b/frame/node-authorization/src/mock.rs index b7c5957e15dee..84e3336b3bd68 100644 --- a/frame/node-authorization/src/mock.rs +++ b/frame/node-authorization/src/mock.rs @@ -22,25 +22,21 @@ use crate as pallet_node_authorization; use frame_support::{ ord_parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild}, + traits::{ConstU32, ConstU64}, }; use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, NodeAuthorization: pallet_node_authorization::{ Pallet, Call, Storage, Config, Event, }, @@ -53,14 +49,13 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -97,7 +92,7 @@ pub fn test_node(id: u8) -> PeerId { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_node_authorization::GenesisConfig:: { nodes: vec![(test_node(10), 10), (test_node(20), 20), (test_node(30), 30)], } diff --git a/frame/nomination-pools/benchmarking/src/mock.rs b/frame/nomination-pools/benchmarking/src/mock.rs index 62655690a2d63..2298f611d7fff 100644 --- a/frame/nomination-pools/benchmarking/src/mock.rs +++ b/frame/nomination-pools/benchmarking/src/mock.rs @@ -20,11 +20,11 @@ use frame_election_provider_support::VoteWeight; use frame_support::{pallet_prelude::*, parameter_types, traits::ConstU64, PalletId}; use sp_runtime::{ traits::{Convert, IdentityLookup}, - FixedU128, Perbill, + BuildStorage, FixedU128, Perbill, }; type AccountId = u128; -type AccountIndex = u32; +type Nonce = u32; type BlockNumber = u64; type Balance = u128; @@ -34,14 +34,13 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; - type BlockNumber = BlockNumber; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); @@ -175,12 +174,9 @@ impl pallet_nomination_pools::Config for Runtime { impl crate::Config for Runtime {} type Block = frame_system::mocking::MockBlock; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; + frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system::{Pallet, Call, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, @@ -192,7 +188,7 @@ frame_support::construct_runtime!( ); pub fn new_test_ext() -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = pallet_nomination_pools::GenesisConfig:: { min_join_bond: 2, min_create_bond: 2, diff --git a/frame/nomination-pools/src/lib.rs b/frame/nomination-pools/src/lib.rs index a356ba529aa44..c4bebc5a1d030 100644 --- a/frame/nomination-pools/src/lib.rs +++ b/frame/nomination-pools/src/lib.rs @@ -362,6 +362,7 @@ use frame_support::{ }, DefaultNoBound, PalletError, }; +use frame_system::pallet_prelude::BlockNumberFor; use scale_info::TypeInfo; use sp_core::U256; use sp_runtime::{ @@ -672,10 +673,10 @@ pub struct Commission { pub max: Option, /// Optional configuration around how often commission can be updated, and when the last /// commission update took place. - pub change_rate: Option>, + pub change_rate: Option>>, /// The block from where throttling should be checked from. This value will be updated on all /// commission updates and when setting an initial `change_rate`. - pub throttle_from: Option, + pub throttle_from: Option>, } impl Commission { @@ -817,7 +818,7 @@ impl Commission { /// throttling can be checked from this block. fn try_update_change_rate( &mut self, - change_rate: CommissionChangeRate, + change_rate: CommissionChangeRate>, ) -> DispatchResult { ensure!(!&self.less_restrictive(&change_rate), Error::::CommissionChangeRateNotAllowed); @@ -837,7 +838,7 @@ impl Commission { /// /// No change rate will always be less restrictive than some change rate, so where no /// `change_rate` is currently set, `false` is returned. - fn less_restrictive(&self, new: &CommissionChangeRate) -> bool { + fn less_restrictive(&self, new: &CommissionChangeRate>) -> bool { self.change_rate .as_ref() .map(|c| new.max_increase > c.max_increase || new.min_delay < c.min_delay) @@ -1680,7 +1681,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { MinJoinBond::::put(self.min_join_bond); MinCreateBond::::put(self.min_create_bond); @@ -1765,7 +1766,7 @@ pub mod pallet { /// A pool's commission `change_rate` has been changed. PoolCommissionChangeRateUpdated { pool_id: PoolId, - change_rate: CommissionChangeRate, + change_rate: CommissionChangeRate>, }, /// Pool commission has been claimed. PoolCommissionClaimed { pool_id: PoolId, commission: BalanceOf }, @@ -2603,7 +2604,7 @@ pub mod pallet { pub fn set_commission_change_rate( origin: OriginFor, pool_id: PoolId, - change_rate: CommissionChangeRate, + change_rate: CommissionChangeRate>, ) -> DispatchResult { let who = ensure_signed(origin)?; let mut bonded_pool = BondedPool::::get(pool_id).ok_or(Error::::PoolNotFound)?; diff --git a/frame/nomination-pools/src/mock.rs b/frame/nomination-pools/src/mock.rs index 0a404603496ec..7d0d729a40d41 100644 --- a/frame/nomination-pools/src/mock.rs +++ b/frame/nomination-pools/src/mock.rs @@ -2,7 +2,7 @@ use super::*; use crate::{self as pools}; use frame_support::{assert_ok, parameter_types, PalletId}; use frame_system::RawOrigin; -use sp_runtime::FixedU128; +use sp_runtime::{BuildStorage, FixedU128}; use sp_staking::Stake; pub type BlockNumber = u64; @@ -168,14 +168,13 @@ impl frame_system::Config for Runtime { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type DbWeight = (); @@ -246,15 +245,11 @@ impl pools::Config for Runtime { type MaxPointsToBalance = frame_support::traits::ConstU8<10>; } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub struct Runtime { - System: frame_system::{Pallet, Call, Storage, Event, Config}, + System: frame_system::{Pallet, Call, Storage, Event, Config}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Pools: pools::{Pallet, Call, Storage, Event}, } @@ -324,7 +319,7 @@ impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { sp_tracing::try_init_simple(); let mut storage = - frame_system::GenesisConfig::default().build_storage::().unwrap(); + frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = crate::GenesisConfig:: { min_join_bond: MinJoinBondConfig::get(), diff --git a/frame/nomination-pools/test-staking/src/mock.rs b/frame/nomination-pools/test-staking/src/mock.rs index 6d73615c8055b..ffc1ed56d08c4 100644 --- a/frame/nomination-pools/test-staking/src/mock.rs +++ b/frame/nomination-pools/test-staking/src/mock.rs @@ -25,11 +25,11 @@ use frame_support::{ }; use sp_runtime::{ traits::{Convert, IdentityLookup}, - FixedU128, Perbill, + BuildStorage, FixedU128, Perbill, }; type AccountId = u128; -type AccountIndex = u32; +type Nonce = u32; type BlockNumber = u64; type Balance = u128; @@ -44,14 +44,13 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; - type BlockNumber = BlockNumber; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); @@ -187,13 +186,9 @@ impl pallet_nomination_pools::Config for Runtime { } type Block = frame_system::mocking::MockBlock; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: frame_system::{Pallet, Call, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, @@ -206,7 +201,7 @@ frame_support::construct_runtime!( pub fn new_test_ext() -> sp_io::TestExternalities { sp_tracing::try_init_simple(); - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = pallet_nomination_pools::GenesisConfig:: { min_join_bond: 2, min_create_bond: 2, diff --git a/frame/offences/benchmarking/src/mock.rs b/frame/offences/benchmarking/src/mock.rs index d6c1f95117c61..0e3dfd09fe7ab 100644 --- a/frame/offences/benchmarking/src/mock.rs +++ b/frame/offences/benchmarking/src/mock.rs @@ -30,11 +30,11 @@ use pallet_session::historical as pallet_session_historical; use sp_runtime::{ testing::{Header, UintAuthorityId}, traits::IdentityLookup, + BuildStorage, }; type AccountId = u64; -type AccountIndex = u32; -type BlockNumber = u64; +type Nonce = u32; type Balance = u64; impl frame_system::Config for Test { @@ -43,14 +43,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; - type BlockNumber = BlockNumber; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); @@ -219,10 +218,7 @@ pub type Block = sp_runtime::generic::Block; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub enum Test { System: system::{Pallet, Call, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, @@ -235,6 +231,6 @@ frame_support::construct_runtime!( ); pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); sp_io::TestExternalities::new(t) } diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index 17480be76c1d8..990ceae5ac01e 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -29,9 +29,8 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, - Perbill, + BuildStorage, Perbill, }; use sp_staking::{ offence::{self, DisableStrategy, Kind, OffenceDetails}, @@ -66,16 +65,12 @@ pub fn with_on_offence_fractions) -> R>(f: F) -> OnOffencePerbill::mutate(|fractions| f(fractions)) } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub struct Runtime { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Offences: offences::{Pallet, Storage, Event}, } ); @@ -86,14 +81,13 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = RocksDbWeight; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -114,7 +108,7 @@ impl Config for Runtime { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext diff --git a/frame/preimage/src/mock.rs b/frame/preimage/src/mock.rs index 7c645da2c51d8..2fb9f36dec454 100644 --- a/frame/preimage/src/mock.rs +++ b/frame/preimage/src/mock.rs @@ -28,18 +28,14 @@ use frame_support::{ use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances, @@ -54,13 +50,12 @@ impl frame_system::Config for Test { type DbWeight = RocksDbWeight; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -104,7 +99,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let balances = pallet_balances::GenesisConfig:: { balances: vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)], }; diff --git a/frame/proxy/src/benchmarking.rs b/frame/proxy/src/benchmarking.rs index 7244dd5f17472..e0d14163d21b2 100644 --- a/frame/proxy/src/benchmarking.rs +++ b/frame/proxy/src/benchmarking.rs @@ -22,7 +22,7 @@ use super::*; use crate::Pallet as Proxy; use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller}; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use sp_runtime::traits::Bounded; const SEED: u32 = 0; @@ -41,7 +41,7 @@ fn add_proxies(n: u32, maybe_who: Option) -> Result<(), RawOrigin::Signed(caller.clone()).into(), real, T::ProxyType::default(), - T::BlockNumber::zero(), + BlockNumberFor::::zero(), )?; } Ok(()) @@ -64,7 +64,7 @@ fn add_announcements( RawOrigin::Signed(real.clone()).into(), caller_lookup, T::ProxyType::default(), - T::BlockNumber::zero(), + BlockNumberFor::::zero(), )?; real }; @@ -187,7 +187,7 @@ benchmarks! { RawOrigin::Signed(caller.clone()), real, T::ProxyType::default(), - T::BlockNumber::zero() + BlockNumberFor::::zero() ) verify { let (proxies, _) = Proxies::::get(caller); @@ -202,7 +202,7 @@ benchmarks! { RawOrigin::Signed(caller.clone()), delegate, T::ProxyType::default(), - T::BlockNumber::zero() + BlockNumberFor::::zero() ) verify { let (proxies, _) = Proxies::::get(caller); @@ -224,7 +224,7 @@ benchmarks! { }: _( RawOrigin::Signed(caller.clone()), T::ProxyType::default(), - T::BlockNumber::zero(), + BlockNumberFor::::zero(), 0 ) verify { @@ -246,7 +246,7 @@ benchmarks! { Pallet::::create_pure( RawOrigin::Signed(whitelisted_caller()).into(), T::ProxyType::default(), - T::BlockNumber::zero(), + BlockNumberFor::::zero(), 0 )?; let height = system::Pallet::::block_number(); diff --git a/frame/proxy/src/lib.rs b/frame/proxy/src/lib.rs index 76ff2662bd0f4..33e9fcfade35a 100644 --- a/frame/proxy/src/lib.rs +++ b/frame/proxy/src/lib.rs @@ -40,7 +40,7 @@ use frame_support::{ traits::{Currency, Get, InstanceFilter, IsSubType, IsType, OriginTrait, ReservableCurrency}, RuntimeDebug, }; -use frame_system::{self as system, ensure_signed}; +use frame_system::{self as system, ensure_signed, pallet_prelude::BlockNumberFor}; pub use pallet::*; use scale_info::TypeInfo; use sp_io::hashing::blake2_256; @@ -227,7 +227,7 @@ pub mod pallet { origin: OriginFor, delegate: AccountIdLookupOf, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, ) -> DispatchResult { let who = ensure_signed(origin)?; let delegate = T::Lookup::lookup(delegate)?; @@ -247,7 +247,7 @@ pub mod pallet { origin: OriginFor, delegate: AccountIdLookupOf, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, ) -> DispatchResult { let who = ensure_signed(origin)?; let delegate = T::Lookup::lookup(delegate)?; @@ -291,7 +291,7 @@ pub mod pallet { pub fn create_pure( origin: OriginFor, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, index: u16, ) -> DispatchResult { let who = ensure_signed(origin)?; @@ -341,7 +341,7 @@ pub mod pallet { spawner: AccountIdLookupOf, proxy_type: T::ProxyType, index: u16, - #[pallet::compact] height: T::BlockNumber, + #[pallet::compact] height: BlockNumberFor, #[pallet::compact] ext_index: u32, ) -> DispatchResult { let who = ensure_signed(origin)?; @@ -535,14 +535,14 @@ pub mod pallet { delegator: T::AccountId, delegatee: T::AccountId, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, }, /// A proxy was removed. ProxyRemoved { delegator: T::AccountId, delegatee: T::AccountId, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, }, } @@ -575,7 +575,10 @@ pub mod pallet { Twox64Concat, T::AccountId, ( - BoundedVec, T::MaxProxies>, + BoundedVec< + ProxyDefinition>, + T::MaxProxies, + >, BalanceOf, ), ValueQuery, @@ -589,7 +592,7 @@ pub mod pallet { Twox64Concat, T::AccountId, ( - BoundedVec, T::BlockNumber>, T::MaxPending>, + BoundedVec, BlockNumberFor>, T::MaxPending>, BalanceOf, ), ValueQuery, @@ -612,7 +615,7 @@ impl Pallet { who: &T::AccountId, proxy_type: &T::ProxyType, index: u16, - maybe_when: Option<(T::BlockNumber, u32)>, + maybe_when: Option<(BlockNumberFor, u32)>, ) -> T::AccountId { let (height, ext_index) = maybe_when.unwrap_or_else(|| { ( @@ -638,7 +641,7 @@ impl Pallet { delegator: &T::AccountId, delegatee: T::AccountId, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, ) -> DispatchResult { ensure!(delegator != &delegatee, Error::::NoSelfProxy); Proxies::::try_mutate(delegator, |(ref mut proxies, ref mut deposit)| { @@ -678,7 +681,7 @@ impl Pallet { delegator: &T::AccountId, delegatee: T::AccountId, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, ) -> DispatchResult { Proxies::::try_mutate_exists(delegator, |x| { let (mut proxies, old_deposit) = x.take().ok_or(Error::::NotFound)?; @@ -734,7 +737,7 @@ impl Pallet { } fn edit_announcements< - F: FnMut(&Announcement, T::BlockNumber>) -> bool, + F: FnMut(&Announcement, BlockNumberFor>) -> bool, >( delegate: &T::AccountId, f: F, @@ -760,8 +763,8 @@ impl Pallet { real: &T::AccountId, delegate: &T::AccountId, force_proxy_type: Option, - ) -> Result, DispatchError> { - let f = |x: &ProxyDefinition| -> bool { + ) -> Result>, DispatchError> { + let f = |x: &ProxyDefinition>| -> bool { &x.delegate == delegate && force_proxy_type.as_ref().map_or(true, |y| &x.proxy_type == y) }; @@ -769,7 +772,7 @@ impl Pallet { } fn do_proxy( - def: ProxyDefinition, + def: ProxyDefinition>, real: T::AccountId, call: ::RuntimeCall, ) { diff --git a/frame/proxy/src/tests.rs b/frame/proxy/src/tests.rs index 54b76413bcff4..1f4d2617700e6 100644 --- a/frame/proxy/src/tests.rs +++ b/frame/proxy/src/tests.rs @@ -31,20 +31,16 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Proxy: proxy::{Pallet, Call, Storage, Event}, Utility: pallet_utility::{Pallet, Call, Event}, @@ -57,14 +53,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -174,7 +169,7 @@ use pallet_utility::{Call as UtilityCall, Event as UtilityEvent}; type SystemError = frame_system::Error; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 10), (3, 10), (4, 10), (5, 3)], } diff --git a/frame/ranked-collective/src/lib.rs b/frame/ranked-collective/src/lib.rs index 6fe9fc221a7df..fe1308cd034f4 100644 --- a/frame/ranked-collective/src/lib.rs +++ b/frame/ranked-collective/src/lib.rs @@ -391,7 +391,7 @@ pub mod pallet { type DemoteOrigin: EnsureOrigin; /// The polling system used for our voting. - type Polls: Polling, Votes = Votes, Moment = Self::BlockNumber>; + type Polls: Polling, Votes = Votes, Moment = BlockNumberFor>; /// Convert the tally class into the minimum rank required to vote on the poll. If /// `Polls::Class` is the same type as `Rank`, then `Identity` can be used here to mean diff --git a/frame/ranked-collective/src/tests.rs b/frame/ranked-collective/src/tests.rs index 338dcaacedcf7..ba8c5a0f937ba 100644 --- a/frame/ranked-collective/src/tests.rs +++ b/frame/ranked-collective/src/tests.rs @@ -27,24 +27,20 @@ use frame_support::{ }; use sp_core::{Get, H256}; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup, ReduceBy}, + BuildStorage, }; use super::*; use crate as pallet_ranked_collective; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type Class = Rank; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Club: pallet_ranked_collective::{Pallet, Call, Storage, Event}, } ); @@ -55,14 +51,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -199,7 +194,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext diff --git a/frame/recovery/src/lib.rs b/frame/recovery/src/lib.rs index 8f70ebfe5ec67..9c01d25d4f76b 100644 --- a/frame/recovery/src/lib.rs +++ b/frame/recovery/src/lib.rs @@ -334,7 +334,7 @@ pub mod pallet { _, Twox64Concat, T::AccountId, - RecoveryConfig, FriendsOf>, + RecoveryConfig, BalanceOf, FriendsOf>, >; /// Active recovery attempts. @@ -349,7 +349,7 @@ pub mod pallet { T::AccountId, Twox64Concat, T::AccountId, - ActiveRecovery, FriendsOf>, + ActiveRecovery, BalanceOf, FriendsOf>, >; /// The list of allowed proxy accounts. @@ -440,7 +440,7 @@ pub mod pallet { origin: OriginFor, friends: Vec, threshold: u16, - delay_period: T::BlockNumber, + delay_period: BlockNumberFor, ) -> DispatchResult { let who = ensure_signed(origin)?; // Check account is not already set up for recovery diff --git a/frame/recovery/src/mock.rs b/frame/recovery/src/mock.rs index 523dd3aa3e8dc..2f2bd866a7198 100644 --- a/frame/recovery/src/mock.rs +++ b/frame/recovery/src/mock.rs @@ -26,20 +26,16 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Recovery: recovery::{Pallet, Call, Storage, Event}, } @@ -52,13 +48,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -115,7 +110,7 @@ pub type BalancesCall = pallet_balances::Call; pub type RecoveryCall = super::Call; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)], } diff --git a/frame/referenda/src/benchmarking.rs b/frame/referenda/src/benchmarking.rs index 4c332a3048d0b..d4b273c0307a3 100644 --- a/frame/referenda/src/benchmarking.rs +++ b/frame/referenda/src/benchmarking.rs @@ -172,7 +172,9 @@ fn skip_timeout_period, I: 'static>(index: ReferendumIndex) { frame_system::Pallet::::set_block_number(timeout_period_over); } -fn alarm_time, I: 'static>(index: ReferendumIndex) -> T::BlockNumber { +fn alarm_time, I: 'static>( + index: ReferendumIndex, +) -> frame_system::pallet_prelude::BlockNumberFor { let status = Referenda::::ensure_ongoing(index).unwrap(); status.alarm.unwrap().0 } diff --git a/frame/referenda/src/lib.rs b/frame/referenda/src/lib.rs index 3756257c33fe5..8ff754dc0db8e 100644 --- a/frame/referenda/src/lib.rs +++ b/frame/referenda/src/lib.rs @@ -77,6 +77,7 @@ use frame_support::{ }, BoundedVec, }; +use frame_system::pallet_prelude::BlockNumberFor; use scale_info::TypeInfo; use sp_runtime::{ traits::{AtLeast32BitUnsigned, Bounded, Dispatchable, One, Saturating, Zero}, @@ -161,8 +162,8 @@ pub mod pallet { /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; /// The Scheduler. - type Scheduler: ScheduleAnon, PalletsOriginOf> - + ScheduleNamed, PalletsOriginOf>; + type Scheduler: ScheduleAnon, CallOf, PalletsOriginOf> + + ScheduleNamed, CallOf, PalletsOriginOf>; /// Currency type for this pallet. type Currency: ReservableCurrency; // Origins and unbalances. @@ -201,25 +202,25 @@ pub mod pallet { /// The number of blocks after submission that a referendum must begin being decided by. /// Once this passes, then anyone may cancel the referendum. #[pallet::constant] - type UndecidingTimeout: Get; + type UndecidingTimeout: Get>; /// Quantization level for the referendum wakeup scheduler. A higher number will result in /// fewer storage reads/writes needed for smaller voters, but also result in delays to the /// automatic referendum status changes. Explicit servicing instructions are unaffected. #[pallet::constant] - type AlarmInterval: Get; + type AlarmInterval: Get>; // The other stuff. /// Information concerning the different referendum tracks. #[pallet::constant] type Tracks: Get< Vec<( - , Self::BlockNumber>>::Id, - TrackInfo, Self::BlockNumber>, + , BlockNumberFor>>::Id, + TrackInfo, BlockNumberFor>, )>, > + TracksInfo< BalanceOf, - Self::BlockNumber, + BlockNumberFor, RuntimeOrigin = ::PalletsOrigin, >; @@ -432,7 +433,7 @@ pub mod pallet { origin: OriginFor, proposal_origin: Box>, proposal: BoundedCallOf, - enactment_moment: DispatchTime, + enactment_moment: DispatchTime>, ) -> DispatchResult { let proposal_origin = *proposal_origin; let who = T::SubmitOrigin::ensure_origin(origin, &proposal_origin)?; @@ -704,7 +705,7 @@ pub mod pallet { impl, I: 'static> Polling for Pallet { type Index = ReferendumIndex; type Votes = VotesOf; - type Moment = T::BlockNumber; + type Moment = BlockNumberFor; type Class = TrackIdOf; fn classes() -> Vec { @@ -713,7 +714,7 @@ impl, I: 'static> Polling for Pallet { fn access_poll( index: Self::Index, - f: impl FnOnce(PollStatus<&mut T::Tally, T::BlockNumber, TrackIdOf>) -> R, + f: impl FnOnce(PollStatus<&mut T::Tally, BlockNumberFor, TrackIdOf>) -> R, ) -> R { match ReferendumInfoFor::::get(index) { Some(ReferendumInfo::Ongoing(mut status)) => { @@ -732,7 +733,7 @@ impl, I: 'static> Polling for Pallet { fn try_access_poll( index: Self::Index, f: impl FnOnce( - PollStatus<&mut T::Tally, T::BlockNumber, TrackIdOf>, + PollStatus<&mut T::Tally, BlockNumberFor, TrackIdOf>, ) -> Result, ) -> Result { match ReferendumInfoFor::::get(index) { @@ -849,7 +850,7 @@ impl, I: 'static> Pallet { fn schedule_enactment( index: ReferendumIndex, track: &TrackInfoOf, - desired: DispatchTime, + desired: DispatchTime>, origin: PalletsOriginOf, call: BoundedCallOf, ) { @@ -871,8 +872,8 @@ impl, I: 'static> Pallet { /// Set an alarm to dispatch `call` at block number `when`. fn set_alarm( call: BoundedCallOf, - when: T::BlockNumber, - ) -> Option<(T::BlockNumber, ScheduleAddressOf)> { + when: BlockNumberFor, + ) -> Option<(BlockNumberFor, ScheduleAddressOf)> { let alarm_interval = T::AlarmInterval::get().max(One::one()); // Alarm must go off no earlier than `when`. // This rounds `when` upwards to the next multiple of `alarm_interval`. @@ -905,9 +906,9 @@ impl, I: 'static> Pallet { fn begin_deciding( status: &mut ReferendumStatusOf, index: ReferendumIndex, - now: T::BlockNumber, + now: BlockNumberFor, track: &TrackInfoOf, - ) -> (Option, BeginDecidingBranch) { + ) -> (Option>, BeginDecidingBranch) { let is_passing = Self::is_passing( &status.tally, Zero::zero(), @@ -943,11 +944,11 @@ impl, I: 'static> Pallet { /// /// If `None`, then it is queued and should be nudged automatically as the queue gets drained. fn ready_for_deciding( - now: T::BlockNumber, + now: BlockNumberFor, track: &TrackInfoOf, index: ReferendumIndex, status: &mut ReferendumStatusOf, - ) -> (Option, ServiceBranch) { + ) -> (Option>, ServiceBranch) { let deciding_count = DecidingCount::::get(status.track); if deciding_count < track.max_deciding { // Begin deciding. @@ -1004,7 +1005,7 @@ impl, I: 'static> Pallet { fn ensure_alarm_at( status: &mut ReferendumStatusOf, index: ReferendumIndex, - alarm: T::BlockNumber, + alarm: BlockNumberFor, ) -> bool { if status.alarm.as_ref().map_or(true, |&(when, _)| when != alarm) { // Either no alarm or one that was different @@ -1049,7 +1050,7 @@ impl, I: 'static> Pallet { /// `TrackQueue`. Basically this happens when a referendum is in the deciding queue and receives /// a vote, or when it moves into the deciding queue. fn service_referendum( - now: T::BlockNumber, + now: BlockNumberFor, index: ReferendumIndex, mut status: ReferendumStatusOf, ) -> (ReferendumInfoOf, bool, ServiceBranch) { @@ -1061,7 +1062,7 @@ impl, I: 'static> Pallet { }; // Default the alarm to the end of the world. let timeout = status.submitted + T::UndecidingTimeout::get(); - let mut alarm = T::BlockNumber::max_value(); + let mut alarm = BlockNumberFor::::max_value(); let branch; match &mut status.deciding { None => { @@ -1192,7 +1193,7 @@ impl, I: 'static> Pallet { }, } - let dirty_alarm = if alarm < T::BlockNumber::max_value() { + let dirty_alarm = if alarm < BlockNumberFor::::max_value() { Self::ensure_alarm_at(&mut status, index, alarm) } else { Self::ensure_no_alarm(&mut status) @@ -1207,7 +1208,7 @@ impl, I: 'static> Pallet { tally: &T::Tally, track_id: TrackIdOf, track: &TrackInfoOf, - ) -> T::BlockNumber { + ) -> BlockNumberFor { deciding.confirming.unwrap_or_else(|| { // Set alarm to the point where the current voting would make it pass. let approval = tally.approval(track_id); @@ -1266,8 +1267,8 @@ impl, I: 'static> Pallet { /// `approval_needed`. fn is_passing( tally: &T::Tally, - elapsed: T::BlockNumber, - period: T::BlockNumber, + elapsed: BlockNumberFor, + period: BlockNumberFor, support_needed: &Curve, approval_needed: &Curve, id: TrackIdOf, diff --git a/frame/referenda/src/migration.rs b/frame/referenda/src/migration.rs index 6f796ca40d9be..6f5e42cd49657 100644 --- a/frame/referenda/src/migration.rs +++ b/frame/referenda/src/migration.rs @@ -37,7 +37,7 @@ pub mod v0 { pub type ReferendumInfoOf = ReferendumInfo< TrackIdOf, PalletsOriginOf, - ::BlockNumber, + frame_system::pallet_prelude::BlockNumberFor, BoundedCallOf, BalanceOf, TallyOf, diff --git a/frame/referenda/src/mock.rs b/frame/referenda/src/mock.rs index 1a43257cb94e1..d4a23d3e24b4e 100644 --- a/frame/referenda/src/mock.rs +++ b/frame/referenda/src/mock.rs @@ -31,19 +31,14 @@ use frame_support::{ use frame_system::{EnsureRoot, EnsureSignedBy}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, Hash, IdentityLookup}, - DispatchResult, Perbill, + BuildStorage, DispatchResult, Perbill, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances, @@ -70,14 +65,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -233,7 +227,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let balances = vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100), (6, 100)]; pallet_balances::GenesisConfig:: { balances } .assimilate_storage(&mut t) diff --git a/frame/referenda/src/types.rs b/frame/referenda/src/types.rs index d61b8955443c2..ba89383888a7d 100644 --- a/frame/referenda/src/types.rs +++ b/frame/referenda/src/types.rs @@ -42,7 +42,7 @@ pub type PalletsOriginOf = pub type ReferendumInfoOf = ReferendumInfo< TrackIdOf, PalletsOriginOf, - ::BlockNumber, + BlockNumberFor, BoundedCallOf, BalanceOf, TallyOf, @@ -52,22 +52,19 @@ pub type ReferendumInfoOf = ReferendumInfo< pub type ReferendumStatusOf = ReferendumStatus< TrackIdOf, PalletsOriginOf, - ::BlockNumber, + BlockNumberFor, BoundedCallOf, BalanceOf, TallyOf, ::AccountId, ScheduleAddressOf, >; -pub type DecidingStatusOf = DecidingStatus<::BlockNumber>; -pub type TrackInfoOf = - TrackInfo, ::BlockNumber>; -pub type TrackIdOf = <>::Tracks as TracksInfo< - BalanceOf, - ::BlockNumber, ->>::Id; +pub type DecidingStatusOf = DecidingStatus>; +pub type TrackInfoOf = TrackInfo, BlockNumberFor>; +pub type TrackIdOf = + <>::Tracks as TracksInfo, BlockNumberFor>>::Id; pub type ScheduleAddressOf = <>::Scheduler as Anon< - ::BlockNumber, + BlockNumberFor, CallOf, PalletsOriginOf, >>::Address; diff --git a/frame/remark/src/mock.rs b/frame/remark/src/mock.rs index 569c383928189..e597a1ca4dfe8 100644 --- a/frame/remark/src/mock.rs +++ b/frame/remark/src/mock.rs @@ -21,22 +21,17 @@ use crate as pallet_remark; use frame_support::traits::{ConstU16, ConstU32, ConstU64}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; pub type Block = frame_system::mocking::MockBlock; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Remark: pallet_remark::{ Pallet, Call, Event }, } ); @@ -47,13 +42,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); diff --git a/frame/root-offences/src/mock.rs b/frame/root-offences/src/mock.rs index 65fd788e05f25..92d188f49fb92 100644 --- a/frame/root-offences/src/mock.rs +++ b/frame/root-offences/src/mock.rs @@ -21,19 +21,19 @@ use crate as root_offences; use frame_election_provider_support::{onchain, SequentialPhragmen}; use frame_support::{ parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild, Hooks, OneSessionHandler}, + traits::{ConstU32, ConstU64, Hooks, OneSessionHandler}, }; use pallet_staking::StakerStatus; use sp_core::H256; use sp_runtime::{ curve::PiecewiseLinear, - testing::{Header, UintAuthorityId}, + testing::UintAuthorityId, traits::{BlakeTwo256, IdentityLookup, Zero}, + BuildStorage, }; use sp_staking::{EraIndex, SessionIndex}; use sp_std::collections::btree_map::BTreeMap; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type AccountId = u64; type Balance = u64; @@ -43,12 +43,9 @@ pub const INIT_TIMESTAMP: u64 = 30_000; pub const BLOCK_TIME: u64 = 1000; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Staking: pallet_staking::{Pallet, Call, Config, Storage, Event}, @@ -90,14 +87,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -244,7 +240,7 @@ impl Default for ExtBuilder { impl ExtBuilder { fn build(self) -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![ diff --git a/frame/salary/src/lib.rs b/frame/salary/src/lib.rs index 1279a30717752..53dd7224909a8 100644 --- a/frame/salary/src/lib.rs +++ b/frame/salary/src/lib.rs @@ -126,14 +126,14 @@ pub mod pallet { /// The number of blocks between sequential payout cycles is the sum of this and /// `PayoutPeriod`. #[pallet::constant] - type RegistrationPeriod: Get; + type RegistrationPeriod: Get>; /// The number of blocks within a cycle which accounts have to claim the payout. /// /// The number of blocks between sequential payout cycles is the sum of this and /// `RegistrationPeriod`. #[pallet::constant] - type PayoutPeriod: Get; + type PayoutPeriod: Get>; /// The total budget per cycle. /// @@ -142,11 +142,10 @@ pub mod pallet { type Budget: Get>; } - pub type CycleIndexOf = ::BlockNumber; + pub type CycleIndexOf = BlockNumberFor; pub type BalanceOf = <>::Paymaster as Pay>::Balance; pub type IdOf = <>::Paymaster as Pay>::Id; - pub type StatusOf = - StatusType, ::BlockNumber, BalanceOf>; + pub type StatusOf = StatusType, BlockNumberFor, BalanceOf>; pub type ClaimantStatusOf = ClaimantStatus, BalanceOf, IdOf>; /// The overall status of the system. @@ -389,7 +388,7 @@ pub mod pallet { pub fn last_active(who: &T::AccountId) -> Result, DispatchError> { Ok(Claimant::::get(&who).ok_or(Error::::NotInducted)?.last_active) } - pub fn cycle_period() -> T::BlockNumber { + pub fn cycle_period() -> BlockNumberFor { T::RegistrationPeriod::get() + T::PayoutPeriod::get() } fn do_payout(who: T::AccountId, beneficiary: T::AccountId) -> DispatchResult { diff --git a/frame/salary/src/tests.rs b/frame/salary/src/tests.rs index 7bad2cf77ace5..034dce24b8b38 100644 --- a/frame/salary/src/tests.rs +++ b/frame/salary/src/tests.rs @@ -27,25 +27,20 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, Identity, IdentityLookup}, - DispatchResult, + BuildStorage, DispatchResult, }; use sp_std::cell::RefCell; use super::*; use crate as pallet_salary; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Salary: pallet_salary::{Pallet, Call, Storage, Event}, } ); @@ -60,14 +55,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -187,7 +181,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext diff --git a/frame/scheduler/src/benchmarking.rs b/frame/scheduler/src/benchmarking.rs index d56e007ec9a2a..b41cea449654c 100644 --- a/frame/scheduler/src/benchmarking.rs +++ b/frame/scheduler/src/benchmarking.rs @@ -23,7 +23,7 @@ use frame_support::{ ensure, traits::{schedule::Priority, BoundedInline}, }; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use sp_std::{prelude::*, vec}; use crate::Pallet as Scheduler; @@ -42,7 +42,10 @@ type SystemOrigin = ::RuntimeOrigin; /// - `None`: aborted (hash without preimage) /// - `Some(true)`: hash resolves into call if possible, plain call otherwise /// - `Some(false)`: plain call -fn fill_schedule(when: T::BlockNumber, n: u32) -> Result<(), &'static str> { +fn fill_schedule( + when: frame_system::pallet_prelude::BlockNumberFor, + n: u32, +) -> Result<(), &'static str> { let t = DispatchTime::At(when); let origin: ::PalletsOrigin = frame_system::RawOrigin::Root.into(); for i in 0..n { @@ -125,7 +128,7 @@ fn make_origin(signed: bool) -> ::PalletsOrigin { benchmarks! { // `service_agendas` when no work is done. service_agendas_base { - let now = T::BlockNumber::from(BLOCK_NUMBER); + let now = BlockNumberFor::::from(BLOCK_NUMBER); IncompleteSince::::put(now - One::one()); }: { Scheduler::::service_agendas(&mut WeightMeter::max_limit(), now, 0); @@ -224,7 +227,7 @@ benchmarks! { schedule { let s in 0 .. (T::MaxScheduledPerBlock::get() - 1); let when = BLOCK_NUMBER.into(); - let periodic = Some((T::BlockNumber::one(), 100)); + let periodic = Some((BlockNumberFor::::one(), 100)); let priority = 0; // Essentially a no-op call. let call = Box::new(SystemCall::set_storage { items: vec![] }.into()); @@ -267,7 +270,7 @@ benchmarks! { let s in 0 .. (T::MaxScheduledPerBlock::get() - 1); let id = u32_to_name(s); let when = BLOCK_NUMBER.into(); - let periodic = Some((T::BlockNumber::one(), 100)); + let periodic = Some((BlockNumberFor::::one(), 100)); let priority = 0; // Essentially a no-op call. let call = Box::new(SystemCall::set_storage { items: vec![] }.into()); diff --git a/frame/scheduler/src/lib.rs b/frame/scheduler/src/lib.rs index 8194f286c8323..4e12e0332f422 100644 --- a/frame/scheduler/src/lib.rs +++ b/frame/scheduler/src/lib.rs @@ -72,7 +72,10 @@ use frame_support::{ }, weights::{Weight, WeightMeter}, }; -use frame_system::{self as system}; +use frame_system::{ + pallet_prelude::BlockNumberFor, + {self as system}, +}; use scale_info::TypeInfo; use sp_io::hashing::blake2_256; use sp_runtime::{ @@ -123,7 +126,7 @@ use crate::{Scheduled as ScheduledV3, Scheduled as ScheduledV2}; pub type ScheduledV2Of = ScheduledV2< Vec, ::RuntimeCall, - ::BlockNumber, + BlockNumberFor, ::PalletsOrigin, ::AccountId, >; @@ -131,7 +134,7 @@ pub type ScheduledV2Of = ScheduledV2< pub type ScheduledV3Of = ScheduledV3< Vec, CallOrHashOf, - ::BlockNumber, + BlockNumberFor, ::PalletsOrigin, ::AccountId, >; @@ -139,7 +142,7 @@ pub type ScheduledV3Of = ScheduledV3< pub type ScheduledOf = Scheduled< TaskName, Bounded<::RuntimeCall>, - ::BlockNumber, + BlockNumberFor, ::PalletsOrigin, ::AccountId, >; @@ -231,14 +234,14 @@ pub mod pallet { } #[pallet::storage] - pub type IncompleteSince = StorageValue<_, T::BlockNumber>; + pub type IncompleteSince = StorageValue<_, BlockNumberFor>; /// Items to be executed, indexed by the block number that they should be executed on. #[pallet::storage] pub type Agenda = StorageMap< _, Twox64Concat, - T::BlockNumber, + BlockNumberFor, BoundedVec>, T::MaxScheduledPerBlock>, ValueQuery, >; @@ -249,28 +252,28 @@ pub mod pallet { /// identities. #[pallet::storage] pub(crate) type Lookup = - StorageMap<_, Twox64Concat, TaskName, TaskAddress>; + StorageMap<_, Twox64Concat, TaskName, TaskAddress>>; /// Events type. #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// Scheduled some task. - Scheduled { when: T::BlockNumber, index: u32 }, + Scheduled { when: BlockNumberFor, index: u32 }, /// Canceled some task. - Canceled { when: T::BlockNumber, index: u32 }, + Canceled { when: BlockNumberFor, index: u32 }, /// Dispatched some task. Dispatched { - task: TaskAddress, + task: TaskAddress>, id: Option, result: DispatchResult, }, /// The call for the provided hash was not found so the task has been aborted. - CallUnavailable { task: TaskAddress, id: Option }, + CallUnavailable { task: TaskAddress>, id: Option }, /// The given task was unable to be renewed since the agenda is full at that block. - PeriodicFailed { task: TaskAddress, id: Option }, + PeriodicFailed { task: TaskAddress>, id: Option }, /// The given task can never be executed since it is overweight. - PermanentlyOverweight { task: TaskAddress, id: Option }, + PermanentlyOverweight { task: TaskAddress>, id: Option }, } #[pallet::error] @@ -290,7 +293,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { /// Execute the scheduled calls - fn on_initialize(now: T::BlockNumber) -> Weight { + fn on_initialize(now: BlockNumberFor) -> Weight { let mut weight_counter = WeightMeter::from_limit(T::MaximumWeight::get()); Self::service_agendas(&mut weight_counter, now, u32::max_value()); weight_counter.consumed @@ -304,8 +307,8 @@ pub mod pallet { #[pallet::weight(::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))] pub fn schedule( origin: OriginFor, - when: T::BlockNumber, - maybe_periodic: Option>, + when: BlockNumberFor, + maybe_periodic: Option>>, priority: schedule::Priority, call: Box<::RuntimeCall>, ) -> DispatchResult { @@ -324,7 +327,7 @@ pub mod pallet { /// Cancel an anonymously scheduled task. #[pallet::call_index(1)] #[pallet::weight(::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))] - pub fn cancel(origin: OriginFor, when: T::BlockNumber, index: u32) -> DispatchResult { + pub fn cancel(origin: OriginFor, when: BlockNumberFor, index: u32) -> DispatchResult { T::ScheduleOrigin::ensure_origin(origin.clone())?; let origin = ::RuntimeOrigin::from(origin); Self::do_cancel(Some(origin.caller().clone()), (when, index))?; @@ -337,8 +340,8 @@ pub mod pallet { pub fn schedule_named( origin: OriginFor, id: TaskName, - when: T::BlockNumber, - maybe_periodic: Option>, + when: BlockNumberFor, + maybe_periodic: Option>>, priority: schedule::Priority, call: Box<::RuntimeCall>, ) -> DispatchResult { @@ -370,8 +373,8 @@ pub mod pallet { #[pallet::weight(::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))] pub fn schedule_after( origin: OriginFor, - after: T::BlockNumber, - maybe_periodic: Option>, + after: BlockNumberFor, + maybe_periodic: Option>>, priority: schedule::Priority, call: Box<::RuntimeCall>, ) -> DispatchResult { @@ -393,8 +396,8 @@ pub mod pallet { pub fn schedule_named_after( origin: OriginFor, id: TaskName, - after: T::BlockNumber, - maybe_periodic: Option>, + after: BlockNumberFor, + maybe_periodic: Option>>, priority: schedule::Priority, call: Box<::RuntimeCall>, ) -> DispatchResult { @@ -434,7 +437,7 @@ impl> Pallet { } Agenda::::translate::< - Vec::RuntimeCall, T::BlockNumber>>>, + Vec::RuntimeCall, BlockNumberFor>>>, _, >(|_, agenda| { Some(BoundedVec::truncate_from( @@ -669,7 +672,7 @@ impl Pallet { Scheduled< TaskName, Bounded<::RuntimeCall>, - T::BlockNumber, + BlockNumberFor, OldOrigin, T::AccountId, >, @@ -695,7 +698,9 @@ impl Pallet { }); } - fn resolve_time(when: DispatchTime) -> Result { + fn resolve_time( + when: DispatchTime>, + ) -> Result, DispatchError> { let now = frame_system::Pallet::::block_number(); let when = match when { @@ -713,9 +718,9 @@ impl Pallet { } fn place_task( - when: T::BlockNumber, + when: BlockNumberFor, what: ScheduledOf, - ) -> Result, (DispatchError, ScheduledOf)> { + ) -> Result>, (DispatchError, ScheduledOf)> { let maybe_name = what.maybe_id; let index = Self::push_to_agenda(when, what)?; let address = (when, index); @@ -727,7 +732,7 @@ impl Pallet { } fn push_to_agenda( - when: T::BlockNumber, + when: BlockNumberFor, what: ScheduledOf, ) -> Result)> { let mut agenda = Agenda::::get(when); @@ -749,7 +754,7 @@ impl Pallet { /// Remove trailing `None` items of an agenda at `when`. If all items are `None` remove the /// agenda record entirely. - fn cleanup_agenda(when: T::BlockNumber) { + fn cleanup_agenda(when: BlockNumberFor) { let mut agenda = Agenda::::get(when); match agenda.iter().rposition(|i| i.is_some()) { Some(i) if agenda.len() > i + 1 => { @@ -764,12 +769,12 @@ impl Pallet { } fn do_schedule( - when: DispatchTime, - maybe_periodic: Option>, + when: DispatchTime>, + maybe_periodic: Option>>, priority: schedule::Priority, origin: T::PalletsOrigin, call: Bounded<::RuntimeCall>, - ) -> Result, DispatchError> { + ) -> Result>, DispatchError> { let when = Self::resolve_time(when)?; let lookup_hash = call.lookup_hash(); @@ -799,7 +804,7 @@ impl Pallet { fn do_cancel( origin: Option, - (when, index): TaskAddress, + (when, index): TaskAddress>, ) -> Result<(), DispatchError> { let scheduled = Agenda::::try_mutate(when, |agenda| { agenda.get_mut(index as usize).map_or( @@ -831,9 +836,9 @@ impl Pallet { } fn do_reschedule( - (when, index): TaskAddress, - new_time: DispatchTime, - ) -> Result, DispatchError> { + (when, index): TaskAddress>, + new_time: DispatchTime>, + ) -> Result>, DispatchError> { let new_time = Self::resolve_time(new_time)?; if new_time == when { @@ -853,12 +858,12 @@ impl Pallet { fn do_schedule_named( id: TaskName, - when: DispatchTime, - maybe_periodic: Option>, + when: DispatchTime>, + maybe_periodic: Option>>, priority: schedule::Priority, origin: T::PalletsOrigin, call: Bounded<::RuntimeCall>, - ) -> Result, DispatchError> { + ) -> Result>, DispatchError> { // ensure id it is unique if Lookup::::contains_key(&id) { return Err(Error::::FailedToSchedule.into()) @@ -922,8 +927,8 @@ impl Pallet { fn do_reschedule_named( id: TaskName, - new_time: DispatchTime, - ) -> Result, DispatchError> { + new_time: DispatchTime>, + ) -> Result>, DispatchError> { let new_time = Self::resolve_time(new_time)?; let lookup = Lookup::::get(id); @@ -953,7 +958,7 @@ use ServiceTaskError::*; impl Pallet { /// Service up to `max` agendas queue starting from earliest incompletely executed agenda. - fn service_agendas(weight: &mut WeightMeter, now: T::BlockNumber, max: u32) { + fn service_agendas(weight: &mut WeightMeter, now: BlockNumberFor, max: u32) { if !weight.check_accrue(T::WeightInfo::service_agendas_base()) { return } @@ -983,8 +988,8 @@ impl Pallet { fn service_agenda( weight: &mut WeightMeter, executed: &mut u32, - now: T::BlockNumber, - when: T::BlockNumber, + now: BlockNumberFor, + when: BlockNumberFor, max: u32, ) -> bool { let mut agenda = Agenda::::get(when); @@ -1052,8 +1057,8 @@ impl Pallet { /// - Rescheduling the task for execution in a later agenda if periodic. fn service_task( weight: &mut WeightMeter, - now: T::BlockNumber, - when: T::BlockNumber, + now: BlockNumberFor, + when: BlockNumberFor, agenda_index: u32, is_first: bool, mut task: ScheduledOf, @@ -1161,14 +1166,14 @@ impl Pallet { } impl> - schedule::v2::Anon::RuntimeCall, T::PalletsOrigin> for Pallet + schedule::v2::Anon, ::RuntimeCall, T::PalletsOrigin> for Pallet { - type Address = TaskAddress; + type Address = TaskAddress>; type Hash = T::Hash; fn schedule( - when: DispatchTime, - maybe_periodic: Option>, + when: DispatchTime>, + maybe_periodic: Option>>, priority: schedule::Priority, origin: T::PalletsOrigin, call: CallOrHashOf, @@ -1184,26 +1189,26 @@ impl> fn reschedule( address: Self::Address, - when: DispatchTime, + when: DispatchTime>, ) -> Result { Self::do_reschedule(address, when) } - fn next_dispatch_time((when, index): Self::Address) -> Result { + fn next_dispatch_time((when, index): Self::Address) -> Result, ()> { Agenda::::get(when).get(index as usize).ok_or(()).map(|_| when) } } impl> - schedule::v2::Named::RuntimeCall, T::PalletsOrigin> for Pallet + schedule::v2::Named, ::RuntimeCall, T::PalletsOrigin> for Pallet { - type Address = TaskAddress; + type Address = TaskAddress>; type Hash = T::Hash; fn schedule_named( id: Vec, - when: DispatchTime, - maybe_periodic: Option>, + when: DispatchTime>, + maybe_periodic: Option>>, priority: schedule::Priority, origin: T::PalletsOrigin, call: CallOrHashOf, @@ -1221,13 +1226,13 @@ impl> fn reschedule_named( id: Vec, - when: DispatchTime, + when: DispatchTime>, ) -> Result { let name = blake2_256(&id[..]); Self::do_reschedule_named(name, when) } - fn next_dispatch_time(id: Vec) -> Result { + fn next_dispatch_time(id: Vec) -> Result, ()> { let name = blake2_256(&id[..]); Lookup::::get(name) .and_then(|(when, index)| Agenda::::get(when).get(index as usize).map(|_| when)) @@ -1235,14 +1240,14 @@ impl> } } -impl schedule::v3::Anon::RuntimeCall, T::PalletsOrigin> +impl schedule::v3::Anon, ::RuntimeCall, T::PalletsOrigin> for Pallet { - type Address = TaskAddress; + type Address = TaskAddress>; fn schedule( - when: DispatchTime, - maybe_periodic: Option>, + when: DispatchTime>, + maybe_periodic: Option>>, priority: schedule::Priority, origin: T::PalletsOrigin, call: Bounded<::RuntimeCall>, @@ -1256,12 +1261,14 @@ impl schedule::v3::Anon::RuntimeCall, T fn reschedule( address: Self::Address, - when: DispatchTime, + when: DispatchTime>, ) -> Result { Self::do_reschedule(address, when).map_err(map_err_to_v3_err::) } - fn next_dispatch_time((when, index): Self::Address) -> Result { + fn next_dispatch_time( + (when, index): Self::Address, + ) -> Result, DispatchError> { Agenda::::get(when) .get(index as usize) .ok_or(DispatchError::Unavailable) @@ -1271,15 +1278,15 @@ impl schedule::v3::Anon::RuntimeCall, T use schedule::v3::TaskName; -impl schedule::v3::Named::RuntimeCall, T::PalletsOrigin> +impl schedule::v3::Named, ::RuntimeCall, T::PalletsOrigin> for Pallet { - type Address = TaskAddress; + type Address = TaskAddress>; fn schedule_named( id: TaskName, - when: DispatchTime, - maybe_periodic: Option>, + when: DispatchTime>, + maybe_periodic: Option>>, priority: schedule::Priority, origin: T::PalletsOrigin, call: Bounded<::RuntimeCall>, @@ -1293,12 +1300,12 @@ impl schedule::v3::Named::RuntimeCall, fn reschedule_named( id: TaskName, - when: DispatchTime, + when: DispatchTime>, ) -> Result { Self::do_reschedule_named(id, when).map_err(map_err_to_v3_err::) } - fn next_dispatch_time(id: TaskName) -> Result { + fn next_dispatch_time(id: TaskName) -> Result, DispatchError> { Lookup::::get(id) .and_then(|(when, index)| Agenda::::get(when).get(index as usize).map(|_| when)) .ok_or(DispatchError::Unavailable) diff --git a/frame/scheduler/src/migration.rs b/frame/scheduler/src/migration.rs index 78313fda66412..06259768f0aa1 100644 --- a/frame/scheduler/src/migration.rs +++ b/frame/scheduler/src/migration.rs @@ -19,6 +19,7 @@ use super::*; use frame_support::traits::OnRuntimeUpgrade; +use frame_system::pallet_prelude::BlockNumberFor; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; @@ -34,22 +35,14 @@ pub mod v1 { pub(crate) type Agenda = StorageMap< Pallet, Twox64Concat, - ::BlockNumber, - Vec< - Option< - ScheduledV1<::RuntimeCall, ::BlockNumber>, - >, - >, + BlockNumberFor, + Vec::RuntimeCall, BlockNumberFor>>>, ValueQuery, >; #[frame_support::storage_alias] - pub(crate) type Lookup = StorageMap< - Pallet, - Twox64Concat, - Vec, - TaskAddress<::BlockNumber>, - >; + pub(crate) type Lookup = + StorageMap, Twox64Concat, Vec, TaskAddress>>; } pub mod v2 { @@ -60,18 +53,14 @@ pub mod v2 { pub(crate) type Agenda = StorageMap< Pallet, Twox64Concat, - ::BlockNumber, + BlockNumberFor, Vec>>, ValueQuery, >; #[frame_support::storage_alias] - pub(crate) type Lookup = StorageMap< - Pallet, - Twox64Concat, - Vec, - TaskAddress<::BlockNumber>, - >; + pub(crate) type Lookup = + StorageMap, Twox64Concat, Vec, TaskAddress>>; } pub mod v3 { @@ -82,18 +71,14 @@ pub mod v3 { pub(crate) type Agenda = StorageMap< Pallet, Twox64Concat, - ::BlockNumber, + BlockNumberFor, Vec>>, ValueQuery, >; #[frame_support::storage_alias] - pub(crate) type Lookup = StorageMap< - Pallet, - Twox64Concat, - Vec, - TaskAddress<::BlockNumber>, - >; + pub(crate) type Lookup = + StorageMap, Twox64Concat, Vec, TaskAddress>>; /// Migrate the scheduler pallet from V3 to V4. pub struct MigrateToV4(sp_std::marker::PhantomData); diff --git a/frame/scheduler/src/mock.rs b/frame/scheduler/src/mock.rs index 1b0fb8112469c..28e334958d924 100644 --- a/frame/scheduler/src/mock.rs +++ b/frame/scheduler/src/mock.rs @@ -30,9 +30,8 @@ use frame_support::{ use frame_system::{EnsureRoot, EnsureSignedBy}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, - Perbill, + BuildStorage, Perbill, }; // Logger module to track execution. @@ -93,16 +92,12 @@ pub mod logger { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Logger: logger::{Pallet, Call, Event}, Scheduler: scheduler::{Pallet, Call, Storage, Event}, Preimage: pallet_preimage::{Pallet, Call, Storage, Event}, @@ -130,13 +125,12 @@ impl system::Config for Test { type DbWeight = RocksDbWeight; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -225,7 +219,7 @@ impl Config for Test { pub type LoggerCall = logger::Call; pub fn new_test_ext() -> sp_io::TestExternalities { - let t = system::GenesisConfig::default().build_storage::().unwrap(); + let t = system::GenesisConfig::::default().build_storage().unwrap(); t.into() } diff --git a/frame/scored-pool/src/lib.rs b/frame/scored-pool/src/lib.rs index f8fc0fecd492a..2bf70cbc574c8 100644 --- a/frame/scored-pool/src/lib.rs +++ b/frame/scored-pool/src/lib.rs @@ -170,7 +170,7 @@ pub mod pallet { /// Every `Period` blocks the `Members` are filled with the highest scoring /// members in the `Pool`. #[pallet::constant] - type Period: Get; + type Period: Get>; /// The receiver of the signal for when the membership has been initialized. /// This happens pre-genesis and will usually be the same as `MembershipChanged`. @@ -256,7 +256,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { let mut pool = self.pool.clone(); @@ -282,7 +282,7 @@ pub mod pallet { impl, I: 'static> Hooks> for Pallet { /// Every `Period` blocks the `Members` set is refreshed from the /// highest scoring members in the pool. - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: frame_system::pallet_prelude::BlockNumberFor) -> Weight { if n % T::Period::get() == Zero::zero() { let pool = >::get(); >::refresh_members(pool, ChangeReceiver::MembershipChanged); diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index 83bc939e8230d..d8c6ef9b0f444 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -22,25 +22,21 @@ use crate as pallet_scored_pool; use frame_support::{ bounded_vec, construct_runtime, ord_parameter_types, parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild}, + traits::{ConstU32, ConstU64}, }; use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, ScoredPool: pallet_scored_pool::{Pallet, Call, Storage, Config, Event}, } @@ -60,14 +56,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -140,7 +135,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut balances = vec![]; for i in 1..31 { balances.push((i, 500_000)); diff --git a/frame/session/benchmarking/src/lib.rs b/frame/session/benchmarking/src/lib.rs index a7e326fb27ac3..f27136e820d41 100644 --- a/frame/session/benchmarking/src/lib.rs +++ b/frame/session/benchmarking/src/lib.rs @@ -31,7 +31,7 @@ use frame_support::{ codec::Decode, traits::{Get, KeyOwnerProofSystem, OnInitialize}, }; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use pallet_session::{historical::Pallet as Historical, Pallet as Session, *}; use pallet_staking::{ benchmarking::create_validator_with_nominators, testing_utils::create_validators, @@ -46,8 +46,8 @@ pub trait Config: { } -impl OnInitialize for Pallet { - fn on_initialize(n: T::BlockNumber) -> frame_support::weights::Weight { +impl OnInitialize> for Pallet { + fn on_initialize(n: BlockNumberFor) -> frame_support::weights::Weight { pallet_session::Pallet::::on_initialize(n) } } @@ -156,7 +156,7 @@ fn check_membership_proof_setup( Session::::set_keys(RawOrigin::Signed(controller).into(), keys, proof).unwrap(); } - Pallet::::on_initialize(T::BlockNumber::one()); + Pallet::::on_initialize(frame_system::pallet_prelude::BlockNumberFor::::one()); // skip sessions until the new validator set is enacted while Session::::validators().len() < n as usize { diff --git a/frame/session/benchmarking/src/mock.rs b/frame/session/benchmarking/src/mock.rs index d4866a46079af..dbbd437bbd938 100644 --- a/frame/session/benchmarking/src/mock.rs +++ b/frame/session/benchmarking/src/mock.rs @@ -24,23 +24,18 @@ use frame_support::{ parameter_types, traits::{ConstU32, ConstU64}, }; -use sp_runtime::traits::IdentityLookup; +use sp_runtime::{traits::IdentityLookup, BuildStorage}; type AccountId = u64; -type AccountIndex = u32; -type BlockNumber = u64; +type Nonce = u32; type Balance = u64; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Staking: pallet_staking::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, @@ -53,14 +48,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; - type BlockNumber = BlockNumber; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); @@ -192,6 +186,6 @@ impl pallet_staking::Config for Test { impl crate::Config for Test {} pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); sp_io::TestExternalities::new(t) } diff --git a/frame/session/src/historical/mod.rs b/frame/session/src/historical/mod.rs index f00a1c95e763e..04129e4eba130 100644 --- a/frame/session/src/historical/mod.rs +++ b/frame/session/src/historical/mod.rs @@ -377,17 +377,17 @@ pub(crate) mod tests { force_new_session, set_next_validators, NextValidators, Session, System, Test, }; - use sp_runtime::{key_types::DUMMY, testing::UintAuthorityId}; + use sp_runtime::{key_types::DUMMY, testing::UintAuthorityId, BuildStorage}; use frame_support::{ - traits::{GenesisBuild, KeyOwnerProofSystem, OnInitialize}, + traits::{KeyOwnerProofSystem, OnInitialize}, BasicExternalities, }; type Historical = Pallet; pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let keys: Vec<_> = NextValidators::get() .iter() .cloned() diff --git a/frame/session/src/historical/offchain.rs b/frame/session/src/historical/offchain.rs index 4185788cbbed0..c44eea2f374c0 100644 --- a/frame/session/src/historical/offchain.rs +++ b/frame/session/src/historical/offchain.rs @@ -149,18 +149,18 @@ mod tests { crypto::key_types::DUMMY, offchain::{testing::TestOffchainExt, OffchainDbExt, OffchainWorkerExt, StorageKind}, }; - use sp_runtime::testing::UintAuthorityId; + use sp_runtime::{testing::UintAuthorityId, BuildStorage}; use frame_support::{ - traits::{GenesisBuild, KeyOwnerProofSystem, OnInitialize}, + traits::{KeyOwnerProofSystem, OnInitialize}, BasicExternalities, }; type Historical = Pallet; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default() - .build_storage::() + let mut t = frame_system::GenesisConfig::::default() + .build_storage() .expect("Failed to create test externalities."); let keys: Vec<_> = NextValidators::get() diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index 1219aaaf12a10..d2b1c2b744674 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -126,6 +126,7 @@ use frame_support::{ weights::Weight, Parameter, }; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::{ traits::{AtLeast32BitUnsigned, Convert, Member, One, OpaqueKeys, Zero}, ConsensusEngineId, KeyTypeId, Permill, RuntimeAppPublic, @@ -393,12 +394,12 @@ pub mod pallet { type ValidatorIdOf: Convert>; /// Indicator for when to end the session. - type ShouldEndSession: ShouldEndSession; + type ShouldEndSession: ShouldEndSession>; /// Something that can predict the next session rotation. This should typically come from /// the same logical unit that provides [`ShouldEndSession`], yet, it gives a best effort /// estimate. It is helpful to implement [`EstimateNextNewSession`]. - type NextSessionRotation: EstimateNextSessionRotation; + type NextSessionRotation: EstimateNextSessionRotation>; /// Handler for managing new session. type SessionManager: SessionManager; @@ -420,7 +421,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { if T::SessionHandler::KEY_TYPE_IDS.len() != T::Keys::key_ids().len() { panic!("Number of keys in session handler and session keys does not match"); @@ -559,7 +560,7 @@ pub mod pallet { impl Hooks> for Pallet { /// Called when a block is initialized. Will rotate session if it is the last /// block of the current session. - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { if T::ShouldEndSession::should_end_session(n) { Self::rotate_session(); T::BlockWeights::get().max_block @@ -901,14 +902,14 @@ impl ValidatorSet for Pallet { } } -impl EstimateNextNewSession for Pallet { - fn average_session_length() -> T::BlockNumber { +impl EstimateNextNewSession> for Pallet { + fn average_session_length() -> BlockNumberFor { T::NextSessionRotation::average_session_length() } /// This session pallet always calls new_session and next_session at the same time, hence we /// do a simple proxy and pass the function to next rotation. - fn estimate_next_new_session(now: T::BlockNumber) -> (Option, Weight) { + fn estimate_next_new_session(now: BlockNumberFor) -> (Option>, Weight) { T::NextSessionRotation::estimate_next_session_rotation(now) } } diff --git a/frame/session/src/mock.rs b/frame/session/src/mock.rs index d6b8d9e207e02..b45ebfd25c44a 100644 --- a/frame/session/src/mock.rs +++ b/frame/session/src/mock.rs @@ -27,14 +27,15 @@ use std::collections::BTreeMap; use sp_core::{crypto::key_types::DUMMY, H256}; use sp_runtime::{ impl_opaque_keys, - testing::{Header, UintAuthorityId}, + testing::UintAuthorityId, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use sp_staking::SessionIndex; use frame_support::{ parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild}, + traits::{ConstU32, ConstU64}, BasicExternalities, }; @@ -75,17 +76,13 @@ impl OpaqueKeys for PreUpgradeMockSessionKeys { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; #[cfg(feature = "historical")] frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, Historical: pallet_session_historical::{Pallet}, } @@ -93,12 +90,9 @@ frame_support::construct_runtime!( #[cfg(not(feature = "historical"))] frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, } ); @@ -215,7 +209,7 @@ pub fn reset_before_session_end_called() { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let keys: Vec<_> = NextValidators::get() .iter() .cloned() @@ -244,14 +238,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/society/src/benchmarking.rs b/frame/society/src/benchmarking.rs index f9cd378b97d3d..20af6e35ada52 100644 --- a/frame/society/src/benchmarking.rs +++ b/frame/society/src/benchmarking.rs @@ -370,7 +370,10 @@ benchmarks_instance_pallet! { impl_benchmark_test_suite!( Society, - sp_io::TestExternalities::from(frame_system::GenesisConfig::default().build_storage::().unwrap()), + sp_io::TestExternalities::from( + as sp_runtime::BuildStorage>::build_storage( + &frame_system::GenesisConfig::default()).unwrap() + ), crate::mock::Test ); } diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 6f42ae00f287d..57e3afdcb65e8 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -416,10 +416,8 @@ impl BidKind { } } -pub type PayoutsFor = BoundedVec< - (::BlockNumber, BalanceOf), - >::MaxPayouts, ->; +pub type PayoutsFor = + BoundedVec<(BlockNumberFor, BalanceOf), >::MaxPayouts>; /// Information concerning a member. #[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] @@ -439,10 +437,7 @@ pub struct PayoutRecord { pub type PayoutRecordFor = PayoutRecord< BalanceOf, - BoundedVec< - (::BlockNumber, BalanceOf), - >::MaxPayouts, - >, + BoundedVec<(BlockNumberFor, BalanceOf), >::MaxPayouts>, >; /// Record for an individual new member who was elevated from a candidate recently. @@ -491,7 +486,7 @@ pub mod pallet { type Currency: ReservableCurrency; /// Something that provides randomness in the runtime. - type Randomness: Randomness; + type Randomness: Randomness>; /// The maximum number of strikes before a member gets funds slashed. #[pallet::constant] @@ -504,23 +499,23 @@ pub mod pallet { /// The number of blocks on which new candidates should be voted on. Together with /// `ClaimPeriod`, this sums to the number of blocks between candidate intake periods. #[pallet::constant] - type VotingPeriod: Get; + type VotingPeriod: Get>; /// The number of blocks on which new candidates can claim their membership and be the /// named head. #[pallet::constant] - type ClaimPeriod: Get; + type ClaimPeriod: Get>; /// The maximum duration of the payout lock. #[pallet::constant] - type MaxLockDuration: Get; + type MaxLockDuration: Get>; /// The origin that is allowed to call `found`. type FounderSetOrigin: EnsureOrigin; /// The number of blocks between membership challenges. #[pallet::constant] - type ChallengePeriod: Get; + type ChallengePeriod: Get>; /// The maximum number of payouts a member may have waiting unclaimed. #[pallet::constant] @@ -758,7 +753,7 @@ pub mod pallet { #[pallet::hooks] impl, I: 'static> Hooks> for Pallet { - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { let mut weight = Weight::zero(); let weights = T::BlockWeights::get(); @@ -798,7 +793,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { Pot::::put(self.pot); } @@ -1409,7 +1404,7 @@ pub enum Period { impl, I: 'static> Pallet { /// Get the period we are currently in. - fn period() -> Period { + fn period() -> Period> { let claim_period = T::ClaimPeriod::get(); let voting_period = T::VotingPeriod::get(); let rotation_period = voting_period + claim_period; @@ -1902,7 +1897,7 @@ impl, I: 'static> Pallet { candidate: &T::AccountId, value: BalanceOf, kind: BidKind>, - maturity: T::BlockNumber, + maturity: BlockNumberFor, ) { let value = match kind { BidKind::Deposit(deposit) => { @@ -1939,7 +1934,7 @@ impl, I: 'static> Pallet { /// /// It is the caller's duty to ensure that `who` is already a member. This does nothing if `who` /// is not a member or if `value` is zero. - fn bump_payout(who: &T::AccountId, when: T::BlockNumber, value: BalanceOf) { + fn bump_payout(who: &T::AccountId, when: BlockNumberFor, value: BalanceOf) { if value.is_zero() { return } @@ -2022,7 +2017,7 @@ impl, I: 'static> Pallet { /// /// This is a rather opaque calculation based on the formula here: /// https://www.desmos.com/calculator/9itkal1tce - fn lock_duration(x: u32) -> T::BlockNumber { + fn lock_duration(x: u32) -> BlockNumberFor { let lock_pc = 100 - 50_000 / (x + 500); Percent::from_percent(lock_pc as u8) * T::MaxLockDuration::get() } diff --git a/frame/society/src/migrations.rs b/frame/society/src/migrations.rs index bd590f9b18770..4a4215fe3988b 100644 --- a/frame/society/src/migrations.rs +++ b/frame/society/src/migrations.rs @@ -161,7 +161,7 @@ pub(crate) mod old { Pallet, Twox64Concat, ::AccountId, - Vec<(::BlockNumber, BalanceOf)>, + Vec<(frame_system::pallet_prelude::BlockNumberFor, BalanceOf)>, ValueQuery, >; #[storage_alias] diff --git a/frame/society/src/mock.rs b/frame/society/src/mock.rs index ed04aa181e161..a318c2e794b7a 100644 --- a/frame/society/src/mock.rs +++ b/frame/society/src/mock.rs @@ -28,22 +28,18 @@ use frame_support_test::TestRandomness; use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use RuntimeOrigin as Origin; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Society: pallet_society::{Pallet, Call, Storage, Event, Config}, } @@ -68,14 +64,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u128; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -150,7 +145,7 @@ impl EnvBuilder { } pub fn execute R>(mut self, f: F) -> R { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); self.balances.push((Society::account_id(), self.balance.max(self.pot))); pallet_balances::GenesisConfig:: { balances: self.balances } .assimilate_storage(&mut t) diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 19529ca08735d..232b37de7c1b8 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -22,8 +22,8 @@ use frame_election_provider_support::{onchain, SequentialPhragmen, VoteWeight}; use frame_support::{ assert_ok, ord_parameter_types, parameter_types, traits::{ - ConstU32, ConstU64, Currency, EitherOfDiverse, FindAuthor, GenesisBuild, Get, Hooks, - Imbalance, OnUnbalanced, OneSessionHandler, + ConstU32, ConstU64, Currency, EitherOfDiverse, FindAuthor, Get, Hooks, Imbalance, + OnUnbalanced, OneSessionHandler, }, weights::constants::RocksDbWeight, }; @@ -32,8 +32,9 @@ use sp_core::H256; use sp_io; use sp_runtime::{ curve::PiecewiseLinear, - testing::{Header, UintAuthorityId}, + testing::UintAuthorityId, traits::{IdentityLookup, Zero}, + BuildStorage, }; use sp_staking::offence::{DisableStrategy, OffenceDetails, OnOffenceHandler}; @@ -42,7 +43,7 @@ pub const BLOCK_TIME: u64 = 1000; /// The AccountId alias in this test module. pub(crate) type AccountId = u64; -pub(crate) type AccountIndex = u64; +pub(crate) type Nonce = u64; pub(crate) type BlockNumber = u64; pub(crate) type Balance = u128; @@ -82,14 +83,10 @@ pub fn is_disabled(controller: AccountId) -> bool { Session::disabled_validators().contains(&validator_index) } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Authorship: pallet_authorship, @@ -127,14 +124,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = RocksDbWeight; type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; - type BlockNumber = BlockNumber; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU64<250>; type Version = (); @@ -429,7 +425,7 @@ impl ExtBuilder { } fn build(self) -> sp_io::TestExternalities { sp_tracing::try_init_simple(); - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); let _ = pallet_balances::GenesisConfig:: { balances: vec![ diff --git a/frame/staking/src/pallet/impls.rs b/frame/staking/src/pallet/impls.rs index 5166608a97aab..f2aa48e3316da 100644 --- a/frame/staking/src/pallet/impls.rs +++ b/frame/staking/src/pallet/impls.rs @@ -1022,7 +1022,7 @@ impl ElectionDataProvider for Pallet { Ok(Self::get_npos_targets(None)) } - fn next_election_prediction(now: T::BlockNumber) -> T::BlockNumber { + fn next_election_prediction(now: BlockNumberFor) -> BlockNumberFor { let current_era = Self::current_era().unwrap_or(0); let current_session = Self::current_planned_session(); let current_era_start_session_index = @@ -1039,7 +1039,7 @@ impl ElectionDataProvider for Pallet { let session_length = T::NextNewSession::average_session_length(); - let sessions_left: T::BlockNumber = match ForceEra::::get() { + let sessions_left: BlockNumberFor = match ForceEra::::get() { Forcing::ForceNone => Bounded::max_value(), Forcing::ForceNew | Forcing::ForceAlways => Zero::zero(), Forcing::NotForcing if era_progress >= T::SessionsPerEra::get() => Zero::zero(), @@ -1238,7 +1238,7 @@ impl historical::SessionManager pallet_authorship::EventHandler for Pallet +impl pallet_authorship::EventHandler> for Pallet where T: Config + pallet_authorship::Config + pallet_session::Config, { diff --git a/frame/staking/src/pallet/mod.rs b/frame/staking/src/pallet/mod.rs index 0163d6543f2ab..dfca6fec3a8f5 100644 --- a/frame/staking/src/pallet/mod.rs +++ b/frame/staking/src/pallet/mod.rs @@ -87,7 +87,7 @@ pub mod pallet { /// The staking balance. type Currency: LockableCurrency< Self::AccountId, - Moment = Self::BlockNumber, + Moment = BlockNumberFor, Balance = Self::CurrencyBalance, >; /// Just the `Currency::Balance` type; we have this item to allow us to constrain it to @@ -118,14 +118,14 @@ pub mod pallet { /// Something that provides the election functionality. type ElectionProvider: ElectionProvider< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, // we only accept an election provider that has staking as data provider. DataProvider = Pallet, >; /// Something that provides the election functionality at genesis. type GenesisElectionProvider: ElectionProvider< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, DataProvider = Pallet, >; @@ -200,7 +200,7 @@ pub mod pallet { /// Something that can estimate the next session change, accurately or as a best effort /// guess. - type NextNewSession: EstimateNextNewSession; + type NextNewSession: EstimateNextNewSession>; /// The maximum number of nominators rewarded for each validator. /// @@ -598,7 +598,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { ValidatorCount::::put(self.validator_count); MinimumValidatorCount::::put(self.minimum_validator_count); diff --git a/frame/state-trie-migration/src/lib.rs b/frame/state-trie-migration/src/lib.rs index 05ca21c1de752..4bbabef1dd4bd 100644 --- a/frame/state-trie-migration/src/lib.rs +++ b/frame/state-trie-migration/src/lib.rs @@ -1062,20 +1062,16 @@ mod mock { }; use sp_runtime::{ traits::{BlakeTwo256, Header as _, IdentityLookup}, - StorageChild, + BuildStorage, StorageChild, }; - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; - type Block = frame_system::mocking::MockBlock; + type Block = frame_system::mocking::MockBlockU32; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Config, Storage, Event}, StateTrieMigration: pallet_state_trie_migration::{Pallet, Call, Storage, Event}, } @@ -1091,13 +1087,12 @@ mod mock { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u32; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = sp_runtime::generic::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU32<250>; type DbWeight = (); @@ -1241,8 +1236,8 @@ mod mock { }; if with_pallets { - frame_system::GenesisConfig::default() - .assimilate_storage::(&mut custom_storage) + frame_system::GenesisConfig::::default() + .assimilate_storage(&mut custom_storage) .unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 1000)] } .assimilate_storage(&mut custom_storage) @@ -1619,7 +1614,7 @@ pub(crate) mod remote_tests { traits::{Get, Hooks}, weights::Weight, }; - use frame_system::Pallet as System; + use frame_system::{pallet_prelude::BlockNumberFor, Pallet as System}; use remote_externalities::Mode; use sp_core::H256; use sp_runtime::{ @@ -1630,7 +1625,7 @@ pub(crate) mod remote_tests { #[allow(dead_code)] fn run_to_block>( - n: ::BlockNumber, + n: BlockNumberFor, ) -> (H256, Weight) { let mut root = Default::default(); let mut weight_sum = Weight::zero(); @@ -1670,7 +1665,7 @@ pub(crate) mod remote_tests { frame_system::Pallet::::block_number() }); - let mut duration: ::BlockNumber = Zero::zero(); + let mut duration: BlockNumberFor = Zero::zero(); // set the version to 1, as if the upgrade happened. ext.state_version = sp_core::storage::StateVersion::V1; diff --git a/frame/statement/src/mock.rs b/frame/statement/src/mock.rs index 8b9e7a1a7d965..79d2aa7d891d5 100644 --- a/frame/statement/src/mock.rs +++ b/frame/statement/src/mock.rs @@ -27,12 +27,10 @@ use frame_support::{ }; use sp_core::{Pair, H256}; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, - AccountId32, + AccountId32, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; pub const MIN_ALLOWED_STATEMENTS: u32 = 4; @@ -41,10 +39,7 @@ pub const MIN_ALLOWED_BYTES: u32 = 1024; pub const MAX_ALLOWED_BYTES: u32 = 4096; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances, @@ -59,13 +54,12 @@ impl frame_system::Config for Test { type DbWeight = RocksDbWeight; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId32; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -111,7 +105,7 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let balances = pallet_balances::GenesisConfig:: { balances: vec![ (sp_core::sr25519::Pair::from_string("//Alice", None).unwrap().public().into(), 6000), diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index a41e479b6154d..f735469558c70 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -289,7 +289,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { if let Some(ref key) = self.key { Key::::put(key); diff --git a/frame/sudo/src/mock.rs b/frame/sudo/src/mock.rs index 856cb35c8718c..9e78e474f4e5a 100644 --- a/frame/sudo/src/mock.rs +++ b/frame/sudo/src/mock.rs @@ -19,12 +19,12 @@ use super::*; use crate as sudo; -use frame_support::traits::{ConstU32, ConstU64, Contains, GenesisBuild}; +use frame_support::traits::{ConstU32, ConstU64, Contains}; use sp_core::H256; use sp_io; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; // Logger module to track execution. @@ -90,16 +90,12 @@ pub mod logger { pub(super) type I32Log = StorageValue<_, BoundedVec>, ValueQuery>; } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Sudo: sudo::{Pallet, Call, Config, Storage, Event}, Logger: logger::{Pallet, Call, Storage, Event}, } @@ -119,13 +115,12 @@ impl frame_system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -157,7 +152,7 @@ pub type LoggerCall = logger::Call; // Build test environment by setting the root `key` for the Genesis. pub fn new_test_ext(root_key: u64) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); sudo::GenesisConfig:: { key: Some(root_key) } .assimilate_storage(&mut t) .unwrap(); @@ -166,5 +161,5 @@ pub fn new_test_ext(root_key: u64) -> sp_io::TestExternalities { #[cfg(feature = "runtime-benchmarks")] pub fn new_bench_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::::default().build_storage().unwrap().into() } diff --git a/frame/support/procedural/src/construct_runtime/expand/config.rs b/frame/support/procedural/src/construct_runtime/expand/config.rs index 32b8a32a4fe6a..440e856221a36 100644 --- a/frame/support/procedural/src/construct_runtime/expand/config.rs +++ b/frame/support/procedural/src/construct_runtime/expand/config.rs @@ -29,7 +29,7 @@ pub fn expand_outer_config( ) -> TokenStream { let mut types = TokenStream::new(); let mut fields = TokenStream::new(); - let mut build_storage_calls = TokenStream::new(); + let mut genesis_build_calls = TokenStream::new(); let mut query_genesis_config_part_macros = Vec::new(); for decl in pallet_decls { @@ -52,8 +52,8 @@ pub fn expand_outer_config( types.extend(expand_config_types(attr, runtime, decl, &config, part_is_generic)); fields.extend(quote!(#attr pub #field_name: #config,)); - build_storage_calls - .extend(expand_config_build_storage_call(scrate, attr, runtime, decl, field_name)); + genesis_build_calls + .extend(expand_config_build_storage_call(scrate, &config, attr, field_name)); query_genesis_config_part_macros.push(quote! { #path::__substrate_genesis_config_check::is_genesis_config_defined!(#pallet_name); #[cfg(feature = "std")] @@ -67,9 +67,7 @@ pub fn expand_outer_config( #types - #[cfg(any(feature = "std", test))] use #scrate::serde as __genesis_config_serde_import__; - #[cfg(any(feature = "std", test))] #[derive(#scrate::serde::Serialize, #scrate::serde::Deserialize, Default)] #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] @@ -88,13 +86,17 @@ pub fn expand_outer_config( &self, storage: &mut #scrate::sp_runtime::Storage, ) -> std::result::Result<(), String> { - #build_storage_calls - #scrate::BasicExternalities::execute_with_storage(storage, || { - ::on_genesis(); - }); + ::build(&self); + Ok(()) + }) + } + } - Ok(()) + impl #scrate::traits::BuildGenesisConfig for RuntimeGenesisConfig { + fn build(&self) { + #genesis_build_calls + ::on_genesis(); } } } @@ -112,17 +114,14 @@ fn expand_config_types( match (decl.instance.as_ref(), part_is_generic) { (Some(inst), true) => quote! { #attr - #[cfg(any(feature = "std", test))] pub type #config = #path::GenesisConfig<#runtime, #path::#inst>; }, (None, true) => quote! { #attr - #[cfg(any(feature = "std", test))] pub type #config = #path::GenesisConfig<#runtime>; }, (_, false) => quote! { #attr - #[cfg(any(feature = "std", test))] pub type #config = #path::GenesisConfig; }, } @@ -130,21 +129,12 @@ fn expand_config_types( fn expand_config_build_storage_call( scrate: &TokenStream, + pallet_genesis_config: &Ident, attr: &TokenStream, - runtime: &Ident, - decl: &Pallet, field_name: &Ident, ) -> TokenStream { - let path = &decl.path; - let instance = if let Some(inst) = decl.instance.as_ref() { - quote!(#path::#inst) - } else { - quote!(#path::__InherentHiddenInstance) - }; - quote! { #attr - #scrate::sp_runtime::BuildModuleGenesisStorage:: - <#runtime, #instance>::build_module_genesis_storage(&self.#field_name, storage)?; + <#pallet_genesis_config as #scrate::traits::BuildGenesisConfig>::build(&self.#field_name); } } diff --git a/frame/support/procedural/src/construct_runtime/expand/inherent.rs b/frame/support/procedural/src/construct_runtime/expand/inherent.rs index 8218f3746e2c3..1dc51d9cd2bc4 100644 --- a/frame/support/procedural/src/construct_runtime/expand/inherent.rs +++ b/frame/support/procedural/src/construct_runtime/expand/inherent.rs @@ -19,12 +19,12 @@ use crate::construct_runtime::Pallet; use proc_macro2::TokenStream; use quote::quote; use std::str::FromStr; -use syn::{Ident, TypePath}; +use syn::Ident; pub fn expand_outer_inherent( runtime: &Ident, - block: &TypePath, - unchecked_extrinsic: &TypePath, + block: &TokenStream, + unchecked_extrinsic: &TokenStream, pallet_decls: &[Pallet], scrate: &TokenStream, ) -> TokenStream { diff --git a/frame/support/procedural/src/construct_runtime/expand/metadata.rs b/frame/support/procedural/src/construct_runtime/expand/metadata.rs index 3f88d8c6d1353..0975fedb35d5b 100644 --- a/frame/support/procedural/src/construct_runtime/expand/metadata.rs +++ b/frame/support/procedural/src/construct_runtime/expand/metadata.rs @@ -19,13 +19,13 @@ use crate::construct_runtime::{parse::PalletPath, Pallet}; use proc_macro2::TokenStream; use quote::quote; use std::str::FromStr; -use syn::{Ident, TypePath}; +use syn::Ident; pub fn expand_runtime_metadata( runtime: &Ident, pallet_declarations: &[Pallet], scrate: &TokenStream, - extrinsic: &TypePath, + extrinsic: &TokenStream, system_path: &PalletPath, ) -> TokenStream { let pallets = pallet_declarations diff --git a/frame/support/procedural/src/construct_runtime/mod.rs b/frame/support/procedural/src/construct_runtime/mod.rs index 203d43ab3cc39..efc2244154479 100644 --- a/frame/support/procedural/src/construct_runtime/mod.rs +++ b/frame/support/procedural/src/construct_runtime/mod.rs @@ -216,10 +216,7 @@ use frame_support_procedural_tools::{ generate_crate_access, generate_crate_access_2018, generate_hidden_includes, }; use itertools::Itertools; -use parse::{ - ExplicitRuntimeDeclaration, ImplicitRuntimeDeclaration, Pallet, RuntimeDeclaration, - WhereSection, -}; +use parse::{ExplicitRuntimeDeclaration, ImplicitRuntimeDeclaration, Pallet, RuntimeDeclaration}; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::quote; @@ -337,19 +334,14 @@ fn construct_runtime_explicit_to_explicit_expanded( fn construct_runtime_final_expansion( definition: ExplicitRuntimeDeclaration, ) -> Result { - let ExplicitRuntimeDeclaration { - name, - where_section: WhereSection { block, node_block, unchecked_extrinsic }, - pallets, - pallets_token, - } = definition; + let ExplicitRuntimeDeclaration { name, pallets, pallets_token, where_section } = definition; let system_pallet = pallets.iter().find(|decl| decl.name == SYSTEM_PALLET_NAME).ok_or_else(|| { syn::Error::new( pallets_token.span.join(), "`System` pallet declaration is missing. \ - Please add this line: `System: frame_system::{Pallet, Call, Storage, Config, Event},`", + Please add this line: `System: frame_system::{Pallet, Call, Storage, Config, Event},`", ) })?; if !system_pallet.cfg_pattern.is_empty() { @@ -379,6 +371,10 @@ fn construct_runtime_final_expansion( let scrate = generate_crate_access(hidden_crate_name, "frame-support"); let scrate_decl = generate_hidden_includes(hidden_crate_name, "frame-support"); + let frame_system = generate_crate_access_2018("frame-system")?; + let block = quote!(<#name as #frame_system::Config>::Block); + let unchecked_extrinsic = quote!(<#block as #scrate::sp_runtime::traits::Block>::Extrinsic); + let outer_event = expand::expand_outer_enum(&name, &pallets, &scrate, expand::OuterEnumType::Event)?; let outer_error = @@ -407,7 +403,21 @@ fn construct_runtime_final_expansion( let integrity_test = decl_integrity_test(&scrate); let static_assertions = decl_static_assertions(&name, &pallets, &scrate); + let warning = + where_section.map_or(None, |where_section| { + Some(proc_macro_warning::Warning::new_deprecated("WhereSection") + .old("use a `where` clause in `construct_runtime`") + .new("use `frame_system::Config` to set the `Block` type and delete this clause. + It is planned to be removed in December 2023") + .help_links(&["https://github.com/paritytech/substrate/pull/14437"]) + .span(where_section.span) + .build(), + ) + }); + let res = quote!( + #warning + #scrate_decl // Prevent UncheckedExtrinsic to print unused warning. @@ -421,9 +431,6 @@ fn construct_runtime_final_expansion( #scrate::scale_info::TypeInfo )] pub struct #name; - impl #scrate::sp_runtime::traits::GetNodeBlockType for #name { - type NodeBlock = #node_block; - } impl #scrate::sp_runtime::traits::GetRuntimeBlockType for #name { type RuntimeBlock = #block; } diff --git a/frame/support/procedural/src/construct_runtime/parse.rs b/frame/support/procedural/src/construct_runtime/parse.rs index b731bb0c83e27..9b08e16469754 100644 --- a/frame/support/procedural/src/construct_runtime/parse.rs +++ b/frame/support/procedural/src/construct_runtime/parse.rs @@ -65,7 +65,7 @@ pub enum RuntimeDeclaration { #[derive(Debug)] pub struct ImplicitRuntimeDeclaration { pub name: Ident, - pub where_section: WhereSection, + pub where_section: Option, pub pallets: Vec, } @@ -73,7 +73,7 @@ pub struct ImplicitRuntimeDeclaration { #[derive(Debug)] pub struct ExplicitRuntimeDeclaration { pub name: Ident, - pub where_section: WhereSection, + pub where_section: Option, pub pallets: Vec, pub pallets_token: token::Brace, } @@ -90,7 +90,7 @@ impl Parse for RuntimeDeclaration { } let name = input.parse::()?; - let where_section = input.parse()?; + let where_section = if input.peek(token::Where) { Some(input.parse()?) } else { None }; let pallets = input.parse::>>()?; let pallets_token = pallets.token; @@ -122,6 +122,7 @@ impl Parse for RuntimeDeclaration { #[derive(Debug)] pub struct WhereSection { + pub span: Span, pub block: syn::TypePath, pub node_block: syn::TypePath, pub unchecked_extrinsic: syn::TypePath, @@ -130,6 +131,7 @@ pub struct WhereSection { impl Parse for WhereSection { fn parse(input: ParseStream) -> Result { input.parse::()?; + let mut definitions = Vec::new(); while !input.peek(token::Brace) { let definition: WhereDefinition = input.parse()?; @@ -153,7 +155,7 @@ impl Parse for WhereSection { ); return Err(Error::new(*kind_span, msg)) } - Ok(Self { block, node_block, unchecked_extrinsic }) + Ok(Self { span: input.span(), block, node_block, unchecked_extrinsic }) } } diff --git a/frame/support/procedural/src/lib.rs b/frame/support/procedural/src/lib.rs index 15b11a1c9698e..a0f2c995514a5 100644 --- a/frame/support/procedural/src/lib.rs +++ b/frame/support/procedural/src/lib.rs @@ -856,7 +856,7 @@ pub fn storage_alias(_: TokenStream, input: TokenStream) -> TokenStream { /// type RuntimeOrigin = RuntimeOrigin; /// type OnSetCode = (); /// type PalletInfo = PalletInfo; -/// type Header = Header; +/// type Block = Block; /// // We decide to override this one. /// type AccountData = pallet_balances::AccountData; /// } @@ -873,7 +873,7 @@ pub fn storage_alias(_: TokenStream, input: TokenStream) -> TokenStream { /// type BlockWeights = (); /// type BlockLength = (); /// type DbWeight = (); -/// type Index = u64; +/// type Nonce = u64; /// type BlockNumber = u64; /// type Hash = sp_core::hash::H256; /// type Hashing = sp_runtime::traits::BlakeTwo256; @@ -902,13 +902,13 @@ pub fn storage_alias(_: TokenStream, input: TokenStream) -> TokenStream { /// type RuntimeOrigin = RuntimeOrigin; /// type OnSetCode = (); /// type PalletInfo = PalletInfo; -/// type Header = Header; +/// type Block = Block; /// type AccountData = pallet_balances::AccountData; /// type Version = ::Version; /// type BlockWeights = ::BlockWeights; /// type BlockLength = ::BlockLength; /// type DbWeight = ::DbWeight; -/// type Index = ::Index; +/// type Nonce = ::Nonce; /// type BlockNumber = ::BlockNumber; /// type Hash = ::Hash; /// type Hashing = ::Hashing; @@ -1559,7 +1559,7 @@ pub fn unbounded(_: TokenStream, _: TokenStream) -> TokenStream { /// ```ignore /// #[pallet::storage] /// #[pallet::whitelist_storage] -/// pub(super) type Number = StorageValue<_, T::BlockNumber, ValueQuery>; +/// pub(super) type Number = StorageValue<_, frame_system::pallet_prelude::BlockNumberFor::, ValueQuery>; /// ``` /// /// NOTE: As with all `pallet::*` attributes, this one _must_ be written as @@ -1651,8 +1651,7 @@ pub fn genesis_config(_: TokenStream, _: TokenStream) -> TokenStream { /// The macro will add the following attribute: /// * `#[cfg(feature = "std")]` /// -/// The macro will implement `sp_runtime::BuildModuleGenesisStorage` using `()` as a second -/// generic for non-instantiable pallets. +/// The macro will implement `sp_runtime::BuildStorage`. #[proc_macro_attribute] pub fn genesis_build(_: TokenStream, _: TokenStream) -> TokenStream { pallet_macro_stub() diff --git a/frame/support/procedural/src/pallet/expand/genesis_build.rs b/frame/support/procedural/src/pallet/expand/genesis_build.rs index 1c8fb40f1f96e..f54d308fce304 100644 --- a/frame/support/procedural/src/pallet/expand/genesis_build.rs +++ b/frame/support/procedural/src/pallet/expand/genesis_build.rs @@ -18,7 +18,7 @@ use crate::pallet::Def; /// -/// * implement the trait `sp_runtime::BuildModuleGenesisStorage` +/// * implement the trait `sp_runtime::BuildStorage` pub fn expand_genesis_build(def: &mut Def) -> proc_macro2::TokenStream { let genesis_config = if let Some(genesis_config) = &def.genesis_config { genesis_config @@ -28,34 +28,22 @@ pub fn expand_genesis_build(def: &mut Def) -> proc_macro2::TokenStream { let genesis_build = def.genesis_build.as_ref().expect("Checked by def parser"); let frame_support = &def.frame_support; - let type_impl_gen = &def.type_impl_generics(genesis_build.attr_span); - let type_use_gen = &def.type_use_generics(genesis_build.attr_span); - let trait_use_gen = if def.config.has_instance { - quote::quote_spanned!(genesis_build.attr_span => T, I) - } else { - // `__InherentHiddenInstance` used by construct_runtime here is alias for `()` - quote::quote_spanned!(genesis_build.attr_span => T, ()) - }; + let type_impl_gen = &genesis_config.gen_kind.type_impl_gen(genesis_build.attr_span); let gen_cfg_ident = &genesis_config.genesis_config; - - let gen_cfg_use_gen = genesis_config.gen_kind.type_use_gen(genesis_build.attr_span); + let gen_cfg_use_gen = &genesis_config.gen_kind.type_use_gen(genesis_build.attr_span); let where_clause = &genesis_build.where_clause; quote::quote_spanned!(genesis_build.attr_span => #[cfg(feature = "std")] - impl<#type_impl_gen> #frame_support::sp_runtime::BuildModuleGenesisStorage<#trait_use_gen> - for #gen_cfg_ident<#gen_cfg_use_gen> #where_clause - { - fn build_module_genesis_storage( - &self, - storage: &mut #frame_support::sp_runtime::Storage, - ) -> std::result::Result<(), std::string::String> { - #frame_support::BasicExternalities::execute_with_storage(storage, || { - >::build(self); - Ok(()) - }) + impl<#type_impl_gen> #frame_support::sp_runtime::BuildStorage for #gen_cfg_ident<#gen_cfg_use_gen> #where_clause + { + fn assimilate_storage(&self, storage: &mut sp_runtime::Storage) -> std::result::Result<(), std::string::String> { + #frame_support::BasicExternalities::execute_with_storage(storage, || { + self.build(); + Ok(()) + }) + } } - } ) } diff --git a/frame/support/procedural/src/pallet/expand/hooks.rs b/frame/support/procedural/src/pallet/expand/hooks.rs index ef22f5a3af5be..76e1fe76116b2 100644 --- a/frame/support/procedural/src/pallet/expand/hooks.rs +++ b/frame/support/procedural/src/pallet/expand/hooks.rs @@ -75,7 +75,7 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { let frame_system = &def.frame_system; quote::quote! { impl<#type_impl_gen> - #frame_support::traits::Hooks<::BlockNumber> + #frame_support::traits::Hooks<#frame_system::pallet_prelude::BlockNumberFor::> for #pallet_ident<#type_use_gen> #where_clause {} } } else { @@ -137,50 +137,50 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { #hooks_impl impl<#type_impl_gen> - #frame_support::traits::OnFinalize<::BlockNumber> + #frame_support::traits::OnFinalize<#frame_system::pallet_prelude::BlockNumberFor::> for #pallet_ident<#type_use_gen> #where_clause { - fn on_finalize(n: ::BlockNumber) { + fn on_finalize(n: #frame_system::pallet_prelude::BlockNumberFor::) { #frame_support::sp_tracing::enter_span!( #frame_support::sp_tracing::trace_span!("on_finalize") ); < Self as #frame_support::traits::Hooks< - ::BlockNumber + #frame_system::pallet_prelude::BlockNumberFor:: > >::on_finalize(n) } } impl<#type_impl_gen> - #frame_support::traits::OnIdle<::BlockNumber> + #frame_support::traits::OnIdle<#frame_system::pallet_prelude::BlockNumberFor::> for #pallet_ident<#type_use_gen> #where_clause { fn on_idle( - n: ::BlockNumber, + n: #frame_system::pallet_prelude::BlockNumberFor::, remaining_weight: #frame_support::weights::Weight ) -> #frame_support::weights::Weight { < Self as #frame_support::traits::Hooks< - ::BlockNumber + #frame_system::pallet_prelude::BlockNumberFor:: > >::on_idle(n, remaining_weight) } } impl<#type_impl_gen> - #frame_support::traits::OnInitialize<::BlockNumber> + #frame_support::traits::OnInitialize<#frame_system::pallet_prelude::BlockNumberFor::> for #pallet_ident<#type_use_gen> #where_clause { fn on_initialize( - n: ::BlockNumber + n: #frame_system::pallet_prelude::BlockNumberFor:: ) -> #frame_support::weights::Weight { #frame_support::sp_tracing::enter_span!( #frame_support::sp_tracing::trace_span!("on_initialize") ); < Self as #frame_support::traits::Hooks< - ::BlockNumber + #frame_system::pallet_prelude::BlockNumberFor:: > >::on_initialize(n) } @@ -205,7 +205,7 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { < Self as #frame_support::traits::Hooks< - ::BlockNumber + #frame_system::pallet_prelude::BlockNumberFor:: > >::on_runtime_upgrade() } @@ -215,7 +215,7 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { < Self as - #frame_support::traits::Hooks<::BlockNumber> + #frame_support::traits::Hooks<#frame_system::pallet_prelude::BlockNumberFor::> >::pre_upgrade() } @@ -226,19 +226,19 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { < Self as - #frame_support::traits::Hooks<::BlockNumber> + #frame_support::traits::Hooks<#frame_system::pallet_prelude::BlockNumberFor::> >::post_upgrade(state) } } impl<#type_impl_gen> - #frame_support::traits::OffchainWorker<::BlockNumber> + #frame_support::traits::OffchainWorker<#frame_system::pallet_prelude::BlockNumberFor::> for #pallet_ident<#type_use_gen> #where_clause { - fn offchain_worker(n: ::BlockNumber) { + fn offchain_worker(n: #frame_system::pallet_prelude::BlockNumberFor::) { < Self as #frame_support::traits::Hooks< - ::BlockNumber + #frame_system::pallet_prelude::BlockNumberFor:: > >::offchain_worker(n) } @@ -253,7 +253,7 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { fn integrity_test() { < Self as #frame_support::traits::Hooks< - ::BlockNumber + #frame_system::pallet_prelude::BlockNumberFor:: > >::integrity_test() } @@ -262,17 +262,17 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { #[cfg(feature = "try-runtime")] impl<#type_impl_gen> - #frame_support::traits::TryState<::BlockNumber> + #frame_support::traits::TryState<#frame_system::pallet_prelude::BlockNumberFor::> for #pallet_ident<#type_use_gen> #where_clause { fn try_state( - n: ::BlockNumber, + n: #frame_system::pallet_prelude::BlockNumberFor::, _s: #frame_support::traits::TryStateSelect ) -> Result<(), #frame_support::sp_runtime::TryRuntimeError> { #log_try_state < Self as #frame_support::traits::Hooks< - ::BlockNumber + #frame_system::pallet_prelude::BlockNumberFor:: > >::try_state(n) } diff --git a/frame/support/procedural/src/pallet/parse/genesis_build.rs b/frame/support/procedural/src/pallet/parse/genesis_build.rs index 6d356b2ee3844..d0e1d9ec998ec 100644 --- a/frame/support/procedural/src/pallet/parse/genesis_build.rs +++ b/frame/support/procedural/src/pallet/parse/genesis_build.rs @@ -23,7 +23,7 @@ pub struct GenesisBuildDef { /// The index of item in pallet module. pub index: usize, /// A set of usage of instance, must be check for consistency with trait. - pub instances: Vec, + pub instances: Option>, /// The where_clause used. pub where_clause: Option, /// The span of the pallet::genesis_build attribute. @@ -53,7 +53,8 @@ impl GenesisBuildDef { })? .1; - let instances = vec![helper::check_genesis_builder_usage(item_trait)?]; + let instances = + helper::check_genesis_builder_usage(item_trait)?.map(|instances| vec![instances]); Ok(Self { attr_span, index, instances, where_clause: item.generics.where_clause.clone() }) } diff --git a/frame/support/procedural/src/pallet/parse/helper.rs b/frame/support/procedural/src/pallet/parse/helper.rs index 9319248771642..1e6e83d7eeba7 100644 --- a/frame/support/procedural/src/pallet/parse/helper.rs +++ b/frame/support/procedural/src/pallet/parse/helper.rs @@ -23,6 +23,7 @@ mod keyword { syn::custom_keyword!(I); syn::custom_keyword!(compact); syn::custom_keyword!(GenesisBuild); + syn::custom_keyword!(BuildGenesisConfig); syn::custom_keyword!(Config); syn::custom_keyword!(T); syn::custom_keyword!(Pallet); @@ -488,26 +489,32 @@ pub fn check_type_def_gen( /// Check the syntax: /// * either `GenesisBuild` /// * or `GenesisBuild` +/// * or `BuildGenesisConfig` /// -/// return the instance if found. -pub fn check_genesis_builder_usage(type_: &syn::Path) -> syn::Result { +/// return the instance if found for `GenesisBuild` +/// return None for BuildGenesisConfig +pub fn check_genesis_builder_usage(type_: &syn::Path) -> syn::Result> { let expected = "expected `GenesisBuild` or `GenesisBuild`"; - pub struct Checker(InstanceUsage); + pub struct Checker(Option); impl syn::parse::Parse for Checker { fn parse(input: syn::parse::ParseStream) -> syn::Result { let mut instance_usage = InstanceUsage { span: input.span(), has_instance: false }; - input.parse::()?; - input.parse::()?; - input.parse::()?; - if input.peek(syn::Token![,]) { - instance_usage.has_instance = true; - input.parse::()?; - input.parse::()?; + if input.peek(keyword::GenesisBuild) { + input.parse::()?; + input.parse::()?; + input.parse::()?; + if input.peek(syn::Token![,]) { + instance_usage.has_instance = true; + input.parse::()?; + input.parse::()?; + } + input.parse::]>()?; + return Ok(Self(Some(instance_usage))) + } else { + input.parse::()?; + return Ok(Self(None)) } - input.parse::]>()?; - - Ok(Self(instance_usage)) } } diff --git a/frame/support/procedural/src/pallet/parse/mod.rs b/frame/support/procedural/src/pallet/parse/mod.rs index 4a4602964a996..0f5e5f1136610 100644 --- a/frame/support/procedural/src/pallet/parse/mod.rs +++ b/frame/support/procedural/src/pallet/parse/mod.rs @@ -268,7 +268,7 @@ impl Def { instances.extend_from_slice(&genesis_config.instances[..]); } if let Some(genesis_build) = &self.genesis_build { - instances.extend_from_slice(&genesis_build.instances[..]); + genesis_build.instances.as_ref().map(|i| instances.extend_from_slice(&i)); } if let Some(extra_constants) = &self.extra_constants { instances.extend_from_slice(&extra_constants.instances[..]); diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 9981e5ad65b78..7dfac19c9407d 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -645,259 +645,6 @@ impl PaysFee for (u64, Pays) { // END TODO /// Declares a `Module` struct and a `Call` enum, which implements the dispatch logic. -/// -/// ## Declaration -/// -/// ``` -/// # #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::dispatch; -/// # use frame_system::{Config, ensure_signed}; -/// decl_module! { -/// pub struct Module for enum Call where origin: T::RuntimeOrigin { -/// -/// // Private functions are dispatchable, but not available to other -/// // FRAME pallets. -/// #[weight = 0] -/// fn my_function(origin, var: u64) -> dispatch::DispatchResult { -/// // Your implementation -/// Ok(()) -/// } -/// -/// // Public functions are both dispatchable and available to other -/// // FRAME pallets. -/// #[weight = 0] -/// pub fn my_public_function(origin) -> dispatch::DispatchResult { -/// // Your implementation -/// Ok(()) -/// } -/// } -/// } -/// # fn main() {} -/// ``` -/// -/// The declaration is set with the header where: -/// -/// * `Module`: The struct generated by the macro, with type `Config`. -/// * `Call`: The enum generated for every pallet, which implements -/// [`Callable`](./dispatch/trait.Callable.html). -/// * `origin`: Alias of `T::RuntimeOrigin`. -/// * `Result`: The expected return type from pallet functions. -/// -/// The first parameter of dispatchable functions must always be `origin`. -/// -/// ### Shorthand Example -/// -/// The macro automatically expands a shorthand function declaration to return the -/// [`DispatchResult`] type. These functions are the same: -/// -/// ``` -/// # #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::dispatch; -/// # use frame_system::{Config, ensure_signed}; -/// decl_module! { -/// pub struct Module for enum Call where origin: T::RuntimeOrigin { -/// #[weight = 0] -/// fn my_long_function(origin) -> dispatch::DispatchResult { -/// // Your implementation -/// Ok(()) -/// } -/// -/// #[weight = 0] -/// fn my_short_function(origin) { -/// // Your implementation -/// } -/// } -/// } -/// # fn main() {} -/// ``` -/// -/// ### Consuming only portions of the annotated static weight -/// -/// Per default a callable function consumes all of its static weight as declared via -/// the #\[weight\] attribute. However, there are use cases where only a portion of this -/// weight should be consumed. In that case the static weight is charged pre dispatch and -/// the difference is refunded post dispatch. -/// -/// In order to make use of this feature the function must return `DispatchResultWithPostInfo` -/// in place of the default `DispatchResult`. Then the actually consumed weight can be returned. -/// To consume a non default weight while returning an error -/// [`WithPostDispatchInfo::with_weight`](./weight/trait.WithPostDispatchInfo.html) can be used -/// to augment any error with custom weight information. -/// -/// ``` -/// # #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::{weights::Weight, dispatch::{DispatchResultWithPostInfo, WithPostDispatchInfo, PostDispatchInfo}}; -/// # use frame_system::{Config, ensure_signed}; -/// decl_module! { -/// pub struct Module for enum Call where origin: T::RuntimeOrigin { -/// #[weight = 1_000_000] -/// fn my_long_function(origin, do_expensive_calc: bool) -> DispatchResultWithPostInfo { -/// ensure_signed(origin).map_err(|e| e.with_weight(Weight::from_parts(100_000, 0)))?; -/// if do_expensive_calc { -/// // do the expensive calculation -/// // ... -/// // return None to indicate that we are using all weight (the default) -/// return Ok(None::.into()); -/// } -/// // expensive calculation not executed: use only a portion of the weight -/// Ok(PostDispatchInfo { actual_weight: Some(Weight::from_parts(100_000, 0)), ..Default::default() }) -/// } -/// } -/// } -/// # fn main() {} -/// ``` -/// -/// ### Transactional Function Example -/// -/// Transactional function discards all changes to storage if it returns `Err`, or commits if -/// `Ok`, via the #\[transactional\] attribute. Note the attribute must be after #\[weight\]. -/// The #\[transactional\] attribute is deprecated since it is the default behaviour. -/// -/// ``` -/// # #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::transactional; -/// # use frame_system::Config; -/// decl_module! { -/// pub struct Module for enum Call where origin: T::RuntimeOrigin { -/// #[weight = 0] -/// #[transactional] -/// fn my_short_function(origin) { -/// // Your implementation -/// } -/// } -/// } -/// # fn main() {} -/// ``` -/// -/// ### Privileged Function Example -/// -/// A privileged function checks that the origin of the call is `ROOT`. -/// -/// ``` -/// # #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::dispatch; -/// # use frame_system::{Config, ensure_signed, ensure_root}; -/// decl_module! { -/// pub struct Module for enum Call where origin: T::RuntimeOrigin { -/// #[weight = 0] -/// fn my_privileged_function(origin) -> dispatch::DispatchResult { -/// ensure_root(origin)?; -/// // Your implementation -/// Ok(()) -/// } -/// } -/// } -/// # fn main() {} -/// ``` -/// -/// ### Attributes on Functions -/// -/// Attributes on functions are supported, but must be in the order of: -/// 1. Optional #\[doc\] attribute. -/// 2. #\[weight\] attribute. -/// 3. Optional function attributes, for instance #\[transactional\]. Those function attributes will -/// be written only on the dispatchable functions implemented on `Module`, not on the `Call` enum -/// variant. -/// -/// ## Multiple Module Instances Example -/// -/// A Substrate module can be built such that multiple instances of the same module can be used -/// within a single runtime. For example, the [Balances module](../pallet_balances/index.html) can -/// be added multiple times to your runtime in order to support multiple, independent currencies for -/// your blockchain. Here is an example of how you would declare such a module using the -/// `decl_module!` macro: -/// -/// ``` -/// # #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::dispatch; -/// # use frame_system::ensure_signed; -/// # pub struct DefaultInstance; -/// # pub trait Instance: 'static {} -/// # impl Instance for DefaultInstance {} -/// pub trait Config: frame_system::Config {} -/// -/// decl_module! { -/// pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: T::RuntimeOrigin { -/// // Your implementation -/// } -/// } -/// # fn main() {} -/// ``` -/// -/// Note: `decl_storage` must be called to generate `Instance` trait and optionally -/// `DefaultInstance` type. -/// -/// ## Where clause -/// -/// Besides the default `origin: T::RuntimeOrigin`, you can also pass other bounds to the module -/// declaration. This where bound will be replicated to all types generated by this macro. The -/// chaining of multiple trait bounds with `+` is not supported. If multiple bounds for one type are -/// required, it needs to be split up into multiple bounds. -/// -/// ``` -/// # #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::dispatch; -/// # use frame_system::{self as system, ensure_signed}; -/// pub trait Config: system::Config where Self::AccountId: From {} -/// -/// decl_module! { -/// pub struct Module for enum Call where origin: T::RuntimeOrigin, T::AccountId: From { -/// // Your implementation -/// } -/// } -/// # fn main() {} -/// ``` -/// -/// ## Reserved Functions -/// -/// The following are reserved function signatures: -/// -/// * `deposit_event`: Helper function for depositing an [event](https://docs.substrate.io/main-docs/build/events-errors/). -/// The default behavior is to call `deposit_event` from the [System -/// module](../frame_system/index.html). However, you can write your own implementation for events -/// in your runtime. To use the default behavior, add `fn deposit_event() = default;` to your -/// `Module`. -/// -/// The following reserved functions also take the block number (with type `T::BlockNumber`) as an -/// optional input: -/// -/// * `on_runtime_upgrade`: Executes at the beginning of a block prior to on_initialize when there -/// is a runtime upgrade. This allows each module to upgrade its storage before the storage items -/// are used. As such, **calling other modules must be avoided**!! Using this function will -/// implement the [`OnRuntimeUpgrade`](../sp_runtime/traits/trait.OnRuntimeUpgrade.html) trait. -/// Function signature must be `fn on_runtime_upgrade() -> frame_support::weights::Weight`. -/// -/// * `on_initialize`: Executes at the beginning of a block. Using this function will -/// implement the [`OnInitialize`](./trait.OnInitialize.html) trait. -/// Function signature can be either: -/// * `fn on_initialize(n: BlockNumber) -> frame_support::weights::Weight` or -/// * `fn on_initialize() -> frame_support::weights::Weight` -/// -/// * `on_idle`: Executes at the end of a block. Passes a remaining weight to provide a threshold -/// for when to execute non vital functions. Using this function will implement the -/// [`OnIdle`](./traits/trait.OnIdle.html) trait. -/// Function signature is: -/// * `fn on_idle(n: BlockNumber, remaining_weight: Weight) -> frame_support::weights::Weight` -/// -/// * `on_finalize`: Executes at the end of a block. Using this function will -/// implement the [`OnFinalize`](./traits/trait.OnFinalize.html) trait. -/// Function signature can be either: -/// * `fn on_finalize(n: BlockNumber) -> frame_support::weights::Weight` or -/// * `fn on_finalize() -> frame_support::weights::Weight` -/// -/// * `offchain_worker`: Executes at the beginning of a block and produces extrinsics for a future -/// block upon completion. Using this function will implement the -/// [`OffchainWorker`](./traits/trait.OffchainWorker.html) trait. -/// * `integrity_test`: Executes in a test generated by `construct_runtime`, note it doesn't execute -/// in an externalities-provided environment. Implement -/// [`IntegrityTest`](./trait.IntegrityTest.html) trait. #[macro_export] #[deprecated(note = "Will be removed after July 2023; use the attribute `#[pallet]` macro instead. For more info, see: ")] @@ -3587,7 +3334,7 @@ mod weight_tests { #[pallet::config] #[pallet::disable_frame_system_supertrait_check] pub trait Config: 'static { - type BlockNumber: Parameter + Default + MaxEncodedLen; + type Block: Parameter + sp_runtime::traits::Block; type AccountId; type Balance; type BaseCallFilter: crate::traits::Contains; @@ -3653,6 +3400,11 @@ mod weight_tests { pub mod pallet_prelude { pub type OriginFor = ::RuntimeOrigin; + + pub type HeaderFor = + <::Block as sp_runtime::traits::HeaderProvider>::HeaderT; + + pub type BlockNumberFor = as sp_runtime::traits::Header>::Number; } } @@ -3665,10 +3417,6 @@ mod weight_tests { crate::construct_runtime!( pub enum Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, { System: self::frame_system, } @@ -3682,7 +3430,7 @@ mod weight_tests { } impl Config for Runtime { - type BlockNumber = BlockNumber; + type Block = Block; type AccountId = AccountId; type Balance = Balance; type BaseCallFilter = crate::traits::Everything; diff --git a/frame/support/src/error.rs b/frame/support/src/error.rs index 14dc16d4dd5c2..5a7dd73f481ec 100644 --- a/frame/support/src/error.rs +++ b/frame/support/src/error.rs @@ -21,51 +21,6 @@ pub use sp_runtime::traits::{BadOrigin, LookupError}; /// Declare an error type for a runtime module. -/// -/// `decl_error!` supports only variants that do not hold any data. The dispatchable -/// functions return [`DispatchResult`](sp_runtime::DispatchResult). The error type -/// implements `From for DispatchResult` to make the error type usable as error -/// in the dispatchable functions. -/// -/// It is required that the error type is registered in `decl_module!` to make the error -/// exported in the metadata. -/// -/// # Usage -/// -/// ``` -/// # use frame_support::{decl_error, decl_module}; -/// # -/// decl_error! { -/// /// Errors that can occur in my module. -/// pub enum MyError for Module { -/// /// Hey this is an error message that indicates bla. -/// MyCoolErrorMessage, -/// /// You are just not cool enough for my module! -/// YouAreNotCoolEnough, -/// } -/// } -/// -/// # use frame_system::Config; -/// -/// // You need to register the error type in `decl_module!` as well to make the error -/// // exported in the metadata. -/// -/// decl_module! { -/// pub struct Module for enum Call where origin: T::RuntimeOrigin { -/// type Error = MyError; -/// -/// #[weight = 0] -/// fn do_something(origin) -> frame_support::dispatch::DispatchResult { -/// Err(MyError::::YouAreNotCoolEnough.into()) -/// } -/// } -/// } -/// -/// # fn main() {} -/// ``` -/// -/// For instantiable modules you also need to give the instance generic type and bound to the -/// error declaration. #[macro_export] #[deprecated(note = "Will be removed after July 2023; use the attribute `#[pallet]` macro instead. For more info, see: ")] diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 2a183b00ee14a..51477ee384c79 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -834,7 +834,7 @@ pub mod tests { use sp_runtime::{generic, traits::BlakeTwo256, BuildStorage}; use sp_std::result; - pub use self::frame_system::{Config, Pallet}; + pub use self::frame_system::{pallet_prelude::*, Config, Pallet}; #[pallet] pub mod frame_system { @@ -849,7 +849,7 @@ pub mod tests { #[pallet::config] #[pallet::disable_frame_system_supertrait_check] pub trait Config: 'static { - type BlockNumber: Parameter + Default + MaxEncodedLen; + type Block: Parameter + sp_runtime::traits::Block; type AccountId; type BaseCallFilter: crate::traits::Contains; type RuntimeOrigin; @@ -879,12 +879,12 @@ pub mod tests { #[pallet::storage] #[pallet::getter(fn generic_data)] pub type GenericData = - StorageMap<_, Identity, T::BlockNumber, T::BlockNumber, ValueQuery>; + StorageMap<_, Identity, BlockNumberFor, BlockNumberFor, ValueQuery>; #[pallet::storage] #[pallet::getter(fn generic_data2)] pub type GenericData2 = - StorageMap<_, Blake2_128Concat, T::BlockNumber, T::BlockNumber, OptionQuery>; + StorageMap<_, Blake2_128Concat, BlockNumberFor, BlockNumberFor, OptionQuery>; #[pallet::storage] pub type DataDM = @@ -894,10 +894,10 @@ pub mod tests { pub type GenericDataDM = StorageDoubleMap< _, Blake2_128Concat, - T::BlockNumber, + BlockNumberFor, Identity, - T::BlockNumber, - T::BlockNumber, + BlockNumberFor, + BlockNumberFor, ValueQuery, >; @@ -905,10 +905,10 @@ pub mod tests { pub type GenericData2DM = StorageDoubleMap< _, Blake2_128Concat, - T::BlockNumber, + BlockNumberFor, Twox64Concat, - T::BlockNumber, - T::BlockNumber, + BlockNumberFor, + BlockNumberFor, OptionQuery, >; @@ -919,25 +919,31 @@ pub mod tests { Blake2_128Concat, u32, Blake2_128Concat, - T::BlockNumber, + BlockNumberFor, Vec, ValueQuery, >; #[pallet::genesis_config] - pub struct GenesisConfig { + pub struct GenesisConfig { pub data: Vec<(u32, u64)>, pub test_config: Vec<(u32, u32, u64)>, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } - impl Default for GenesisConfig { + impl Default for GenesisConfig { fn default() -> Self { - Self { data: vec![(15u32, 42u64)], test_config: vec![(15u32, 16u32, 42u64)] } + Self { + _config: Default::default(), + data: vec![(15u32, 42u64)], + test_config: vec![(15u32, 16u32, 42u64)], + } } } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { for (k, v) in &self.data { >::insert(k, v); @@ -950,6 +956,11 @@ pub mod tests { pub mod pallet_prelude { pub type OriginFor = ::RuntimeOrigin; + + pub type HeaderFor = + <::Block as sp_runtime::traits::HeaderProvider>::HeaderT; + + pub type BlockNumberFor = as sp_runtime::traits::Header>::Number; } } @@ -961,17 +972,13 @@ pub mod tests { crate::construct_runtime!( pub enum Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, { System: self::frame_system, } ); impl Config for Runtime { - type BlockNumber = BlockNumber; + type Block = Block; type AccountId = AccountId; type BaseCallFilter = crate::traits::Everything; type RuntimeOrigin = RuntimeOrigin; @@ -999,12 +1006,8 @@ pub mod tests { fn storage_alias_works() { new_test_ext().execute_with(|| { #[crate::storage_alias] - type GenericData2 = StorageMap< - System, - Blake2_128Concat, - ::BlockNumber, - ::BlockNumber, - >; + type GenericData2 = + StorageMap, BlockNumberFor>; assert_eq!(Pallet::::generic_data2(5), None); GenericData2::::insert(5, 5); @@ -1012,12 +1015,8 @@ pub mod tests { /// Some random docs that ensure that docs are accepted #[crate::storage_alias] - pub type GenericData = StorageMap< - Test2, - Blake2_128Concat, - ::BlockNumber, - ::BlockNumber, - >; + pub type GenericData = + StorageMap, BlockNumberFor>; }); } @@ -1556,7 +1555,7 @@ pub mod pallet_prelude { }, }, traits::{ - ConstU32, EnsureOrigin, GenesisBuild, Get, GetDefault, GetStorageVersion, Hooks, + BuildGenesisConfig, ConstU32, EnsureOrigin, Get, GetDefault, GetStorageVersion, Hooks, IsType, PalletInfoAccess, StorageInfoTrait, StorageVersion, TypedGet, }, Blake2_128, Blake2_128Concat, Blake2_256, CloneNoBound, DebugNoBound, EqNoBound, Identity, @@ -2231,7 +2230,7 @@ pub mod pallet_prelude { /// for the pallet. /// /// Item is defined as either an enum or a struct. It needs to be public and implement the -/// trait [`GenesisBuild`](`traits::GenesisBuild`) with +/// trait [`BuildGenesisConfig`](`traits::BuildGenesisConfig`) with /// [`#[pallet::genesis_build]`](#genesis-build-palletgenesis_build-optional). The type /// generics are constrained to be either none, or `T` or `T: Config`. /// @@ -2513,14 +2512,15 @@ pub mod pallet_prelude { /// // /// // Type must implement the `Default` trait. /// #[pallet::genesis_config] -/// #[derive(Default)] -/// pub struct GenesisConfig { +/// #[derive(frame_support::DefaultNoBound)] +/// pub struct GenesisConfig { +/// _config: sp_std::marker::PhantomData, /// _myfield: u32, /// } /// /// // Declare genesis builder. (This is need only if GenesisConfig is declared) /// #[pallet::genesis_build] -/// impl GenesisBuild for GenesisConfig { +/// impl BuildGenesisConfig for GenesisConfig { /// fn build(&self) {} /// } /// @@ -2650,13 +2650,14 @@ pub mod pallet_prelude { /// StorageMap; /// /// #[pallet::genesis_config] -/// #[derive(Default)] -/// pub struct GenesisConfig { +/// #[derive(frame_support::DefaultNoBound)] +/// pub struct GenesisConfig, I: 'static = ()> { +/// _config: sp_std::marker::PhantomData<(T,I)>, /// _myfield: u32, /// } /// /// #[pallet::genesis_build] -/// impl, I: 'static> GenesisBuild for GenesisConfig { +/// impl, I: 'static> BuildGenesisConfig for GenesisConfig { /// fn build(&self) {} /// } /// diff --git a/frame/support/src/migrations.rs b/frame/support/src/migrations.rs index 889439907efd2..f2ca2f55d3be1 100644 --- a/frame/support/src/migrations.rs +++ b/frame/support/src/migrations.rs @@ -255,12 +255,9 @@ pub fn migrate_from_pallet_version_to_storage_version< /// # Examples: /// ```ignore /// construct_runtime! { -/// pub enum Runtime where -/// Block = Block, -/// NodeBlock = primitives::Block, -/// UncheckedExtrinsic = UncheckedExtrinsic +/// pub enum Runtime /// { -/// System: frame_system::{Pallet, Call, Storage, Config, Event} = 0, +/// System: frame_system::{Pallet, Call, Storage, Config, Event} = 0, /// /// SomePalletToRemove: pallet_something::{Pallet, Call, Storage, Event} = 1, /// AnotherPalletToRemove: pallet_something_else::{Pallet, Call, Storage, Event} = 2, diff --git a/frame/support/src/storage/generator/mod.rs b/frame/support/src/storage/generator/mod.rs index 349f5de3ef3bc..bac9f642e37d6 100644 --- a/frame/support/src/storage/generator/mod.rs +++ b/frame/support/src/storage/generator/mod.rs @@ -58,7 +58,7 @@ mod tests { #[pallet::config] #[pallet::disable_frame_system_supertrait_check] pub trait Config: 'static { - type BlockNumber; + type Block: sp_runtime::traits::Block; type AccountId; type BaseCallFilter: crate::traits::Contains; type RuntimeOrigin; @@ -102,6 +102,11 @@ mod tests { pub mod pallet_prelude { pub type OriginFor = ::RuntimeOrigin; + + pub type HeaderFor = + <::Block as sp_runtime::traits::HeaderProvider>::HeaderT; + + pub type BlockNumberFor = as sp_runtime::traits::Header>::Number; } } @@ -113,18 +118,14 @@ mod tests { crate::construct_runtime!( pub enum Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, { System: self::frame_system, } ); impl self::frame_system::Config for Runtime { - type BlockNumber = BlockNumber; type AccountId = AccountId; + type Block = Block; type BaseCallFilter = crate::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index f34a0b5d87bcf..27396d93487bd 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -80,8 +80,10 @@ pub use metadata::{ }; mod hooks; +#[allow(deprecated)] +pub use hooks::GenesisBuild; pub use hooks::{ - GenesisBuild, Hooks, IntegrityTest, OnFinalize, OnGenesis, OnIdle, OnInitialize, + BuildGenesisConfig, Hooks, IntegrityTest, OnFinalize, OnGenesis, OnIdle, OnInitialize, OnRuntimeUpgrade, OnTimestampSet, }; diff --git a/frame/support/src/traits/hooks.rs b/frame/support/src/traits/hooks.rs index 7dda6624ffe65..58da1ad569929 100644 --- a/frame/support/src/traits/hooks.rs +++ b/frame/support/src/traits/hooks.rs @@ -359,8 +359,19 @@ pub trait Hooks { fn integrity_test() {} } +/// A trait to define the build function of a genesis config for both runtime and pallets. +/// +/// Replaces deprecated [`GenesisBuild`]. +pub trait BuildGenesisConfig: Default + sp_runtime::traits::MaybeSerializeDeserialize { + /// The build function puts initial `GenesisConfig` keys/values pairs into the storage. + fn build(&self); +} + /// A trait to define the build function of a genesis config, T and I are placeholder for pallet /// trait and pallet instance. +#[deprecated( + note = "GenesisBuild is planned to be removed in December 2023. Use BuildGenesisConfig instead of it." +)] pub trait GenesisBuild: Default + sp_runtime::traits::MaybeSerializeDeserialize { /// The build function is called within an externalities allowing storage APIs. /// Thus one can write to storage using regular pallet storages. diff --git a/frame/support/test/compile_pass/src/lib.rs b/frame/support/test/compile_pass/src/lib.rs index 4eaa657b1e486..bf90d73acb320 100644 --- a/frame/support/test/compile_pass/src/lib.rs +++ b/frame/support/test/compile_pass/src/lib.rs @@ -45,7 +45,6 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { pub type Signature = sr25519::Signature; pub type AccountId = ::Signer; pub type BlockNumber = u64; -pub type Index = u64; parameter_types! { pub const Version: RuntimeVersion = VERSION; @@ -55,16 +54,15 @@ impl frame_system::Config for Runtime { type BaseCallFilter = Everything; type BlockWeights = (); type BlockLength = (); - type Index = u128; + type Nonce = u128; type Hash = H256; type Hashing = BlakeTwo256; - type Header = Header; + type Block = Block; type Lookup = IdentityLookup; type BlockHashCount = ConstU64<2400>; type Version = Version; type AccountData = (); type RuntimeOrigin = RuntimeOrigin; - type BlockNumber = BlockNumber; type AccountId = AccountId; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; @@ -83,12 +81,7 @@ pub type Block = generic::Block; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; construct_runtime!( - pub struct Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub struct Runtime { System: frame_system, } ); diff --git a/frame/support/test/pallet/Cargo.toml b/frame/support/test/pallet/Cargo.toml index f2ff334a0438c..bc171c354e6ab 100644 --- a/frame/support/test/pallet/Cargo.toml +++ b/frame/support/test/pallet/Cargo.toml @@ -17,6 +17,7 @@ scale-info = { version = "2.0.0", default-features = false, features = ["derive" serde = { version = "1.0.163", default-features = false, features = ["derive"] } frame-support = { version = "4.0.0-dev", default-features = false, path = "../../" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../../../system" } +sp-runtime = { version = "24.0.0", default-features = false, path = "../../../../primitives/runtime" } [features] default = ["std"] diff --git a/frame/support/test/pallet/src/lib.rs b/frame/support/test/pallet/src/lib.rs index f2d0fd7b80d8d..49450659285d7 100644 --- a/frame/support/test/pallet/src/lib.rs +++ b/frame/support/test/pallet/src/lib.rs @@ -37,11 +37,14 @@ pub mod pallet { pub type Value = StorageValue<_, u32>; #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig {} + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + _config: core::marker::PhantomData, + } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index 2a3cf13d4dac7..6b38d42d33d0d 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -22,6 +22,7 @@ #![deny(warnings)] pub use frame_support::dispatch::RawOrigin; +use frame_system::pallet_prelude::BlockNumberFor; pub use self::pallet::*; @@ -126,12 +127,12 @@ pub mod pallet_prelude { /// tests! pub struct TestRandomness(sp_std::marker::PhantomData); -impl frame_support::traits::Randomness - for TestRandomness +impl + frame_support::traits::Randomness> for TestRandomness where T: frame_system::Config, { - fn random(subject: &[u8]) -> (Output, T::BlockNumber) { + fn random(subject: &[u8]) -> (Output, BlockNumberFor) { use sp_runtime::traits::TrailingZeroInput; ( diff --git a/frame/support/test/tests/common/outer_enums.rs b/frame/support/test/tests/common/outer_enums.rs index 98139b0f0d1a8..92dc7ac522079 100644 --- a/frame/support/test/tests/common/outer_enums.rs +++ b/frame/support/test/tests/common/outer_enums.rs @@ -52,7 +52,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) {} } @@ -96,7 +96,7 @@ pub mod pallet2 { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) {} } @@ -140,7 +140,7 @@ pub mod pallet3 { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) {} } } diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index f91ea6cdf4127..ff207ddf977c6 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -22,9 +22,13 @@ #![recursion_limit = "128"] use codec::MaxEncodedLen; -use frame_support::{parameter_types, traits::PalletInfo as _}; +use frame_support::{ + derive_impl, parameter_types, traits::PalletInfo as _, weights::RuntimeDbWeight, +}; +use frame_system::limits::{BlockLength, BlockWeights}; use scale_info::TypeInfo; -use sp_core::sr25519; +use sp_api::RuntimeVersion; +use sp_core::{sr25519, ConstU64}; use sp_runtime::{ generic, traits::{BlakeTwo256, Verify}, @@ -37,9 +41,8 @@ parameter_types! { #[frame_support::pallet(dev_mode)] mod module1 { - use self::frame_system::pallet_prelude::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -75,10 +78,9 @@ mod module1 { #[frame_support::pallet(dev_mode)] mod module2 { - use self::frame_system::pallet_prelude::*; use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -122,10 +124,9 @@ mod nested { #[frame_support::pallet(dev_mode)] pub mod module3 { - use self::frame_system::pallet_prelude::*; use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -165,11 +166,14 @@ mod nested { } #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig {} + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, + } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } } @@ -177,10 +181,9 @@ mod nested { #[frame_support::pallet(dev_mode)] pub mod module3 { - use self::frame_system::pallet_prelude::*; use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -234,11 +237,14 @@ pub mod module3 { } #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig {} + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, + } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } } @@ -250,20 +256,15 @@ pub type Header = generic::Header; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; pub type Block = generic::Block; -use frame_support_test as system; - frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { - System: system::{Pallet, Call, Event, Origin} = 30, + System: frame_system::{Pallet, Call, Event, Origin} = 30, Module1_1: module1::::{Pallet, Call, Storage, Event, Origin}, Module2: module2::{Pallet, Call, Storage, Event, Origin}, Module1_2: module1::::{Pallet, Call, Storage, Event, Origin}, - NestedModule3: nested::module3::{Pallet, Call, Config, Storage, Event, Origin}, - Module3: self::module3::{Pallet, Call, Config, Storage, Event, Origin}, + NestedModule3: nested::module3::{Pallet, Call, Config, Storage, Event, Origin}, + Module3: self::module3::{Pallet, Call, Config, Storage, Event, Origin}, Module1_3: module1::::{Pallet, Storage, Event } = 6, Module1_4: module1::::{Pallet, Call, Event } = 3, Module1_5: module1::::{Pallet, Event}, @@ -274,15 +275,18 @@ frame_support::construct_runtime!( } ); -impl frame_support_test::Config for Runtime { - type BlockNumber = BlockNumber; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { type AccountId = AccountId; + type Lookup = sp_runtime::traits::IdentityLookup; type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type DbWeight = (); + type OnSetCode = (); + type Block = Block; + type BlockHashCount = ConstU64<10>; } impl module1::Config for Runtime { @@ -330,7 +334,7 @@ fn test_pub() -> AccountId { fn check_modules_error_type() { sp_io::TestExternalities::default().execute_with(|| { assert_eq!( - Module1_1::fail(system::Origin::::Root.into()), + Module1_1::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 31, error: [0; 4], @@ -338,7 +342,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module2::fail(system::Origin::::Root.into()), + Module2::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 32, error: [0; 4], @@ -346,7 +350,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_2::fail(system::Origin::::Root.into()), + Module1_2::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 33, error: [0; 4], @@ -354,7 +358,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - NestedModule3::fail(system::Origin::::Root.into()), + NestedModule3::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 34, error: [0; 4], @@ -362,7 +366,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_3::fail(system::Origin::::Root.into()), + Module1_3::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 6, error: [0; 4], @@ -370,7 +374,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_4::fail(system::Origin::::Root.into()), + Module1_4::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 3, error: [0; 4], @@ -378,7 +382,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_5::fail(system::Origin::::Root.into()), + Module1_5::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 4, error: [0; 4], @@ -386,7 +390,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_6::fail(system::Origin::::Root.into()), + Module1_6::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 1, error: [0; 4], @@ -394,7 +398,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_7::fail(system::Origin::::Root.into()), + Module1_7::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 2, error: [0; 4], @@ -402,7 +406,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_8::fail(system::Origin::::Root.into()), + Module1_8::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 12, error: [0; 4], @@ -410,7 +414,7 @@ fn check_modules_error_type() { })), ); assert_eq!( - Module1_9::fail(system::Origin::::Root.into()), + Module1_9::fail(frame_system::Origin::::Root.into()), Err(DispatchError::Module(ModuleError { index: 13, error: [0; 4], @@ -430,7 +434,7 @@ fn integrity_test_works() { fn origin_codec() { use codec::Encode; - let origin = OriginCaller::system(system::RawOrigin::None); + let origin = OriginCaller::system(frame_system::RawOrigin::None); assert_eq!(origin.encode()[0], 30); let origin = OriginCaller::Module1_1(module1::Origin(Default::default())); @@ -465,7 +469,8 @@ fn origin_codec() { fn event_codec() { use codec::Encode; - let event = system::Event::::ExtrinsicSuccess; + let event = + frame_system::Event::::ExtrinsicSuccess { dispatch_info: Default::default() }; assert_eq!(RuntimeEvent::from(event).encode()[0], 30); let event = module1::Event::::A(test_pub()); @@ -502,7 +507,7 @@ fn event_codec() { #[test] fn call_codec() { use codec::Encode; - assert_eq!(RuntimeCall::System(system::Call::noop {}).encode()[0], 30); + assert_eq!(RuntimeCall::System(frame_system::Call::remark { remark: vec![1] }).encode()[0], 30); assert_eq!(RuntimeCall::Module1_1(module1::Call::fail {}).encode()[0], 31); assert_eq!(RuntimeCall::Module2(module2::Call::fail {}).encode()[0], 32); assert_eq!(RuntimeCall::Module1_2(module1::Call::fail {}).encode()[0], 33); @@ -633,15 +638,67 @@ fn call_subtype_conversion() { fn test_metadata() { use frame_support::metadata::{v14::*, *}; use scale_info::meta_type; + use sp_core::Encode; + + fn maybe_docs(doc: Vec<&'static str>) -> Vec<&'static str> { + if cfg!(feature = "no-metadata-docs") { + vec![] + } else { + doc + } + } let pallets = vec![ PalletMetadata { name: "System", storage: None, - calls: Some(meta_type::>().into()), - event: Some(meta_type::>().into()), - constants: vec![], - error: Some(meta_type::>().into()), + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![ + PalletConstantMetadata { + name: "BlockWeights", + ty: meta_type::(), + value: BlockWeights::default().encode(), + docs: maybe_docs(vec![" Block & extrinsics weights: base values and limits."]), + }, + PalletConstantMetadata { + name: "BlockLength", + ty: meta_type::(), + value: BlockLength::default().encode(), + docs: maybe_docs(vec![" The maximum length of a block (in bytes)."]), + }, + PalletConstantMetadata { + name: "BlockHashCount", + ty: meta_type::(), + value: 10u64.encode(), + docs: maybe_docs(vec![" Maximum number of block number to block hash mappings to keep (oldest pruned first)."]), + }, + PalletConstantMetadata { + name: "DbWeight", + ty: meta_type::(), + value: RuntimeDbWeight::default().encode(), + docs: maybe_docs(vec![" The weight of runtime database operations the runtime can invoke.",]), + }, + PalletConstantMetadata { + name: "Version", + ty: meta_type::(), + value: RuntimeVersion::default().encode(), + docs: maybe_docs(vec![ " Get the chain's current version."]), + }, + PalletConstantMetadata { + name: "SS58Prefix", + ty: meta_type::(), + value: 0u16.encode(), + docs: maybe_docs(vec![ + " The designated SS58 prefix of this chain.", + "", + " This replaces the \"ss58Format\" property declared in the chain spec. Reason is", + " that the runtime should know about the prefix in order to make use of it as", + " an identifier of the chain.", + ]), + }, + ], + error: Some(meta_type::>().into()), index: 30, }, PalletMetadata { @@ -775,7 +832,7 @@ fn test_metadata() { fn pallet_in_runtime_is_correct() { assert_eq!(PalletInfo::index::().unwrap(), 30); assert_eq!(PalletInfo::name::().unwrap(), "System"); - assert_eq!(PalletInfo::module_name::().unwrap(), "system"); + assert_eq!(PalletInfo::module_name::().unwrap(), "frame_system"); assert!(PalletInfo::crate_version::().is_some()); assert_eq!(PalletInfo::index::().unwrap(), 31); diff --git a/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.rs b/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.rs index ea468d6de13ee..4cb249714650e 100644 --- a/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.rs +++ b/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.rs @@ -20,12 +20,9 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic}, + System: system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet exclude_parts { Pallet } use_parts { Pallet }, } } diff --git a/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.stderr b/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.stderr index b1c1879aa56ad..1ea62b7d6fd65 100644 --- a/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.stderr +++ b/frame/support/test/tests/construct_runtime_ui/both_use_and_excluded_parts.stderr @@ -1,7 +1,7 @@ error: Unexpected tokens, expected one of `=`, `,` - --> tests/construct_runtime_ui/both_use_and_excluded_parts.rs:29:43 + --> tests/construct_runtime_ui/both_use_and_excluded_parts.rs:26:43 | -29 | Pallet: pallet exclude_parts { Pallet } use_parts { Pallet }, +26 | Pallet: pallet exclude_parts { Pallet } use_parts { Pallet }, | ^^^^^^^^^ error[E0412]: cannot find type `RuntimeCall` in this scope diff --git a/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.rs b/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.rs index dd8340daa0233..513fbcfb51354 100644 --- a/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.rs +++ b/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system::{Pallet}, Balance: balances::{Pallet}, diff --git a/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.stderr b/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.stderr index 27c5644e0d736..6fb983f03a961 100644 --- a/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.stderr +++ b/frame/support/test/tests/construct_runtime_ui/conflicting_module_name.stderr @@ -1,11 +1,11 @@ error: Two pallets with the same name! - --> $DIR/conflicting_module_name.rs:10:3 - | -10 | Balance: balances::{Pallet}, - | ^^^^^^^ + --> tests/construct_runtime_ui/conflicting_module_name.rs:7:3 + | +7 | Balance: balances::{Pallet}, + | ^^^^^^^ error: Two pallets with the same name! - --> $DIR/conflicting_module_name.rs:11:3 - | -11 | Balance: balances::{Pallet}, - | ^^^^^^^ + --> tests/construct_runtime_ui/conflicting_module_name.rs:8:3 + | +8 | Balance: balances::{Pallet}, + | ^^^^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.rs b/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.rs new file mode 100644 index 0000000000000..c0e325085b5e5 --- /dev/null +++ b/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.rs @@ -0,0 +1,13 @@ +use frame_support::construct_runtime; + +construct_runtime! { + pub struct Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = Uxt, + { + System: frame_system::{Pallet, Call, Storage, Config, Event}, + } +} + +fn main() {} diff --git a/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr b/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr new file mode 100644 index 0000000000000..946277e9068e3 --- /dev/null +++ b/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr @@ -0,0 +1,442 @@ +error: use of deprecated constant `WhereSection::_w`: + It is deprecated to use a `where` clause in `construct_runtime`. + Please instead use `frame_system::Config` to set the `Block` type and delete this clause. + It is planned to be removed in December 2023. + + For more info see: + + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | / construct_runtime! { +4 | | pub struct Runtime where +5 | | Block = Block, +6 | | NodeBlock = Block, +... | +10 | | } +11 | | } + | |_^ + | + = note: `-D deprecated` implied by `-D warnings` + = note: this error originates in the macro `frame_support::match_and_insert` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | +note: required by a bound in `frame_system::Event` + --> $WORKSPACE/frame/system/src/lib.rs + | + | pub enum Event { + | ^^^^^^ required by this bound in `Event` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied in `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | +note: required because it appears within the type `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `Clone` + --> $RUST/core/src/clone.rs + | + | pub trait Clone: Sized { + | ^^^^^ required by this bound in `Clone` + = note: this error originates in the derive macro `Clone` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied in `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | +note: required because it appears within the type `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `EncodeLike` + --> $CARGO/parity-scale-codec-3.6.1/src/encode_like.rs + | + | pub trait EncodeLike: Sized + Encode {} + | ^^^^^ required by this bound in `EncodeLike` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied in `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | +note: required because it appears within the type `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `Decode` + --> $CARGO/parity-scale-codec-3.6.1/src/codec.rs + | + | pub trait Decode: Sized { + | ^^^^^ required by this bound in `Decode` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied in `frame_system::Event` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = note: required because it appears within the type `Event` +note: required by a bound in `From` + --> $RUST/core/src/convert/mod.rs + | + | pub trait From: Sized { + | ^ required by this bound in `From` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied in `frame_system::Event` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = note: required because it appears within the type `Event` +note: required by a bound in `TryInto` + --> $RUST/core/src/convert/mod.rs + | + | pub trait TryInto: Sized { + | ^ required by this bound in `TryInto` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | construct_runtime! { + | ^ the trait `Config` is not implemented for `Runtime` + | + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `RawOrigin<_>: TryFrom` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = help: the trait `TryFrom` is implemented for `RawOrigin<::AccountId>` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = help: the trait `Callable` is implemented for `Pallet` + = note: required for `Pallet` to implement `Callable` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = note: required for `Pallet` to implement `Callable` +note: required because it appears within the type `RuntimeCall` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `Clone` + --> $RUST/core/src/clone.rs + | + | pub trait Clone: Sized { + | ^^^^^ required by this bound in `Clone` + = note: this error originates in the derive macro `Clone` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = note: required for `Pallet` to implement `Callable` +note: required because it appears within the type `RuntimeCall` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `EncodeLike` + --> $CARGO/parity-scale-codec-3.6.1/src/encode_like.rs + | + | pub trait EncodeLike: Sized + Encode {} + | ^^^^^ required by this bound in `EncodeLike` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = note: required for `Pallet` to implement `Callable` +note: required because it appears within the type `RuntimeCall` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `Decode` + --> $CARGO/parity-scale-codec-3.6.1/src/codec.rs + | + | pub trait Decode: Sized { + | ^^^^^ required by this bound in `Decode` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:9:3 + | +9 | System: frame_system::{Pallet, Call, Storage, Config, Event}, + | ^^^^^^ the trait `Config` is not implemented for `Runtime` + | +note: required by a bound in `frame_system::GenesisConfig` + --> $WORKSPACE/frame/system/src/lib.rs + | + | pub struct GenesisConfig { + | ^^^^^^ required by this bound in `GenesisConfig` + +error[E0277]: the trait bound `Runtime: Config` is not satisfied in `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | +note: required because it appears within the type `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `Result` + --> $RUST/core/src/result.rs + | + | pub enum Result { + | ^ required by this bound in `Result` + = note: this error originates in the derive macro `self::sp_api_hidden_includes_construct_runtime::hidden_include::codec::Decode` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied in `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | +note: required because it appears within the type `RuntimeEvent` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `TryInto` + --> $RUST/core/src/convert/mod.rs + | + | pub trait TryInto: Sized { + | ^^^^^ required by this bound in `TryInto` + = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Runtime: Config` is not satisfied + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | + | + = note: required for `Pallet` to implement `Callable` +note: required because it appears within the type `RuntimeCall` + --> tests/construct_runtime_ui/deprecated_where_block.rs:3:1 + | +3 | // construct_runtime! { +4 | || pub struct Runtime where +5 | || Block = Block, +6 | || NodeBlock = Block, +... || +10 | || } +11 | || } + | ||_- in this macro invocation +... | +note: required by a bound in `Result` + --> $RUST/core/src/result.rs + | + | pub enum Result { + | ^ required by this bound in `Result` + = note: this error originates in the derive macro `self::sp_api_hidden_includes_construct_runtime::hidden_include::codec::Decode` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/double_module_parts.rs b/frame/support/test/tests/construct_runtime_ui/double_module_parts.rs index 3269d22434fdf..68a2523d3bcb2 100644 --- a/frame/support/test/tests/construct_runtime_ui/double_module_parts.rs +++ b/frame/support/test/tests/construct_runtime_ui/double_module_parts.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system::{Pallet}, Balance: balances::{Config, Call, Config, Origin}, diff --git a/frame/support/test/tests/construct_runtime_ui/double_module_parts.stderr b/frame/support/test/tests/construct_runtime_ui/double_module_parts.stderr index 9d10474ce85ab..e3f694781441f 100644 --- a/frame/support/test/tests/construct_runtime_ui/double_module_parts.stderr +++ b/frame/support/test/tests/construct_runtime_ui/double_module_parts.stderr @@ -1,5 +1,5 @@ error: `Config` was already declared before. Please remove the duplicate declaration - --> $DIR/double_module_parts.rs:10:37 - | -10 | Balance: balances::{Config, Call, Config, Origin}, - | ^^^^^^ + --> tests/construct_runtime_ui/double_module_parts.rs:7:37 + | +7 | Balance: balances::{Config, Call, Config, Origin}, + | ^^^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.rs b/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.rs index 44b7fd0ba25f7..23badd76276e2 100644 --- a/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.rs +++ b/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { system: , } diff --git a/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.stderr b/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.stderr index 7102076e5acb0..f0c0f17779d67 100644 --- a/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.stderr +++ b/frame/support/test/tests/construct_runtime_ui/empty_pallet_path.stderr @@ -1,5 +1,5 @@ error: expected one of: `crate`, `self`, `super`, identifier - --> $DIR/empty_pallet_path.rs:9:11 + --> tests/construct_runtime_ui/empty_pallet_path.rs:6:11 | -9 | system: , +6 | system: , | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.rs b/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.rs index 83a166fc00552..10cda7b4e7e8a 100644 --- a/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.rs @@ -25,12 +25,9 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic}, + System: system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet exclude_parts { Call }, } } diff --git a/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.stderr b/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.stderr index 66098898bb877..4b85613838ab5 100644 --- a/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/exclude_undefined_part.stderr @@ -1,7 +1,7 @@ error: Invalid pallet part specified, the pallet `Pallet` doesn't have the `Call` part. Available parts are: `Pallet`, `Storage`. - --> tests/construct_runtime_ui/exclude_undefined_part.rs:34:34 + --> tests/construct_runtime_ui/exclude_undefined_part.rs:31:34 | -34 | Pallet: pallet exclude_parts { Call }, +31 | Pallet: pallet exclude_parts { Call }, | ^^^^ error[E0412]: cannot find type `RuntimeCall` in this scope diff --git a/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.rs b/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.rs index 7ab4329110d8b..35d49a4d8a23b 100644 --- a/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.rs +++ b/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.rs @@ -1,13 +1,10 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { #[cfg(test)] - System: frame_system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.stderr b/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.stderr index a86a839615aa0..6a6c4b4158889 100644 --- a/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.stderr +++ b/frame/support/test/tests/construct_runtime_ui/feature_gated_system_pallet.stderr @@ -1,5 +1,5 @@ error: `System` pallet declaration is feature gated, please remove any `#[cfg]` attributes - --> tests/construct_runtime_ui/feature_gated_system_pallet.rs:10:3 - | -10 | System: frame_system::{Pallet, Call, Storage, Config, Event}, - | ^^^^^^ + --> tests/construct_runtime_ui/feature_gated_system_pallet.rs:7:3 + | +7 | System: frame_system::{Pallet, Call, Storage, Config, Event}, + | ^^^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.rs b/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.rs index 0912ffc98d54b..1ad1f8e0b1d5f 100644 --- a/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.rs +++ b/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system::{Pallet}, Balance: balances::::{Call, Origin}, diff --git a/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.stderr b/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.stderr index ca2bb998e06d3..a6adb37d04949 100644 --- a/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.stderr +++ b/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.stderr @@ -1,5 +1,5 @@ error: `Call` is not allowed to have generics. Only the following pallets are allowed to have generics: `Event`, `Error`, `Origin`, `Config`. - --> $DIR/generics_in_invalid_module.rs:10:36 - | -10 | Balance: balances::::{Call, Origin}, - | ^^^^ + --> tests/construct_runtime_ui/generics_in_invalid_module.rs:7:36 + | +7 | Balance: balances::::{Call, Origin}, + | ^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.rs b/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.rs index c253444ee31db..bce87c51336eb 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.rs +++ b/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system::{Pallet}, #[cfg(feature = 1)] diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.stderr b/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.stderr index 68366a3410bf1..bfee2910cd2a4 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.stderr +++ b/frame/support/test/tests/construct_runtime_ui/invalid_meta_literal.stderr @@ -1,6 +1,6 @@ error: feature = 1 ^ expected one of ``, `all`, `any`, `not` here - --> tests/construct_runtime_ui/invalid_meta_literal.rs:10:3 - | -10 | #[cfg(feature = 1)] - | ^ + --> tests/construct_runtime_ui/invalid_meta_literal.rs:7:3 + | +7 | #[cfg(feature = 1)] + | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_module_details.rs b/frame/support/test/tests/construct_runtime_ui/invalid_module_details.rs index 9fb3169e1df77..bf6919f5a58ef 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_module_details.rs +++ b/frame/support/test/tests/construct_runtime_ui/invalid_module_details.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { system: System::(), } diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_module_details.stderr b/frame/support/test/tests/construct_runtime_ui/invalid_module_details.stderr index 0a20cf4e39a88..1f9277c3f0a8e 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_module_details.stderr +++ b/frame/support/test/tests/construct_runtime_ui/invalid_module_details.stderr @@ -1,5 +1,5 @@ error: Unexpected tokens, expected one of `::$ident` `::{`, `exclude_parts`, `use_parts`, `=`, `,` - --> tests/construct_runtime_ui/invalid_module_details.rs:9:17 + --> tests/construct_runtime_ui/invalid_module_details.rs:6:17 | -9 | system: System::(), +6 | system: System::(), | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.rs b/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.rs index 6ba268b73eea6..51f14e6883e4a 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.rs +++ b/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { system: System::{enum}, } diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.stderr b/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.stderr index f1c3929fff25f..dfcc9b8be42c6 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.stderr +++ b/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.stderr @@ -1,5 +1,5 @@ error: expected one of: `Pallet`, `Call`, `Storage`, `Event`, `Error`, `Config`, `Origin`, `Inherent`, `ValidateUnsigned`, `FreezeReason`, `HoldReason`, `LockId`, `SlashReason` - --> $DIR/invalid_module_details_keyword.rs:9:20 + --> tests/construct_runtime_ui/invalid_module_details_keyword.rs:6:20 | -9 | system: System::{enum}, +6 | system: System::{enum}, | ^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.rs b/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.rs index 173916f2ff6eb..607741d7823d4 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.rs +++ b/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system::{Pallet}, Balance: balances::{Unexpected}, diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.stderr b/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.stderr index 2d5eeb5108fb9..9dd849ff0412e 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.stderr +++ b/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.stderr @@ -1,5 +1,5 @@ error: expected one of: `Pallet`, `Call`, `Storage`, `Event`, `Error`, `Config`, `Origin`, `Inherent`, `ValidateUnsigned`, `FreezeReason`, `HoldReason`, `LockId`, `SlashReason` - --> $DIR/invalid_module_entry.rs:10:23 - | -10 | Balance: balances::{Unexpected}, - | ^^^^^^^^^^ + --> tests/construct_runtime_ui/invalid_module_entry.rs:7:23 + | +7 | Balance: balances::{Unexpected}, + | ^^^^^^^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.rs b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.rs index 09c316e6ebaed..c132fa01b2297 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.rs +++ b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { system: System ? } diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.stderr b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.stderr index 6025de82bd206..80be1b8dd42fd 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.stderr +++ b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.stderr @@ -1,5 +1,5 @@ error: Unexpected tokens, expected one of `::$ident` `::{`, `exclude_parts`, `use_parts`, `=`, `,` - --> $DIR/invalid_token_after_module.rs:9:18 + --> tests/construct_runtime_ui/invalid_token_after_module.rs:6:18 | -9 | system: System ? +6 | system: System ? | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.rs b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.rs index 18d367d102d3a..42e7759f87f2b 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.rs +++ b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { system ? } diff --git a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.stderr b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.stderr index eaae082c8460c..8988f8a35b0a4 100644 --- a/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.stderr +++ b/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.stderr @@ -1,5 +1,5 @@ error: expected `:` - --> $DIR/invalid_token_after_name.rs:9:10 + --> tests/construct_runtime_ui/invalid_token_after_name.rs:6:10 | -9 | system ? +6 | system ? | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.rs b/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.rs index d3018f02f89e3..bc2039c4e8180 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.rs +++ b/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system expanded::{}::{Pallet}, Balance: balances:: expanded::{}::{Event}, diff --git a/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.stderr b/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.stderr index 97968df36a482..30fcba4c710d0 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.stderr +++ b/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.stderr @@ -1,5 +1,5 @@ error: Instantiable pallet with no generic `Event` cannot be constructed: pallet `Balance` must have generic `Event` - --> $DIR/missing_event_generic_on_module_with_instance.rs:10:3 - | -10 | Balance: balances:: expanded::{}::{Event}, - | ^^^^^^^ + --> tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.rs:7:3 + | +7 | Balance: balances:: expanded::{}::{Event}, + | ^^^^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/missing_module_instance.rs b/frame/support/test/tests/construct_runtime_ui/missing_module_instance.rs index 24e4ee979bd76..afd96a04854f2 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_module_instance.rs +++ b/frame/support/test/tests/construct_runtime_ui/missing_module_instance.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { system: System::<>, } diff --git a/frame/support/test/tests/construct_runtime_ui/missing_module_instance.stderr b/frame/support/test/tests/construct_runtime_ui/missing_module_instance.stderr index 6303c74e42e5c..5072f718db12e 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_module_instance.stderr +++ b/frame/support/test/tests/construct_runtime_ui/missing_module_instance.stderr @@ -1,5 +1,5 @@ error: expected identifier - --> $DIR/missing_module_instance.rs:9:20 + --> tests/construct_runtime_ui/missing_module_instance.rs:6:20 | -9 | system: System::<>, +6 | system: System::<>, | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.rs b/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.rs index 5fc238067f287..42db63ae90a3a 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.rs +++ b/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system expanded::{}::{Pallet}, Balance: balances:: expanded::{}::{Origin}, diff --git a/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.stderr b/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.stderr index f7df25d4c363f..6c076d7b49fc0 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.stderr +++ b/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.stderr @@ -1,5 +1,5 @@ error: Instantiable pallet with no generic `Origin` cannot be constructed: pallet `Balance` must have generic `Origin` - --> $DIR/missing_origin_generic_on_module_with_instance.rs:10:3 - | -10 | Balance: balances:: expanded::{}::{Origin}, - | ^^^^^^^ + --> tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.rs:7:3 + | +7 | Balance: balances:: expanded::{}::{Origin}, + | ^^^^^^^ diff --git a/frame/support/test/tests/construct_runtime_ui/missing_system_module.rs b/frame/support/test/tests/construct_runtime_ui/missing_system_module.rs index 7ab902c3aadd8..685f9059b1be2 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_system_module.rs +++ b/frame/support/test/tests/construct_runtime_ui/missing_system_module.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { } } diff --git a/frame/support/test/tests/construct_runtime_ui/missing_system_module.stderr b/frame/support/test/tests/construct_runtime_ui/missing_system_module.stderr index 7648f5c1bfb33..c8631f44051ca 100644 --- a/frame/support/test/tests/construct_runtime_ui/missing_system_module.stderr +++ b/frame/support/test/tests/construct_runtime_ui/missing_system_module.stderr @@ -1,6 +1,6 @@ -error: `System` pallet declaration is missing. Please add this line: `System: frame_system::{Pallet, Call, Storage, Config, Event},` - --> $DIR/missing_system_module.rs:8:2 +error: `System` pallet declaration is missing. Please add this line: `System: frame_system::{Pallet, Call, Storage, Config, Event},` + --> tests/construct_runtime_ui/missing_system_module.rs:5:2 | -8 | / { -9 | | } +5 | / { +6 | | } | |_____^ diff --git a/frame/support/test/tests/construct_runtime_ui/missing_where_block.rs b/frame/support/test/tests/construct_runtime_ui/missing_where_block.rs deleted file mode 100644 index 303df6b03d72e..0000000000000 --- a/frame/support/test/tests/construct_runtime_ui/missing_where_block.rs +++ /dev/null @@ -1,7 +0,0 @@ -use frame_support::construct_runtime; - -construct_runtime! { - pub struct Runtime {} -} - -fn main() {} diff --git a/frame/support/test/tests/construct_runtime_ui/missing_where_block.stderr b/frame/support/test/tests/construct_runtime_ui/missing_where_block.stderr deleted file mode 100644 index d2a66f95101f4..0000000000000 --- a/frame/support/test/tests/construct_runtime_ui/missing_where_block.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: expected `where` - --> tests/construct_runtime_ui/missing_where_block.rs:4:21 - | -4 | pub struct Runtime {} - | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs b/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs index 5dfc67c83836a..0d6afbcdc2c65 100644 --- a/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs +++ b/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs @@ -22,14 +22,13 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -47,12 +46,9 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { - System: frame_system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet1: pallet::{Pallet}, Pallet2: pallet::{Pallet}, Pallet3: pallet::{Pallet}, diff --git a/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.stderr b/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.stderr index 19a9a7bd08e32..55cef6704ee3f 100644 --- a/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.stderr +++ b/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.stderr @@ -1,7 +1,7 @@ error: The number of pallets exceeds the maximum number of tuple elements. To increase this limit, enable the tuples-96 feature of [frame_support]. - --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:50:2 + --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:49:2 | -50 | pub struct Runtime where +49 | pub struct Runtime | ^^^ error[E0412]: cannot find type `RuntimeCall` in this scope @@ -34,26 +34,26 @@ error[E0412]: cannot find type `RuntimeOrigin` in this scope | ^^^^^^^^^^^^^ help: you might have meant to use the associated type: `Self::RuntimeOrigin` error[E0412]: cannot find type `RuntimeCall` in this scope - --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:27:21 + --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:26:21 | -27 | type RuntimeCall = RuntimeCall; +26 | type RuntimeCall = RuntimeCall; | ^^^^^^^^^^^ help: you might have meant to use the associated type: `Self::RuntimeCall` error[E0412]: cannot find type `RuntimeEvent` in this scope - --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:33:22 + --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:32:22 | -33 | type RuntimeEvent = RuntimeEvent; +32 | type RuntimeEvent = RuntimeEvent; | ^^^^^^^^^^^^ help: you might have meant to use the associated type: `Self::RuntimeEvent` error[E0412]: cannot find type `PalletInfo` in this scope - --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:39:20 + --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:38:20 | -39 | type PalletInfo = PalletInfo; +38 | type PalletInfo = PalletInfo; | ^^^^^^^^^^ | help: you might have meant to use the associated type | -39 | type PalletInfo = Self::PalletInfo; +38 | type PalletInfo = Self::PalletInfo; | ~~~~~~~~~~~~~~~~ help: consider importing this trait | diff --git a/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs b/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs index 866c3f0de6c3c..8b3e26bc5e2e4 100644 --- a/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs +++ b/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs @@ -1,6 +1,6 @@ use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; +use sp_runtime::{generic, traits::BlakeTwo256}; #[frame_support::pallet] mod pallet { @@ -18,22 +18,22 @@ mod pallet { #[derive(scale_info::TypeInfo, frame_support::PalletError, codec::Encode, codec::Decode)] pub enum Nested1 { - Nested2(Nested2) + Nested2(Nested2), } #[derive(scale_info::TypeInfo, frame_support::PalletError, codec::Encode, codec::Decode)] pub enum Nested2 { - Nested3(Nested3) + Nested3(Nested3), } #[derive(scale_info::TypeInfo, frame_support::PalletError, codec::Encode, codec::Decode)] pub enum Nested3 { - Nested4(Nested4) + Nested4(Nested4), } #[derive(scale_info::TypeInfo, frame_support::PalletError, codec::Encode, codec::Decode)] pub enum Nested4 { - Num(u8) + Num(u8), } pub type Signature = sr25519::Signature; @@ -47,14 +47,13 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -72,12 +71,9 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { - System: frame_system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.stderr b/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.stderr index b9cec02a2b092..47504573515a2 100644 --- a/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.stderr +++ b/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.stderr @@ -1,13 +1,13 @@ error[E0080]: evaluation of constant value failed - --> tests/construct_runtime_ui/pallet_error_too_large.rs:74:1 + --> tests/construct_runtime_ui/pallet_error_too_large.rs:73:1 | -74 | / construct_runtime! { -75 | | pub struct Runtime where -76 | | Block = Block, -77 | | NodeBlock = Block, -... | -82 | | } -83 | | } - | |_^ the evaluated program panicked at 'The maximum encoded size of the error type in the `Pallet` pallet exceeds `MAX_MODULE_ERROR_ENCODED_SIZE`', $DIR/tests/construct_runtime_ui/pallet_error_too_large.rs:74:1 +73 | / construct_runtime! { +74 | | pub struct Runtime +75 | | { +76 | | System: frame_system::{Pallet, Call, Storage, Config, Event}, +77 | | Pallet: pallet::{Pallet}, +78 | | } +79 | | } + | |_^ the evaluated program panicked at 'The maximum encoded size of the error type in the `Pallet` pallet exceeds `MAX_MODULE_ERROR_ENCODED_SIZE`', $DIR/tests/construct_runtime_ui/pallet_error_too_large.rs:73:1 | = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs index 0010f5277bb40..25cb5e93f652e 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs @@ -1,6 +1,6 @@ use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; +use sp_runtime::{generic, traits::BlakeTwo256}; #[frame_support::pallet] mod pallet { @@ -22,14 +22,13 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -47,12 +46,9 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { - System: frame_system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet, Call}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.stderr index c2092edea05b5..f3f29e4c69554 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.stderr @@ -4,13 +4,13 @@ error: `Pallet` does not have #[pallet::call] defined, perhaps you should remove 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet::{Pallet, Call}, +53 | | } +54 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_call_check::is_call_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs index 28622eb08e443..c44cceef81a12 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs @@ -1,6 +1,6 @@ use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; +use sp_runtime::{generic, traits::BlakeTwo256}; #[frame_support::pallet] mod pallet { @@ -22,14 +22,13 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -47,12 +46,9 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { - System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, + System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, Pallet: pallet expanded::{}::{Pallet, Event}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr index eb667fe04a39e..81e42cec3b97a 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr @@ -4,27 +4,27 @@ error: `Pallet` does not have #[pallet::event] defined, perhaps you should remov 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Event}, +53 | | } +54 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_event_check::is_event_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0412]: cannot find type `Event` in module `pallet` - --> tests/construct_runtime_ui/undefined_event_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_event_part.rs:48:1 | -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Event}, +53 | | } +54 | | } | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs index f6365ceb1a9cd..4436202f04fc7 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs @@ -1,6 +1,6 @@ use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; +use sp_runtime::{generic, traits::BlakeTwo256}; #[frame_support::pallet] mod pallet { @@ -22,14 +22,13 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -47,12 +46,9 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { - System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, + System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, Pallet: pallet expanded::{}::{Pallet, Config}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr index cdab7d3afa18c..920785fc96291 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr @@ -4,27 +4,27 @@ error: `Pallet` does not have #[pallet::genesis_config] defined, perhaps you sho 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Config}, +53 | | } +54 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_genesis_config_check::is_genesis_config_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0412]: cannot find type `GenesisConfig` in module `pallet` - --> tests/construct_runtime_ui/undefined_genesis_config_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_genesis_config_part.rs:48:1 | -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Config}, +53 | | } +54 | | } | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs index 83179a51abc8f..8b48c4d0d6af7 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs @@ -1,6 +1,6 @@ use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; +use sp_runtime::{generic, traits::BlakeTwo256}; #[frame_support::pallet] mod pallet { @@ -22,14 +22,13 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -47,12 +46,9 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { - System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, + System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, Pallet: pallet expanded::{}::{Pallet, Inherent}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.stderr index a068cab4cb1ab..659d43b151006 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.stderr @@ -4,31 +4,31 @@ error: `Pallet` does not have #[pallet::inherent] defined, perhaps you should re 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +53 | | } +54 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_inherent_check::is_inherent_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `create_inherent` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:48:1 | 11 | pub struct Pallet(_); | -------------------- function or associated item `create_inherent` not found for this struct ... -49 | construct_runtime! { +48 | construct_runtime! { | _^ -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +53 | | } +54 | | } | |_^ function or associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope @@ -37,19 +37,19 @@ error[E0599]: no function or associated item named `create_inherent` found for s = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `is_inherent` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:48:1 | 11 | pub struct Pallet(_); | -------------------- function or associated item `is_inherent` not found for this struct ... -49 | construct_runtime! { +48 | construct_runtime! { | _^ -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +53 | | } +54 | | } | |_^ function or associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope @@ -58,19 +58,19 @@ error[E0599]: no function or associated item named `is_inherent` found for struc = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `check_inherent` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:48:1 | 11 | pub struct Pallet(_); | -------------------- function or associated item `check_inherent` not found for this struct ... -49 | construct_runtime! { +48 | construct_runtime! { | _^ -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +53 | | } +54 | | } | |_^ function or associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope @@ -79,19 +79,19 @@ error[E0599]: no function or associated item named `check_inherent` found for st = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no associated item named `INHERENT_IDENTIFIER` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:48:1 | 11 | pub struct Pallet(_); | -------------------- associated item `INHERENT_IDENTIFIER` not found for this struct ... -49 | construct_runtime! { +48 | construct_runtime! { | _^ -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +53 | | } +54 | | } | |_^ associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope @@ -100,19 +100,19 @@ error[E0599]: no associated item named `INHERENT_IDENTIFIER` found for struct `p = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `is_inherent_required` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:48:1 | 11 | pub struct Pallet(_); | -------------------- function or associated item `is_inherent_required` not found for this struct ... -49 | construct_runtime! { +48 | construct_runtime! { | _^ -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +53 | | } +54 | | } | |_^ function or associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs index b15a2d3349043..974928785f748 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs @@ -1,6 +1,6 @@ use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; +use sp_runtime::{generic, traits::BlakeTwo256}; #[frame_support::pallet] mod pallet { @@ -22,14 +22,13 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -47,12 +46,9 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { - System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, + System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, Pallet: pallet expanded::{}::{Pallet, Origin}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr index 0677340e25c12..c41dbe79421ea 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr @@ -4,27 +4,27 @@ error: `Pallet` does not have #[pallet::origin] defined, perhaps you should remo 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Origin}, +53 | | } +54 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_origin_check::is_origin_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0412]: cannot find type `Origin` in module `pallet` - --> tests/construct_runtime_ui/undefined_origin_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_origin_part.rs:48:1 | -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet expanded::{}::{Pallet, Origin}, +53 | | } +54 | | } | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs index b5573d816eff2..505b249d92d58 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs @@ -22,14 +22,13 @@ impl pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -47,12 +46,9 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { - System: frame_system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet, ValidateUnsigned}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr index 211df67b70056..007b77250736e 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr @@ -4,48 +4,46 @@ error: `Pallet` does not have #[pallet::validate_unsigned] defined, perhaps you 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -49 | / construct_runtime! { -50 | | pub struct Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } +48 | / construct_runtime! { +49 | | pub struct Runtime +50 | | { +51 | | System: frame_system::{Pallet, Call, Storage, Config, Event}, +52 | | Pallet: pallet::{Pallet, ValidateUnsigned}, +53 | | } +54 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_validate_unsigned_check::is_validate_unsigned_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no variant or associated item named `Pallet` found for enum `RuntimeCall` in the current scope - --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:56:3 + --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:52:3 | -49 | // construct_runtime! { -50 | || pub struct Runtime where -51 | || Block = Block, -52 | || NodeBlock = Block, -... || -55 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, -56 | || Pallet: pallet::{Pallet, ValidateUnsigned}, +48 | // construct_runtime! { +49 | || pub struct Runtime +50 | || { +51 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, +52 | || Pallet: pallet::{Pallet, ValidateUnsigned}, | || -^^^^^^ variant or associated item not found in `RuntimeCall` | ||________| | | ... | error[E0599]: no function or associated item named `pre_dispatch` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:48:1 | 11 | pub struct Pallet(_); | -------------------- function or associated item `pre_dispatch` not found for this struct ... -49 | construct_runtime! { +48 | construct_runtime! { | __^ | | _| | || -50 | || pub struct Runtime where -51 | || Block = Block, -52 | || NodeBlock = Block, -... || -57 | || } -58 | || } +49 | || pub struct Runtime +50 | || { +51 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, +52 | || Pallet: pallet::{Pallet, ValidateUnsigned}, +53 | || } +54 | || } | ||_- in this macro invocation ... | | @@ -56,21 +54,21 @@ error[E0599]: no function or associated item named `pre_dispatch` found for stru = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `validate_unsigned` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:49:1 + --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:48:1 | 11 | pub struct Pallet(_); | -------------------- function or associated item `validate_unsigned` not found for this struct ... -49 | construct_runtime! { +48 | construct_runtime! { | __^ | | _| | || -50 | || pub struct Runtime where -51 | || Block = Block, -52 | || NodeBlock = Block, -... || -57 | || } -58 | || } +49 | || pub struct Runtime +50 | || { +51 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, +52 | || Pallet: pallet::{Pallet, ValidateUnsigned}, +53 | || } +54 | || } | ||_- in this macro invocation ... | | diff --git a/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.rs b/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.rs index e5fd284dc8722..e4e2d3dca021e 100644 --- a/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.rs +++ b/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system::{Pallet}, #[cfg(feature(test))] diff --git a/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.stderr b/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.stderr index 98d99a0d34997..34637269db617 100644 --- a/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.stderr +++ b/frame/support/test/tests/construct_runtime_ui/unsupported_meta_structure.stderr @@ -1,6 +1,6 @@ error: feature(test) ^ expected one of `=`, `,`, `)` here - --> tests/construct_runtime_ui/unsupported_meta_structure.rs:10:3 - | -10 | #[cfg(feature(test))] - | ^ + --> tests/construct_runtime_ui/unsupported_meta_structure.rs:7:3 + | +7 | #[cfg(feature(test))] + | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.rs b/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.rs index 03363d30a6429..491cc2c90533d 100644 --- a/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.rs +++ b/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.rs @@ -1,10 +1,7 @@ use frame_support::construct_runtime; construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { System: system::{Pallet}, #[attr] diff --git a/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.stderr b/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.stderr index fceb2b8a99db8..da1b61b1c3078 100644 --- a/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.stderr +++ b/frame/support/test/tests/construct_runtime_ui/unsupported_pallet_attr.stderr @@ -1,5 +1,5 @@ error: Unsupported attribute, only #[cfg] is supported on pallet declarations in `construct_runtime` - --> tests/construct_runtime_ui/unsupported_pallet_attr.rs:10:3 - | -10 | #[attr] - | ^ + --> tests/construct_runtime_ui/unsupported_pallet_attr.rs:7:3 + | +7 | #[attr] + | ^ diff --git a/frame/support/test/tests/construct_runtime_ui/use_undefined_part.rs b/frame/support/test/tests/construct_runtime_ui/use_undefined_part.rs index 971e2b831ae08..8563be1008cd9 100644 --- a/frame/support/test/tests/construct_runtime_ui/use_undefined_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/use_undefined_part.rs @@ -25,12 +25,9 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic}, + System: system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet use_parts { Call }, } } diff --git a/frame/support/test/tests/construct_runtime_ui/use_undefined_part.stderr b/frame/support/test/tests/construct_runtime_ui/use_undefined_part.stderr index cb6b6a44d61da..4058ccab2c5d7 100644 --- a/frame/support/test/tests/construct_runtime_ui/use_undefined_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/use_undefined_part.stderr @@ -1,7 +1,7 @@ error: Invalid pallet part specified, the pallet `Pallet` doesn't have the `Call` part. Available parts are: `Pallet`, `Storage`. - --> tests/construct_runtime_ui/use_undefined_part.rs:34:30 + --> tests/construct_runtime_ui/use_undefined_part.rs:31:30 | -34 | Pallet: pallet use_parts { Call }, +31 | Pallet: pallet use_parts { Call }, | ^^^^ error[E0412]: cannot find type `RuntimeCall` in this scope diff --git a/frame/support/test/tests/final_keys.rs b/frame/support/test/tests/final_keys.rs index f56a6c9fcaaa1..765afaf1e6604 100644 --- a/frame/support/test/tests/final_keys.rs +++ b/frame/support/test/tests/final_keys.rs @@ -16,8 +16,10 @@ // limitations under the License. use codec::Encode; -use frame_support::{storage::unhashed, StoragePrefixedMap}; -use sp_core::sr25519; +use frame_support::{derive_impl, storage::unhashed, StoragePrefixedMap}; +use frame_system::pallet_prelude::BlockNumberFor; + +use sp_core::{sr25519, ConstU32}; use sp_io::{ hashing::{blake2_128, twox_128, twox_64}, TestExternalities, @@ -31,7 +33,6 @@ use sp_runtime::{ mod no_instance { use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; #[pallet::pallet] pub struct Pallet(_); @@ -59,7 +60,7 @@ mod no_instance { #[pallet::storage] #[pallet::getter(fn test_generic_value)] - pub type TestGenericValue = StorageValue<_, T::BlockNumber, OptionQuery>; + pub type TestGenericValue = StorageValue<_, BlockNumberFor, OptionQuery>; #[pallet::storage] #[pallet::getter(fn foo2)] pub type TestGenericDoubleMap = StorageDoubleMap< @@ -67,7 +68,7 @@ mod no_instance { Blake2_128Concat, u32, Blake2_128Concat, - T::BlockNumber, + BlockNumberFor, u32, ValueQuery, >; @@ -75,8 +76,8 @@ mod no_instance { #[pallet::genesis_config] pub struct GenesisConfig { pub value: u32, - pub test_generic_value: T::BlockNumber, - pub test_generic_double_map: Vec<(u32, T::BlockNumber, u32)>, + pub test_generic_value: BlockNumberFor, + pub test_generic_double_map: Vec<(u32, BlockNumberFor, u32)>, } impl Default for GenesisConfig { @@ -90,7 +91,7 @@ mod no_instance { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { >::put(self.value); >::put(&self.test_generic_value); @@ -105,7 +106,6 @@ mod no_instance { mod instance { use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; #[pallet::pallet] pub struct Pallet(PhantomData<(T, I)>); @@ -136,7 +136,7 @@ mod instance { #[pallet::storage] #[pallet::getter(fn test_generic_value)] pub type TestGenericValue, I: 'static = ()> = - StorageValue<_, T::BlockNumber, OptionQuery>; + StorageValue<_, BlockNumberFor, OptionQuery>; #[pallet::storage] #[pallet::getter(fn foo2)] pub type TestGenericDoubleMap, I: 'static = ()> = StorageDoubleMap< @@ -144,7 +144,7 @@ mod instance { Blake2_128Concat, u32, Blake2_128Concat, - T::BlockNumber, + BlockNumberFor, u32, ValueQuery, >; @@ -152,8 +152,8 @@ mod instance { #[pallet::genesis_config] pub struct GenesisConfig, I: 'static = ()> { pub value: u32, - pub test_generic_value: T::BlockNumber, - pub test_generic_double_map: Vec<(u32, T::BlockNumber, u32)>, + pub test_generic_value: BlockNumberFor, + pub test_generic_double_map: Vec<(u32, BlockNumberFor, u32)>, pub phantom: PhantomData, } @@ -169,7 +169,7 @@ mod instance { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { >::put(self.value); >::put(&self.test_generic_value); @@ -201,27 +201,25 @@ pub type Block = generic::Block; frame_support::construct_runtime!( pub enum Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + { - System: frame_support_test, + System: frame_system, FinalKeysNone: no_instance, FinalKeysSome: instance, Instance2FinalKeysSome: instance::, } ); -impl frame_support_test::Config for Runtime { - type BlockNumber = BlockNumber; - type AccountId = AccountId; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU32<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type DbWeight = (); + type OnSetCode = (); } impl no_instance::Config for Runtime {} diff --git a/frame/support/test/tests/genesisconfig.rs b/frame/support/test/tests/genesisconfig.rs index 291b250c146b2..c6781220692a9 100644 --- a/frame/support/test/tests/genesisconfig.rs +++ b/frame/support/test/tests/genesisconfig.rs @@ -15,7 +15,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -use sp_core::sr25519; +use frame_support::derive_impl; +use frame_system::pallet_prelude::BlockNumberFor; +use sp_core::{sr25519, ConstU32}; use sp_runtime::{ generic, traits::{BlakeTwo256, Verify}, @@ -25,7 +27,6 @@ use sp_runtime::{ pub mod pallet { use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; #[pallet::pallet] pub struct Pallet(_); @@ -39,11 +40,11 @@ pub mod pallet { #[pallet::storage] #[pallet::unbounded] pub type AppendableDM = - StorageDoubleMap<_, Identity, u32, Identity, T::BlockNumber, Vec>; + StorageDoubleMap<_, Identity, u32, Identity, BlockNumberFor, Vec>; #[pallet::genesis_config] pub struct GenesisConfig { - pub t: Vec<(u32, T::BlockNumber, Vec)>, + pub t: Vec<(u32, BlockNumberFor, Vec)>, } impl Default for GenesisConfig { @@ -53,7 +54,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { for (k1, k2, v) in &self.t { >::insert(k1, k2, v); @@ -71,25 +72,23 @@ pub type Block = generic::Block; frame_support::construct_runtime!( pub enum Test - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + { - System: frame_support_test, + System: frame_system, MyPallet: pallet, } ); -impl frame_support_test::Config for Test { - type BlockNumber = BlockNumber; - type AccountId = AccountId; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU32<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type DbWeight = (); + type OnSetCode = (); } impl pallet::Config for Test {} diff --git a/frame/support/test/tests/instance.rs b/frame/support/test/tests/instance.rs index 28611ddbf599c..2fb6d7658d6ab 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -18,6 +18,7 @@ #![recursion_limit = "128"] use frame_support::{ + derive_impl, inherent::{InherentData, InherentIdentifier, MakeFatalError, ProvideInherent}, metadata_ir::{ PalletStorageMetadataIR, StorageEntryMetadataIR, StorageEntryModifierIR, @@ -25,6 +26,7 @@ use frame_support::{ }, traits::ConstU32, }; +use frame_system::pallet_prelude::BlockNumberFor; use sp_core::sr25519; use sp_runtime::{ generic, @@ -39,10 +41,9 @@ pub trait Currency {} // * Origin, Inherent, Event #[frame_support::pallet(dev_mode)] mod module1 { - use self::frame_system::pallet_prelude::*; use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -77,7 +78,7 @@ mod module1 { #[pallet::genesis_config] pub struct GenesisConfig, I: 'static = ()> { pub value: >::GenericType, - pub test: ::BlockNumber, + pub test: BlockNumberFor, } impl, I: 'static> Default for GenesisConfig { @@ -87,9 +88,9 @@ mod module1 { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig + impl, I: 'static> BuildGenesisConfig for GenesisConfig where - T::BlockNumber: std::fmt::Display, + BlockNumberFor: std::fmt::Display, { fn build(&self) { >::put(self.value.clone()); @@ -123,7 +124,7 @@ mod module1 { #[pallet::inherent] impl, I: 'static> ProvideInherent for Pallet where - T::BlockNumber: From, + BlockNumberFor: From, { type Call = Call; type Error = MakeFatalError<()>; @@ -150,7 +151,6 @@ mod module1 { mod module2 { use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; #[pallet::pallet] pub struct Pallet(PhantomData<(T, I)>); @@ -196,9 +196,9 @@ mod module2 { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig + impl, I: 'static> BuildGenesisConfig for GenesisConfig where - T::BlockNumber: std::fmt::Display, + BlockNumberFor: std::fmt::Display, { fn build(&self) { >::put(self.value.clone()); @@ -252,7 +252,6 @@ mod module2 { mod module3 { use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; #[pallet::pallet] pub struct Pallet(PhantomData<(T, I)>); @@ -277,12 +276,9 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub enum Runtime { - System: frame_support_test::{Pallet, Call, Event}, + System: frame_system::{Pallet, Call, Event}, Module1_1: module1::::{ Pallet, Call, Storage, Event, Config, Origin, Inherent }, @@ -303,15 +299,16 @@ frame_support::construct_runtime!( } ); -impl frame_support_test::Config for Runtime { - type BlockNumber = BlockNumber; - type AccountId = AccountId; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU32<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type DbWeight = (); + type OnSetCode = (); } impl module1::Config for Runtime { diff --git a/frame/support/test/tests/issue2219.rs b/frame/support/test/tests/issue2219.rs index 3822fea030d15..4016707b51a8d 100644 --- a/frame/support/test/tests/issue2219.rs +++ b/frame/support/test/tests/issue2219.rs @@ -15,6 +15,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +use frame_support::derive_impl; +use frame_system::pallet_prelude::BlockNumberFor; use sp_core::{sr25519, ConstU64}; use sp_runtime::{ generic, @@ -25,10 +27,8 @@ use sp_runtime::{ mod module { use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; - pub type Request = - (::AccountId, Role, ::BlockNumber); + pub type Request = (::AccountId, Role, BlockNumberFor); pub type Requests = Vec>; #[derive(Copy, Clone, Eq, PartialEq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)] @@ -46,35 +46,35 @@ mod module { pub max_actors: u32, // payouts are made at this block interval - pub reward_period: T::BlockNumber, + pub reward_period: BlockNumberFor, // minimum amount of time before being able to unstake - pub bonding_period: T::BlockNumber, + pub bonding_period: BlockNumberFor, // how long tokens remain locked for after unstaking - pub unbonding_period: T::BlockNumber, + pub unbonding_period: BlockNumberFor, // minimum period required to be in service. unbonding before this time is highly penalized - pub min_service_period: T::BlockNumber, + pub min_service_period: BlockNumberFor, // "startup" time allowed for roles that need to sync their infrastructure // with other providers before they are considered in service and punishable for // not delivering required level of service. - pub startup_grace_period: T::BlockNumber, + pub startup_grace_period: BlockNumberFor, } impl Default for RoleParameters { fn default() -> Self { Self { max_actors: 10, - reward_period: T::BlockNumber::default(), - unbonding_period: T::BlockNumber::default(), + reward_period: BlockNumberFor::::default(), + unbonding_period: BlockNumberFor::::default(), // not currently used min_actors: 5, - bonding_period: T::BlockNumber::default(), - min_service_period: T::BlockNumber::default(), - startup_grace_period: T::BlockNumber::default(), + bonding_period: BlockNumberFor::::default(), + min_service_period: BlockNumberFor::::default(), + startup_grace_period: BlockNumberFor::::default(), } } } @@ -115,7 +115,7 @@ mod module { /// tokens locked until given block number #[pallet::storage] #[pallet::getter(fn bondage)] - pub type Bondage = StorageMap<_, Blake2_128Concat, T::AccountId, T::BlockNumber>; + pub type Bondage = StorageMap<_, Blake2_128Concat, T::AccountId, BlockNumberFor>; /// First step before enter a role is registering intent with a new account/key. /// This is done by sending a role_entry_request() from the new account. @@ -134,14 +134,16 @@ mod module { pub type RequestLifeTime = StorageValue<_, u64, ValueQuery, ConstU64<0>>; #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig { + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { pub enable_storage_role: bool, pub request_life_time: u64, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { if self.enable_storage_role { >::insert(Role::Storage, >::default()); @@ -159,27 +161,23 @@ pub type Header = generic::Header; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; pub type Block = generic::Block; -impl frame_support_test::Config for Runtime { - type BlockNumber = BlockNumber; - type AccountId = AccountId; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU64<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type DbWeight = (); + type OnSetCode = (); } impl module::Config for Runtime {} frame_support::construct_runtime!( - pub struct Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_support_test, + pub struct Runtime { + System: frame_system, Module: module, } ); @@ -187,7 +185,12 @@ frame_support::construct_runtime!( #[test] fn create_genesis_config() { let config = RuntimeGenesisConfig { - module: module::GenesisConfig { request_life_time: 0, enable_storage_role: true }, + system: Default::default(), + module: module::GenesisConfig { + request_life_time: 0, + enable_storage_role: true, + ..Default::default() + }, }; assert_eq!(config.module.request_life_time, 0); assert!(config.module.enable_storage_role); diff --git a/frame/support/test/tests/origin.rs b/frame/support/test/tests/origin.rs index 47451157b352c..5682bb500c7e3 100644 --- a/frame/support/test/tests/origin.rs +++ b/frame/support/test/tests/origin.rs @@ -19,15 +19,18 @@ #![recursion_limit = "128"] -use frame_support::traits::{Contains, OriginTrait}; +use frame_support::{ + derive_impl, + traits::{Contains, OriginTrait}, +}; +use sp_core::ConstU32; use sp_runtime::{generic, traits::BlakeTwo256}; mod nested { #[frame_support::pallet(dev_mode)] pub mod module { - use self::frame_system::pallet_prelude::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -60,11 +63,14 @@ mod nested { } #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig {} + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, + } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } } @@ -72,9 +78,8 @@ mod nested { #[frame_support::pallet(dev_mode)] pub mod module { - use self::frame_system::pallet_prelude::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -128,11 +133,14 @@ pub mod module { } #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig {} + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, + } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } } @@ -154,26 +162,24 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub enum RuntimeOriginTest where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub enum RuntimeOriginTest { - System: frame_support_test, + System: frame_system, NestedModule: nested::module, Module: module, } ); -impl frame_support_test::Config for RuntimeOriginTest { - type BlockNumber = BlockNumber; - type AccountId = AccountId; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for RuntimeOriginTest { type BaseCallFilter = BaseCallFilter; + type Block = Block; + type BlockHashCount = ConstU32<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type DbWeight = (); + type OnSetCode = (); } impl nested::module::Config for RuntimeOriginTest { diff --git a/frame/support/test/tests/pallet.rs b/frame/support/test/tests/pallet.rs index 5129346acea55..99010ffc8dbdf 100644 --- a/frame/support/test/tests/pallet.rs +++ b/frame/support/test/tests/pallet.rs @@ -402,13 +402,18 @@ pub mod pallet { pub type Unbounded = StorageValue>; #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig { + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig + where + T::AccountId: From + SomeAssociation1 + From, + { + #[serde(skip)] + _config: sp_std::marker::PhantomData, _myfield: u32, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig + impl BuildGenesisConfig for GenesisConfig where T::AccountId: From + SomeAssociation1 + From, { @@ -586,7 +591,7 @@ pub mod pallet2 { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig + impl BuildGenesisConfig for GenesisConfig where T::AccountId: From + SomeAssociation1, { @@ -651,14 +656,13 @@ frame_support::parameter_types!( impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU32<250>; type BlockWeights = (); @@ -704,10 +708,7 @@ pub type UncheckedExtrinsic = sp_runtime::testing::TestXt>; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { // Exclude part `Storage` in order not to check its metadata in tests. System: frame_system exclude_parts { Pallet, Storage }, diff --git a/frame/support/test/tests/pallet_instance.rs b/frame/support/test/tests/pallet_instance.rs index 03dcc455096e9..4ecb9bcb58ae9 100644 --- a/frame/support/test/tests/pallet_instance.rs +++ b/frame/support/test/tests/pallet_instance.rs @@ -185,13 +185,15 @@ pub mod pallet { >; #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig { + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig, I: 'static = ()> { + #[serde(skip)] + _config: sp_std::marker::PhantomData<(T, I)>, _myfield: u32, } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) {} } @@ -281,7 +283,7 @@ pub mod pallet2 { } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) {} } } @@ -289,14 +291,13 @@ pub mod pallet2 { impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU32<250>; type BlockWeights = (); @@ -334,10 +335,7 @@ pub type Block = sp_runtime::generic::Block; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { // Exclude part `Storage` in order not to check its metadata in tests. System: frame_system exclude_parts { Storage }, diff --git a/frame/support/test/tests/pallet_outer_enums_explicit.rs b/frame/support/test/tests/pallet_outer_enums_explicit.rs index dc98ec43fd933..a8250f8b15325 100644 --- a/frame/support/test/tests/pallet_outer_enums_explicit.rs +++ b/frame/support/test/tests/pallet_outer_enums_explicit.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::traits::ConstU32; +use frame_support::{derive_impl, traits::ConstU32}; mod common; @@ -25,31 +25,16 @@ pub type Header = sp_runtime::generic::Header; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU32<10>; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; - type Hash = sp_runtime::testing::H256; - type Hashing = sp_runtime::traits::BlakeTwo256; - type AccountId = u64; - type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; type RuntimeEvent = RuntimeEvent; - type BlockHashCount = ConstU32<250>; - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); type OnSetCode = (); - type MaxConsumers = ConstU32<16>; } impl common::outer_enums::pallet::Config for Runtime { @@ -72,13 +57,10 @@ impl common::outer_enums::pallet3::Config }, + System: frame_system::{Pallet, Config, Call, Event }, // This pallet exposes the Error type explicitly. Example: common::outer_enums::pallet::{Pallet, Config, Event, Error}, diff --git a/frame/support/test/tests/pallet_outer_enums_implicit.rs b/frame/support/test/tests/pallet_outer_enums_implicit.rs index 9a14538c35930..191f095f5d78d 100644 --- a/frame/support/test/tests/pallet_outer_enums_implicit.rs +++ b/frame/support/test/tests/pallet_outer_enums_implicit.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::traits::ConstU32; +use frame_support::{derive_impl, traits::ConstU32}; mod common; @@ -25,31 +25,16 @@ pub type Header = sp_runtime::generic::Header; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU32<10>; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; - type Hash = sp_runtime::testing::H256; - type Hashing = sp_runtime::traits::BlakeTwo256; - type AccountId = u64; - type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; type RuntimeEvent = RuntimeEvent; - type BlockHashCount = ConstU32<250>; - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); type OnSetCode = (); - type MaxConsumers = ConstU32<16>; } impl common::outer_enums::pallet::Config for Runtime { @@ -72,10 +57,7 @@ impl common::outer_enums::pallet3::Config GenesisBuild for GenesisConfig {} + impl BuildGenesisConfig for GenesisConfig {} } fn main() { diff --git a/frame/support/test/tests/pallet_ui/genesis_default_not_satisfied.stderr b/frame/support/test/tests/pallet_ui/genesis_default_not_satisfied.stderr index 04d5b99d0dea5..7245333c9842e 100644 --- a/frame/support/test/tests/pallet_ui/genesis_default_not_satisfied.stderr +++ b/frame/support/test/tests/pallet_ui/genesis_default_not_satisfied.stderr @@ -1,14 +1,14 @@ error[E0277]: the trait bound `pallet::GenesisConfig: std::default::Default` is not satisfied - --> tests/pallet_ui/genesis_default_not_satisfied.rs:22:38 + --> tests/pallet_ui/genesis_default_not_satisfied.rs:22:30 | -22 | impl GenesisBuild for GenesisConfig {} - | ^^^^^^^^^^^^^ the trait `std::default::Default` is not implemented for `pallet::GenesisConfig` +22 | impl BuildGenesisConfig for GenesisConfig {} + | ^^^^^^^^^^^^^ the trait `std::default::Default` is not implemented for `pallet::GenesisConfig` | -note: required by a bound in `GenesisBuild` +note: required by a bound in `BuildGenesisConfig` --> $WORKSPACE/frame/support/src/traits/hooks.rs | - | pub trait GenesisBuild: Default + sp_runtime::traits::MaybeSerializeDeserialize { - | ^^^^^^^ required by this bound in `GenesisBuild` + | pub trait BuildGenesisConfig: Default + sp_runtime::traits::MaybeSerializeDeserialize { + | ^^^^^^^ required by this bound in `BuildGenesisConfig` help: consider annotating `pallet::GenesisConfig` with `#[derive(Default)]` | 19 + #[derive(Default)] diff --git a/frame/support/test/tests/pallet_ui/pallet_doc_arg_non_path.rs b/frame/support/test/tests/pallet_ui/pallet_doc_arg_non_path.rs index ef3097d23007d..32df5d6183653 100644 --- a/frame/support/test/tests/pallet_ui/pallet_doc_arg_non_path.rs +++ b/frame/support/test/tests/pallet_ui/pallet_doc_arg_non_path.rs @@ -5,7 +5,7 @@ mod pallet { #[pallet::config] pub trait Config: frame_system::Config where - ::Index: From, + ::Nonce: From, { } diff --git a/frame/support/test/tests/pallet_ui/pallet_doc_empty.rs b/frame/support/test/tests/pallet_ui/pallet_doc_empty.rs index fe40806d2fa75..6ff01e9fb44b8 100644 --- a/frame/support/test/tests/pallet_ui/pallet_doc_empty.rs +++ b/frame/support/test/tests/pallet_ui/pallet_doc_empty.rs @@ -5,7 +5,7 @@ mod pallet { #[pallet::config] pub trait Config: frame_system::Config where - ::Index: From, + ::Nonce: From, { } diff --git a/frame/support/test/tests/pallet_ui/pallet_doc_invalid_arg.rs b/frame/support/test/tests/pallet_ui/pallet_doc_invalid_arg.rs index 8f0ccb3777a49..c7d3b556a08e2 100644 --- a/frame/support/test/tests/pallet_ui/pallet_doc_invalid_arg.rs +++ b/frame/support/test/tests/pallet_ui/pallet_doc_invalid_arg.rs @@ -5,7 +5,7 @@ mod pallet { #[pallet::config] pub trait Config: frame_system::Config where - ::Index: From, + ::Nonce: From, { } diff --git a/frame/support/test/tests/pallet_ui/pallet_doc_multiple_args.rs b/frame/support/test/tests/pallet_ui/pallet_doc_multiple_args.rs index ffbed9d950799..a799879fe4442 100644 --- a/frame/support/test/tests/pallet_ui/pallet_doc_multiple_args.rs +++ b/frame/support/test/tests/pallet_ui/pallet_doc_multiple_args.rs @@ -5,7 +5,7 @@ mod pallet { #[pallet::config] pub trait Config: frame_system::Config where - ::Index: From, + ::Nonce: From, { } diff --git a/frame/support/test/tests/pallet_ui/pass/dev_mode_valid.rs b/frame/support/test/tests/pallet_ui/pass/dev_mode_valid.rs index 28b901213943c..ed779da80a188 100644 --- a/frame/support/test/tests/pallet_ui/pass/dev_mode_valid.rs +++ b/frame/support/test/tests/pallet_ui/pass/dev_mode_valid.rs @@ -1,10 +1,6 @@ #![cfg_attr(not(feature = "std"), no_std)] -use frame_support::{ - traits::{ - ConstU32, - }, -}; +use frame_support::traits::ConstU32; pub use pallet::*; @@ -60,14 +56,13 @@ pub mod pallet { impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU32<250>; type BlockWeights = (); @@ -89,10 +84,7 @@ pub type Block = sp_runtime::generic::Block; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { // Exclude part `Storage` in order not to check its metadata in tests. System: frame_system exclude_parts { Pallet, Storage }, @@ -100,17 +92,15 @@ frame_support::construct_runtime!( } ); -impl pallet::Config for Runtime { - -} +impl pallet::Config for Runtime {} fn main() { - use frame_support::{pallet_prelude::*}; - use storage::unhashed; + use frame_support::pallet_prelude::*; use sp_io::{ hashing::{blake2_128, twox_128}, TestExternalities, }; + use storage::unhashed; fn blake2_128_concat(d: &[u8]) -> Vec { let mut v = blake2_128(d).to_vec(); diff --git a/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs b/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs index 9c9c49c4b2740..87659a0bab513 100644 --- a/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs +++ b/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs @@ -1,6 +1,6 @@ use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; +use sp_runtime::{generic, traits::BlakeTwo256}; pub type Signature = sr25519::Signature; pub type BlockNumber = u32; @@ -13,14 +13,13 @@ impl test_pallet::Config for Runtime {} impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = frame_support::traits::ConstU32<250>; type BlockWeights = (); @@ -38,13 +37,10 @@ impl frame_system::Config for Runtime { } construct_runtime! { - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub struct Runtime { - System: frame_system::{Pallet, Call, Storage, Config, Event}, - Pallet: test_pallet::{Pallet, Config}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Pallet: test_pallet::{Pallet, Config}, } } diff --git a/frame/support/test/tests/pallet_ui/pass/where_clause_missing_hooks.rs b/frame/support/test/tests/pallet_ui/pass/where_clause_missing_hooks.rs index bf5f22306207a..15fff372a1dd1 100644 --- a/frame/support/test/tests/pallet_ui/pass/where_clause_missing_hooks.rs +++ b/frame/support/test/tests/pallet_ui/pass/where_clause_missing_hooks.rs @@ -1,17 +1,24 @@ #[frame_support::pallet] mod pallet { #[pallet::config] - pub trait Config: frame_system::Config where ::Index: From {} + pub trait Config: frame_system::Config + where + ::Nonce: From, + { + } #[pallet::pallet] pub struct Pallet(core::marker::PhantomData); #[pallet::call] - impl Pallet where ::Index: From {} + impl Pallet where ::Nonce: From {} - impl Pallet where ::Index: From { + impl Pallet + where + ::Nonce: From, + { fn foo(x: u128) { - let _index = ::Index::from(x); + let _index = ::Nonce::from(x); } } } diff --git a/frame/support/test/tests/runtime_metadata.rs b/frame/support/test/tests/runtime_metadata.rs index 70ca307d4428c..50bad87d32eb0 100644 --- a/frame/support/test/tests/runtime_metadata.rs +++ b/frame/support/test/tests/runtime_metadata.rs @@ -25,7 +25,6 @@ use scale_info::{form::MetaForm, meta_type}; use sp_runtime::traits::Block as BlockT; pub type BlockNumber = u64; -pub type Index = u64; pub type Header = sp_runtime::generic::Header; pub type Block = sp_runtime::generic::Block; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; @@ -36,14 +35,13 @@ impl frame_system::Config for Runtime { type DbWeight = (); type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU32<250>; type Version = (); @@ -58,10 +56,7 @@ impl frame_system::Config for Runtime { } frame_support::construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + pub enum Runtime { System: frame_system, } diff --git a/frame/support/test/tests/storage_layers.rs b/frame/support/test/tests/storage_layers.rs index 3e306834869bb..b825c85f9564c 100644 --- a/frame/support/test/tests/storage_layers.rs +++ b/frame/support/test/tests/storage_layers.rs @@ -58,7 +58,7 @@ pub mod pallet { } pub type BlockNumber = u32; -pub type Index = u64; +pub type Nonce = u64; pub type AccountId = u64; pub type Header = sp_runtime::generic::Header; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; @@ -70,13 +70,12 @@ impl frame_system::Config for Runtime { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = Index; - type BlockNumber = BlockNumber; + type Nonce = Nonce; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU32<250>; type DbWeight = (); @@ -94,12 +93,7 @@ impl frame_system::Config for Runtime { impl Config for Runtime {} frame_support::construct_runtime!( - pub struct Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub struct Runtime { System: frame_system, MyPallet: pallet, } diff --git a/frame/support/test/tests/storage_transaction.rs b/frame/support/test/tests/storage_transaction.rs index 5fc4ba7cca6d9..c477433086098 100644 --- a/frame/support/test/tests/storage_transaction.rs +++ b/frame/support/test/tests/storage_transaction.rs @@ -19,12 +19,12 @@ #![allow(deprecated)] use frame_support::{ - assert_noop, assert_ok, assert_storage_noop, + assert_noop, assert_ok, assert_storage_noop, derive_impl, dispatch::DispatchResult, storage::{with_transaction, TransactionOutcome::*}, transactional, }; -use sp_core::sr25519; +use sp_core::{sr25519, ConstU32}; use sp_io::TestExternalities; use sp_runtime::{ generic, @@ -36,10 +36,9 @@ pub use self::pallet::*; #[frame_support::pallet] pub mod pallet { - use self::frame_system::pallet_prelude::*; use super::*; use frame_support::pallet_prelude::*; - use frame_support_test as frame_system; + use frame_system::pallet_prelude::*; #[pallet::pallet] #[pallet::generate_store(pub (super) trait Store)] @@ -82,25 +81,23 @@ pub type Block = generic::Block; frame_support::construct_runtime!( pub enum Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + { - System: frame_support_test, + System: frame_system, MyPallet: pallet, } ); -impl frame_support_test::Config for Runtime { - type BlockNumber = BlockNumber; - type AccountId = AccountId; +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU32<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type DbWeight = (); + type OnSetCode = (); } impl Config for Runtime {} diff --git a/frame/support/test/tests/versioned_runtime_upgrade.rs b/frame/support/test/tests/versioned_runtime_upgrade.rs index f74521f3101da..93d87df8ca185 100644 --- a/frame/support/test/tests/versioned_runtime_upgrade.rs +++ b/frame/support/test/tests/versioned_runtime_upgrade.rs @@ -27,8 +27,9 @@ use frame_support::{ weights::constants::RocksDbWeight, }; use frame_system::Config; +use sp_core::ConstU64; +use sp_runtime::BuildStorage; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; #[frame_support::pallet] @@ -48,11 +49,14 @@ mod dummy_pallet { pub type SomeStorage = StorageValue<_, u32, ValueQuery>; #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig {} + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + _config: sp_std::marker::PhantomData, + } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } } @@ -60,19 +64,18 @@ mod dummy_pallet { impl dummy_pallet::Config for Test {} construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, - DummyPallet: dummy_pallet::{Pallet, Config, Storage} = 1, + System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, + DummyPallet: dummy_pallet::{Pallet, Config, Storage} = 1, } ); #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = ConstU64<10>; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; @@ -81,7 +84,7 @@ impl frame_system::Config for Test { } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext: sp_io::TestExternalities = sp_io::TestExternalities::from(storage); ext.execute_with(|| System::set_block_number(1)); ext diff --git a/frame/system/README.md b/frame/system/README.md index c22b41e42d798..30b2ea73720cf 100644 --- a/frame/system/README.md +++ b/frame/system/README.md @@ -33,7 +33,7 @@ The System module defines the following extensions: - [`CheckWeight`]: Checks the weight and length of the block and ensure that it does not exceed the limits. - [`CheckNonce`]: Checks the nonce of the transaction. Contains a single payload of type - `T::Index`. + `T::Nonce`. - [`CheckEra`]: Checks the era of the transaction. Contains a single payload of type `Era`. - [`CheckGenesis`]: Checks the provided genesis hash of the transaction. Must be a part of the signed payload of the transaction. diff --git a/frame/system/benches/bench.rs b/frame/system/benches/bench.rs index e2fed3e51855d..da8bb10fd4e42 100644 --- a/frame/system/benches/bench.rs +++ b/frame/system/benches/bench.rs @@ -19,11 +19,9 @@ use criterion::{black_box, criterion_group, criterion_main, Criterion}; use frame_support::traits::{ConstU32, ConstU64}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, - Perbill, + BuildStorage, Perbill, }; - #[frame_support::pallet] mod module { use frame_support::pallet_prelude::*; @@ -43,16 +41,12 @@ mod module { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub struct Runtime { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Module: module::{Pallet, Event}, } ); @@ -69,14 +63,13 @@ impl frame_system::Config for Runtime { type BlockLength = BlockLength; type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -95,8 +88,8 @@ impl module::Config for Runtime { } fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default() - .build_storage::() + frame_system::GenesisConfig::::default() + .build_storage() .unwrap() .into() } diff --git a/frame/system/benchmarking/src/mock.rs b/frame/system/benchmarking/src/mock.rs index 8b05c5a8ba82a..4e6b1221da356 100644 --- a/frame/system/benchmarking/src/mock.rs +++ b/frame/system/benchmarking/src/mock.rs @@ -20,22 +20,17 @@ #![cfg(test)] use codec::Encode; -use sp_runtime::traits::IdentityLookup; +use sp_runtime::{traits::IdentityLookup, BuildStorage}; type AccountId = u64; -type AccountIndex = u32; -type BlockNumber = u64; +type Nonce = u32; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, } ); @@ -45,14 +40,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = AccountIndex; - type BlockNumber = BlockNumber; + type Nonce = Nonce; type RuntimeCall = RuntimeCall; type Hash = sp_core::H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = sp_runtime::testing::Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = (); type Version = (); @@ -81,7 +75,7 @@ impl sp_core::traits::ReadRuntimeVersion for MockedReadRuntimeVersion { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let version = sp_version::RuntimeVersion { spec_name: "spec_name".into(), diff --git a/frame/system/rpc/runtime-api/src/lib.rs b/frame/system/rpc/runtime-api/src/lib.rs index 2ea9f2f62e11c..f59988d818f07 100644 --- a/frame/system/rpc/runtime-api/src/lib.rs +++ b/frame/system/rpc/runtime-api/src/lib.rs @@ -24,12 +24,12 @@ #![cfg_attr(not(feature = "std"), no_std)] sp_api::decl_runtime_apis! { - /// The API to query account nonce (aka transaction index). - pub trait AccountNonceApi where + /// The API to query account nonce. + pub trait AccountNonceApi where AccountId: codec::Codec, - Index: codec::Codec, + Nonce: codec::Codec, { /// Get current account nonce of given `AccountId`. - fn account_nonce(account: AccountId) -> Index; + fn account_nonce(account: AccountId) -> Nonce; } } diff --git a/frame/system/src/extensions/check_genesis.rs b/frame/system/src/extensions/check_genesis.rs index 5964ec452842f..76a711a823e7d 100644 --- a/frame/system/src/extensions/check_genesis.rs +++ b/frame/system/src/extensions/check_genesis.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{Config, Pallet}; +use crate::{pallet_prelude::BlockNumberFor, Config, Pallet}; use codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime::{ @@ -60,7 +60,7 @@ impl SignedExtension for CheckGenesis { const IDENTIFIER: &'static str = "CheckGenesis"; fn additional_signed(&self) -> Result { - Ok(>::block_hash(T::BlockNumber::zero())) + Ok(>::block_hash(BlockNumberFor::::zero())) } fn pre_dispatch( diff --git a/frame/system/src/extensions/check_mortality.rs b/frame/system/src/extensions/check_mortality.rs index 23c357d481350..148dfd4aad471 100644 --- a/frame/system/src/extensions/check_mortality.rs +++ b/frame/system/src/extensions/check_mortality.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{BlockHash, Config, Pallet}; +use crate::{pallet_prelude::BlockNumberFor, BlockHash, Config, Pallet}; use codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime::{ @@ -78,7 +78,7 @@ impl SignedExtension for CheckMortality { fn additional_signed(&self) -> Result { let current_u64 = >::block_number().saturated_into::(); - let n = self.0.birth(current_u64).saturated_into::(); + let n = self.0.birth(current_u64).saturated_into::>(); if !>::contains_key(n) { Err(InvalidTransaction::AncientBirthBlock.into()) } else { diff --git a/frame/system/src/extensions/check_nonce.rs b/frame/system/src/extensions/check_nonce.rs index 57ebd7701ef6a..2939fd6534c09 100644 --- a/frame/system/src/extensions/check_nonce.rs +++ b/frame/system/src/extensions/check_nonce.rs @@ -37,11 +37,11 @@ use sp_std::vec; /// some kind of priority upon validating transactions. #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] #[scale_info(skip_type_params(T))] -pub struct CheckNonce(#[codec(compact)] pub T::Index); +pub struct CheckNonce(#[codec(compact)] pub T::Nonce); impl CheckNonce { /// utility constructor. Used only in client/factory code. - pub fn from(nonce: T::Index) -> Self { + pub fn from(nonce: T::Nonce) -> Self { Self(nonce) } } @@ -88,7 +88,7 @@ where } .into()) } - account.nonce += T::Index::one(); + account.nonce += T::Nonce::one(); crate::Account::::insert(who, account); Ok(()) } diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index cbda3d55cc68c..cdd9f7630818a 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -50,7 +50,7 @@ //! - [`CheckWeight`]: Checks the weight and length of the block and ensure that it does not //! exceed the limits. //! - [`CheckNonce`]: Checks the nonce of the transaction. Contains a single payload of type -//! `T::Index`. +//! `T::Nonce`. //! - [`CheckEra`]: Checks the era of the transaction. Contains a single payload of type `Era`. //! - [`CheckGenesis`]: Checks the provided genesis hash of the transaction. Must be a part of the //! signed payload of the transaction. @@ -64,6 +64,7 @@ #![cfg_attr(not(feature = "std"), no_std)] +use pallet_prelude::{BlockNumberFor, HeaderFor}; #[cfg(feature = "std")] use serde::Serialize; use sp_io::hashing::blake2_256; @@ -72,9 +73,9 @@ use sp_runtime::traits::TrailingZeroInput; use sp_runtime::{ generic, traits::{ - self, AtLeast32Bit, AtLeast32BitUnsigned, BadOrigin, BlockNumberProvider, Bounded, - CheckEqual, Dispatchable, Hash, Lookup, LookupError, MaybeDisplay, - MaybeSerializeDeserialize, Member, One, Saturating, SimpleBitOps, StaticLookup, Zero, + self, AtLeast32Bit, BadOrigin, BlockNumberProvider, Bounded, CheckEqual, Dispatchable, + Hash, Header, Lookup, LookupError, MaybeDisplay, MaybeSerializeDeserialize, Member, One, + Saturating, SimpleBitOps, StaticLookup, Zero, }, DispatchError, RuntimeDebug, }; @@ -84,6 +85,8 @@ use sp_std::{fmt::Debug, marker::PhantomData, prelude::*}; use sp_version::RuntimeVersion; use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen}; +#[cfg(feature = "std")] +use frame_support::traits::BuildGenesisConfig; use frame_support::{ dispatch::{ extract_actual_pays_fee, extract_actual_weight, DispatchClass, DispatchInfo, @@ -101,8 +104,6 @@ use scale_info::TypeInfo; use sp_core::storage::well_known_keys; use sp_weights::{RuntimeDbWeight, Weight}; -#[cfg(feature = "std")] -use frame_support::traits::GenesisBuild; #[cfg(any(feature = "std", test))] use sp_io::TestExternalities; @@ -216,14 +217,11 @@ pub mod pallet { #[frame_support::register_default_impl(TestDefaultConfig)] impl DefaultConfig for TestDefaultConfig { - type Index = u32; - type BlockNumber = u32; - type Header = sp_runtime::generic::Header; + type Nonce = u32; type Hash = sp_core::hash::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; - type BlockHashCount = frame_support::traits::ConstU32<10>; type MaxConsumers = frame_support::traits::ConstU32<16>; type AccountData = (); type OnNewAccount = (); @@ -275,9 +273,8 @@ pub mod pallet { + Debug + From>; - /// Account index (aka nonce) type. This stores the number of previous transactions - /// associated with a sender account. - type Index: Parameter + /// This stores the number of previous transactions associated with a sender account. + type Nonce: Parameter + Member + MaybeSerializeDeserialize + Debug @@ -287,21 +284,6 @@ pub mod pallet { + Copy + MaxEncodedLen; - /// The block number type used by the runtime. - type BlockNumber: Parameter - + Member - + MaybeSerializeDeserialize - + Debug - + MaybeDisplay - + AtLeast32BitUnsigned - + Default - + Bounded - + Copy - + sp_std::hash::Hash - + sp_std::str::FromStr - + MaxEncodedLen - + TypeInfo; - /// The output of the `Hashing` function. type Hash: Parameter + Member @@ -338,12 +320,15 @@ pub mod pallet { /// functional/efficient alternatives. type Lookup: StaticLookup; - /// The block header. - type Header: Parameter + traits::Header; + /// The Block type used by the runtime. This is used by `construct_runtime` to retrieve the + /// extrinsics or other block specific data as needed. + #[pallet::no_default] + type Block: Parameter + Member + traits::Block; /// Maximum number of block number to block hash mappings to keep (oldest pruned first). #[pallet::constant] - type BlockHashCount: Get; + #[pallet::no_default] + type BlockHashCount: Get>; /// The weight of runtime database operations the runtime can invoke. #[pallet::constant] @@ -568,7 +553,7 @@ pub mod pallet { _, Blake2_128Concat, T::AccountId, - AccountInfo, + AccountInfo, ValueQuery, >; @@ -590,7 +575,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn block_hash)] pub type BlockHash = - StorageMap<_, Twox64Concat, T::BlockNumber, T::Hash, ValueQuery>; + StorageMap<_, Twox64Concat, BlockNumberFor, T::Hash, ValueQuery>; /// Extrinsics data for the current block (maps an extrinsic's index to its data). #[pallet::storage] @@ -603,7 +588,7 @@ pub mod pallet { #[pallet::storage] #[pallet::whitelist_storage] #[pallet::getter(fn block_number)] - pub(super) type Number = StorageValue<_, T::BlockNumber, ValueQuery>; + pub(super) type Number = StorageValue<_, BlockNumberFor, ValueQuery>; /// Hash of the previous block. #[pallet::storage] @@ -642,14 +627,14 @@ pub mod pallet { /// allows light-clients to leverage the changes trie storage tracking mechanism and /// in case of changes fetch the list of events of interest. /// - /// The value has the type `(T::BlockNumber, EventIndex)` because if we used only just + /// The value has the type `(BlockNumberFor, EventIndex)` because if we used only just /// the `EventIndex` then in case if the topic has the same contents on the next block /// no notification will be triggered thus the event might be lost. #[pallet::storage] #[pallet::unbounded] #[pallet::getter(fn event_topics)] pub(super) type EventTopics = - StorageMap<_, Blake2_128Concat, T::Hash, Vec<(T::BlockNumber, EventIndex)>, ValueQuery>; + StorageMap<_, Blake2_128Concat, T::Hash, Vec<(BlockNumberFor, EventIndex)>, ValueQuery>; /// Stores the `spec_version` and `spec_name` of when the last runtime upgrade happened. #[pallet::storage] @@ -670,17 +655,19 @@ pub mod pallet { #[pallet::whitelist_storage] pub(super) type ExecutionPhase = StorageValue<_, Phase>; - #[derive(Default)] + #[derive(frame_support::DefaultNoBound)] #[pallet::genesis_config] - pub struct GenesisConfig { + pub struct GenesisConfig { #[serde(with = "sp_core::bytes")] pub code: Vec, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { - >::insert::<_, T::Hash>(T::BlockNumber::zero(), hash69()); + >::insert::<_, T::Hash>(BlockNumberFor::::zero(), hash69()); >::put::(hash69()); >::put(LastRuntimeUpgradeInfo::from(T::Version::get())); >::put(true); @@ -692,26 +679,6 @@ pub mod pallet { } } -#[cfg(feature = "std")] -impl GenesisConfig { - /// Direct implementation of `GenesisBuild::build_storage`. - /// - /// Kept in order not to break dependency. - pub fn build_storage(&self) -> Result { - >::build_storage(self) - } - - /// Direct implementation of `GenesisBuild::assimilate_storage`. - /// - /// Kept in order not to break dependency. - pub fn assimilate_storage( - &self, - storage: &mut sp_runtime::Storage, - ) -> Result<(), String> { - >::assimilate_storage(self, storage) - } -} - pub type Key = Vec; pub type KeyValue = (Vec, Vec); @@ -764,9 +731,9 @@ pub type RefCount = u32; /// Information of an account. #[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct AccountInfo { +pub struct AccountInfo { /// The number of transactions this account has sent. - pub nonce: Index, + pub nonce: Nonce, /// The number of other modules that currently depend on this account's existence. The account /// cannot be reaped until this is zero. pub consumers: RefCount, @@ -1388,7 +1355,7 @@ impl Pallet { } /// Start the execution of a particular block. - pub fn initialize(number: &T::BlockNumber, parent_hash: &T::Hash, digest: &generic::Digest) { + pub fn initialize(number: &BlockNumberFor, parent_hash: &T::Hash, digest: &generic::Digest) { // populate environment ExecutionPhase::::put(Phase::Initialization); storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32); @@ -1405,7 +1372,7 @@ impl Pallet { /// Remove temporary "environment" entries in storage, compute the storage root and return the /// resulting header for this block. - pub fn finalize() -> T::Header { + pub fn finalize() -> HeaderFor { log::debug!( target: LOG_TARGET, "[{:?}] {} extrinsics, length: {} (normal {}%, op: {}%, mandatory {}%) / normal weight:\ @@ -1477,13 +1444,7 @@ impl Pallet { let storage_root = T::Hash::decode(&mut &sp_io::storage::root(version)[..]) .expect("Node is configured to use the same hash; qed"); - ::new( - number, - extrinsics_root, - storage_root, - parent_hash, - digest, - ) + HeaderFor::::new(number, extrinsics_root, storage_root, parent_hash, digest) } /// Deposits a log and ensures it matches the block's log data. @@ -1496,8 +1457,8 @@ impl Pallet { pub fn externalities() -> TestExternalities { TestExternalities::new(sp_core::storage::Storage { top: map![ - >::hashed_key_for(T::BlockNumber::zero()) => [69u8; 32].encode(), - >::hashed_key().to_vec() => T::BlockNumber::one().encode(), + >::hashed_key_for(BlockNumberFor::::zero()) => [69u8; 32].encode(), + >::hashed_key().to_vec() => BlockNumberFor::::one().encode(), >::hashed_key().to_vec() => [69u8; 32].encode() ], children_default: map![], @@ -1542,7 +1503,7 @@ impl Pallet { /// Set the block number to something in particular. Can be used as an alternative to /// `initialize` for tests that don't need to bother with the other environment entries. #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))] - pub fn set_block_number(n: T::BlockNumber) { + pub fn set_block_number(n: BlockNumberFor) { >::put(n); } @@ -1608,13 +1569,13 @@ impl Pallet { } /// Retrieve the account transaction counter from storage. - pub fn account_nonce(who: impl EncodeLike) -> T::Index { + pub fn account_nonce(who: impl EncodeLike) -> T::Nonce { Account::::get(who).nonce } /// Increment a particular account's nonce by 1. pub fn inc_account_nonce(who: impl EncodeLike) { - Account::::mutate(who, |a| a.nonce += T::Index::one()); + Account::::mutate(who, |a| a.nonce += T::Nonce::one()); } /// Note what the extrinsic data of the current extrinsic index is. @@ -1670,7 +1631,7 @@ impl Pallet { } /// An account is being created. - pub fn on_created_account(who: T::AccountId, _a: &mut AccountInfo) { + pub fn on_created_account(who: T::AccountId, _a: &mut AccountInfo) { T::OnNewAccount::on_new_account(&who); Self::deposit_event(Event::NewAccount { account: who }); } @@ -1760,7 +1721,7 @@ impl HandleLifetime for Consumer { } impl BlockNumberProvider for Pallet { - type BlockNumber = ::BlockNumber; + type BlockNumber = BlockNumberFor; fn current_block_number() -> Self::BlockNumber { Pallet::::block_number() @@ -1831,6 +1792,10 @@ pub mod pallet_prelude { /// Type alias for the `Origin` associated type of system config. pub type OriginFor = ::RuntimeOrigin; + /// Type alias for the `Header`. + pub type HeaderFor = + <::Block as sp_runtime::traits::HeaderProvider>::HeaderT; + /// Type alias for the `BlockNumber` associated type of system config. - pub type BlockNumberFor = ::BlockNumber; + pub type BlockNumberFor = as sp_runtime::traits::Header>::Number; } diff --git a/frame/system/src/migrations/mod.rs b/frame/system/src/migrations/mod.rs index f8ebfab33b891..6f873061dbab9 100644 --- a/frame/system/src/migrations/mod.rs +++ b/frame/system/src/migrations/mod.rs @@ -31,8 +31,8 @@ type RefCount = u32; /// Information of an account. #[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] -struct AccountInfo { - nonce: Index, +struct AccountInfo { + nonce: Nonce, consumers: RefCount, providers: RefCount, sufficients: RefCount, @@ -47,8 +47,8 @@ pub trait V2ToV3 { /// System config account id type AccountId: 'static + FullCodec; - /// System config index - type Index: 'static + FullCodec + Copy; + /// System config nonce + type Nonce: 'static + FullCodec + Copy; /// System config account data type AccountData: 'static + FullCodec; @@ -65,13 +65,13 @@ type Account = StorageMap< Pallet, Blake2_128Concat, ::AccountId, - AccountInfo<::Index, ::AccountData>, + AccountInfo<::Nonce, ::AccountData>, >; /// Migrate from unique `u8` reference counting to triple `u32` reference counting. pub fn migrate_from_single_u8_to_triple_ref_count() -> Weight { let mut translated: usize = 0; - >::translate::<(V::Index, u8, V::AccountData), _>(|_key, (nonce, rc, data)| { + >::translate::<(V::Nonce, u8, V::AccountData), _>(|_key, (nonce, rc, data)| { translated += 1; Some(AccountInfo { nonce, consumers: rc as RefCount, providers: 1, sufficients: 0, data }) }); @@ -88,7 +88,7 @@ pub fn migrate_from_single_u8_to_triple_ref_count() -> Wei /// Migrate from unique `u32` reference counting to triple `u32` reference counting. pub fn migrate_from_single_to_triple_ref_count() -> Weight { let mut translated: usize = 0; - >::translate::<(V::Index, RefCount, V::AccountData), _>( + >::translate::<(V::Nonce, RefCount, V::AccountData), _>( |_key, (nonce, consumers, data)| { translated += 1; Some(AccountInfo { nonce, consumers, providers: 1, sufficients: 0, data }) @@ -106,7 +106,7 @@ pub fn migrate_from_single_to_triple_ref_count() -> Weight /// Migrate from dual `u32` reference counting to triple `u32` reference counting. pub fn migrate_from_dual_to_triple_ref_count() -> Weight { let mut translated: usize = 0; - >::translate::<(V::Index, RefCount, RefCount, V::AccountData), _>( + >::translate::<(V::Nonce, RefCount, RefCount, V::AccountData), _>( |_key, (nonce, consumers, providers, data)| { translated += 1; Some(AccountInfo { nonce, consumers, providers, sufficients: 0, data }) diff --git a/frame/system/src/mock.rs b/frame/system/src/mock.rs index b484c22ad4fe4..c016ea9e1cd14 100644 --- a/frame/system/src/mock.rs +++ b/frame/system/src/mock.rs @@ -22,21 +22,16 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, Perbill, }; -type UncheckedExtrinsic = mocking::MockUncheckedExtrinsic; type Block = mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, } ); @@ -96,13 +91,12 @@ impl Config for Test { type BlockLength = RuntimeBlockLength; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<10>; type DbWeight = DbWeight; diff --git a/frame/system/src/mocking.rs b/frame/system/src/mocking.rs index 8f76c1b8e08ba..833309e05ecc9 100644 --- a/frame/system/src/mocking.rs +++ b/frame/system/src/mocking.rs @@ -29,6 +29,19 @@ pub type MockUncheckedExtrinsic = generic::Unchec /// An implementation of `sp_runtime::traits::Block` to be used in tests. pub type MockBlock = generic::Block< - generic::Header<::BlockNumber, sp_runtime::traits::BlakeTwo256>, + generic::Header, + MockUncheckedExtrinsic, +>; + +/// An implementation of `sp_runtime::traits::Block` to be used in tests with u32 BlockNumber type. +pub type MockBlockU32 = generic::Block< + generic::Header, + MockUncheckedExtrinsic, +>; + +/// An implementation of `sp_runtime::traits::Block` to be used in tests with u128 BlockNumber +/// type. +pub type MockBlockU128 = generic::Block< + generic::Header, MockUncheckedExtrinsic, >; diff --git a/frame/system/src/offchain.rs b/frame/system/src/offchain.rs index 742146d1642c8..313a557c44d76 100644 --- a/frame/system/src/offchain.rs +++ b/frame/system/src/offchain.rs @@ -486,7 +486,7 @@ pub trait CreateSignedTransaction: call: Self::OverarchingCall, public: Self::Public, account: Self::AccountId, - nonce: Self::Index, + nonce: Self::Nonce, ) -> Option<(Self::OverarchingCall, ::SignaturePayload)>; } diff --git a/frame/timestamp/src/lib.rs b/frame/timestamp/src/lib.rs index e707764beb95c..4eb95941d7828 100644 --- a/frame/timestamp/src/lib.rs +++ b/frame/timestamp/src/lib.rs @@ -130,7 +130,7 @@ pub mod pallet { type Moment: Parameter + Default + AtLeast32Bit - + Scale + + Scale, Output = Self::Moment> + Copy + MaxEncodedLen + scale_info::StaticTypeInfo; diff --git a/frame/timestamp/src/mock.rs b/frame/timestamp/src/mock.rs index 6f681788236c3..418d257b3f005 100644 --- a/frame/timestamp/src/mock.rs +++ b/frame/timestamp/src/mock.rs @@ -27,21 +27,17 @@ use frame_support::{ use sp_core::H256; use sp_io::TestExternalities; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type Moment = u64; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, } ); @@ -52,14 +48,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -100,7 +95,7 @@ pub(crate) fn get_captured_moment() -> Option { } pub(crate) fn new_test_ext() -> TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); clear_captured_moment(); TestExternalities::new(t) } diff --git a/frame/tips/src/benchmarking.rs b/frame/tips/src/benchmarking.rs index 613f684afdf56..4a991b11b9331 100644 --- a/frame/tips/src/benchmarking.rs +++ b/frame/tips/src/benchmarking.rs @@ -78,7 +78,7 @@ fn create_tips, I: 'static>( } Tips::::mutate(hash, |maybe_tip| { if let Some(open_tip) = maybe_tip { - open_tip.closes = Some(T::BlockNumber::zero()); + open_tip.closes = Some(frame_system::pallet_prelude::BlockNumberFor::::zero()); } }); Ok(()) diff --git a/frame/tips/src/lib.rs b/frame/tips/src/lib.rs index 970e2ac152c4b..6e8f72e0540e6 100644 --- a/frame/tips/src/lib.rs +++ b/frame/tips/src/lib.rs @@ -74,6 +74,7 @@ use frame_support::{ }, Parameter, }; +use frame_system::pallet_prelude::BlockNumberFor; pub use pallet::*; pub use weights::WeightInfo; @@ -143,7 +144,7 @@ pub mod pallet { /// The period for which a tip remains open after is has achieved threshold tippers. #[pallet::constant] - type TipCountdown: Get; + type TipCountdown: Get>; /// The percent of the final tip which goes to the original reporter of the tip. #[pallet::constant] @@ -173,7 +174,7 @@ pub mod pallet { _, Twox64Concat, T::Hash, - OpenTip, T::BlockNumber, T::Hash>, + OpenTip, BlockNumberFor, T::Hash>, OptionQuery, >; @@ -470,7 +471,7 @@ impl, I: 'static> Pallet { /// /// `O(T)` and one storage access. fn insert_tip_and_check_closing( - tip: &mut OpenTip, T::BlockNumber, T::Hash>, + tip: &mut OpenTip, BlockNumberFor, T::Hash>, tipper: T::AccountId, tip_value: BalanceOf, ) -> bool { @@ -515,7 +516,7 @@ impl, I: 'static> Pallet { /// Plus `O(T)` (`T` is Tippers length). fn payout_tip( hash: T::Hash, - tip: OpenTip, T::BlockNumber, T::Hash>, + tip: OpenTip, BlockNumberFor, T::Hash>, ) { let mut tips = tip.tips; Self::retain_active_tips(&mut tips); @@ -577,7 +578,7 @@ impl, I: 'static> Pallet { for (hash, old_tip) in storage_key_iter::< T::Hash, - OldOpenTip, T::BlockNumber, T::Hash>, + OldOpenTip, BlockNumberFor, T::Hash>, Twox64Concat, >(module, item) .drain() diff --git a/frame/tips/src/tests.rs b/frame/tips/src/tests.rs index 25043b413db07..a700892d42703 100644 --- a/frame/tips/src/tests.rs +++ b/frame/tips/src/tests.rs @@ -21,16 +21,13 @@ use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, IdentityLookup}, BuildStorage, Perbill, Permill, }; use sp_storage::Storage; use frame_support::{ - assert_noop, assert_ok, - pallet_prelude::GenesisBuild, - parameter_types, + assert_noop, assert_ok, parameter_types, storage::StoragePrefixedMap, traits::{ConstU32, ConstU64, SortedMembers, StorageVersion}, PalletId, @@ -39,19 +36,15 @@ use frame_support::{ use super::*; use crate::{self as pallet_tips, Event as TipEvent}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event}, - Treasury1: pallet_treasury::::{Pallet, Call, Storage, Config, Event}, + Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event}, + Treasury1: pallet_treasury::::{Pallet, Call, Storage, Config, Event}, Tips: pallet_tips::{Pallet, Call, Storage, Event}, Tips1: pallet_tips::::{Pallet, Call, Storage, Event}, } @@ -66,14 +59,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u128; // u64 is not enough to hold bytes used to generate bounty account type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -570,7 +562,7 @@ fn test_migration_v4() { #[test] fn genesis_funding_works() { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let initial_funding = 100; pallet_balances::GenesisConfig:: { // Total issuance will be 200 with treasury account initialized with 100. @@ -578,7 +570,9 @@ fn genesis_funding_works() { } .assimilate_storage(&mut t) .unwrap(); - GenesisBuild::::assimilate_storage(&pallet_treasury::GenesisConfig, &mut t).unwrap(); + pallet_treasury::GenesisConfig::::default() + .assimilate_storage(&mut t) + .unwrap(); let mut t: sp_io::TestExternalities = t.into(); t.execute_with(|| { diff --git a/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs b/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs index 6e05ec6163ddb..bfbe8b4178cee 100644 --- a/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs +++ b/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs @@ -33,21 +33,16 @@ use pallet_asset_conversion::{NativeOrAssetId, NativeOrAssetIdConverter}; use pallet_transaction_payment::CurrencyAdapter; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{AccountIdConversion, BlakeTwo256, IdentityLookup, SaturatedConversion}, Permill, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type Balance = u64; type AccountId = u64; frame_support::construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Runtime { System: system, Balances: pallet_balances, @@ -89,14 +84,13 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/transaction-payment/asset-conversion-tx-payment/src/tests.rs b/frame/transaction-payment/asset-conversion-tx-payment/src/tests.rs index 7cd22e305831b..9e9b74a0ddb2e 100644 --- a/frame/transaction-payment/asset-conversion-tx-payment/src/tests.rs +++ b/frame/transaction-payment/asset-conversion-tx-payment/src/tests.rs @@ -26,7 +26,7 @@ use frame_system as system; use mock::{ExtrinsicBaseWeight, *}; use pallet_asset_conversion::NativeOrAssetId; use pallet_balances::Call as BalancesCall; -use sp_runtime::traits::StaticLookup; +use sp_runtime::{traits::StaticLookup, BuildStorage}; const CALL: &::RuntimeCall = &RuntimeCall::Balances(BalancesCall::transfer_allow_death { dest: 2, value: 69 }); @@ -65,7 +65,7 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { self.set_constants(); - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: if self.balance_factor > 0 { vec![ diff --git a/frame/transaction-payment/asset-tx-payment/src/mock.rs b/frame/transaction-payment/asset-tx-payment/src/mock.rs index 740915023a32d..b8d7b523ca258 100644 --- a/frame/transaction-payment/asset-tx-payment/src/mock.rs +++ b/frame/transaction-payment/asset-tx-payment/src/mock.rs @@ -29,23 +29,14 @@ use frame_system as system; use frame_system::EnsureRoot; use pallet_transaction_payment::CurrencyAdapter; use sp_core::H256; -use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, ConvertInto, IdentityLookup, SaturatedConversion}, -}; +use sp_runtime::traits::{BlakeTwo256, ConvertInto, IdentityLookup, SaturatedConversion}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type Balance = u64; type AccountId = u64; frame_support::construct_runtime!( - pub struct Runtime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub struct Runtime { System: system, Balances: pallet_balances, TransactionPayment: pallet_transaction_payment, @@ -85,14 +76,13 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/transaction-payment/asset-tx-payment/src/tests.rs b/frame/transaction-payment/asset-tx-payment/src/tests.rs index 2fee9c849f4b4..8df98ceda9971 100644 --- a/frame/transaction-payment/asset-tx-payment/src/tests.rs +++ b/frame/transaction-payment/asset-tx-payment/src/tests.rs @@ -25,7 +25,7 @@ use frame_support::{ use frame_system as system; use mock::{ExtrinsicBaseWeight, *}; use pallet_balances::Call as BalancesCall; -use sp_runtime::traits::StaticLookup; +use sp_runtime::{traits::StaticLookup, BuildStorage}; const CALL: &::RuntimeCall = &RuntimeCall::Balances(BalancesCall::transfer_allow_death { dest: 2, value: 69 }); @@ -64,7 +64,7 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { self.set_constants(); - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: if self.balance_factor > 0 { vec![ diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 1ea2dc9f33ebb..d61be5540c3a4 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -380,18 +380,20 @@ pub mod pallet { pub(super) type StorageVersion = StorageValue<_, Releases, ValueQuery>; #[pallet::genesis_config] - pub struct GenesisConfig { + pub struct GenesisConfig { pub multiplier: Multiplier, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } - impl Default for GenesisConfig { + impl Default for GenesisConfig { fn default() -> Self { - Self { multiplier: MULTIPLIER_DEFAULT_VALUE } + Self { multiplier: MULTIPLIER_DEFAULT_VALUE, _config: Default::default() } } } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { StorageVersion::::put(Releases::V2); NextFeeMultiplier::::put(self.multiplier); @@ -408,7 +410,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_finalize(_: T::BlockNumber) { + fn on_finalize(_: frame_system::pallet_prelude::BlockNumberFor) { >::mutate(|fm| { *fm = T::FeeMultiplierUpdate::convert(*fm); }); diff --git a/frame/transaction-payment/src/mock.rs b/frame/transaction-payment/src/mock.rs index 28d57065eca18..97253be463058 100644 --- a/frame/transaction-payment/src/mock.rs +++ b/frame/transaction-payment/src/mock.rs @@ -19,10 +19,7 @@ use super::*; use crate as pallet_transaction_payment; use sp_core::H256; -use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, IdentityLookup}, -}; +use sp_runtime::traits::{BlakeTwo256, IdentityLookup}; use frame_support::{ dispatch::DispatchClass, @@ -33,16 +30,12 @@ use frame_support::{ use frame_system as system; use pallet_balances::Call as BalancesCall; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub struct Runtime { - System: system::{Pallet, Call, Config, Storage, Event}, + System: system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event}, } @@ -82,14 +75,13 @@ impl frame_system::Config for Runtime { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/frame/transaction-payment/src/tests.rs b/frame/transaction-payment/src/tests.rs index d5109609e2975..d3a1721ccb990 100644 --- a/frame/transaction-payment/src/tests.rs +++ b/frame/transaction-payment/src/tests.rs @@ -20,12 +20,14 @@ use crate as pallet_transaction_payment; use codec::Encode; -use sp_runtime::{testing::TestXt, traits::One, transaction_validity::InvalidTransaction}; +use sp_runtime::{ + testing::TestXt, traits::One, transaction_validity::InvalidTransaction, BuildStorage, +}; use frame_support::{ assert_noop, assert_ok, dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, PostDispatchInfo}, - traits::{Currency, GenesisBuild}, + traits::Currency, weights::Weight, }; use frame_system as system; @@ -80,7 +82,7 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { self.set_constants(); - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: if self.balance_factor > 0 { vec![ @@ -99,8 +101,9 @@ impl ExtBuilder { .unwrap(); if let Some(multiplier) = self.initial_multiplier { - let genesis = pallet::GenesisConfig { multiplier }; - GenesisBuild::::assimilate_storage(&genesis, &mut t).unwrap(); + pallet::GenesisConfig:: { multiplier, ..Default::default() } + .assimilate_storage(&mut t) + .unwrap(); } t.into() diff --git a/frame/transaction-storage/src/benchmarking.rs b/frame/transaction-storage/src/benchmarking.rs index dfea3331569f9..fdbaeb1f95181 100644 --- a/frame/transaction-storage/src/benchmarking.rs +++ b/frame/transaction-storage/src/benchmarking.rs @@ -22,7 +22,7 @@ use super::*; use frame_benchmarking::v1::{benchmarks, whitelisted_caller}; use frame_support::traits::{Currency, Get, OnFinalize, OnInitialize}; -use frame_system::{EventRecord, Pallet as System, RawOrigin}; +use frame_system::{pallet_prelude::BlockNumberFor, EventRecord, Pallet as System, RawOrigin}; use sp_runtime::traits::{Bounded, One, Zero}; use sp_std::*; use sp_transaction_storage_proof::TransactionStorageProof; @@ -113,7 +113,7 @@ fn assert_last_event(generic_event: ::RuntimeEvent) { assert_eq!(event, &system_event); } -pub fn run_to_block(n: T::BlockNumber) { +pub fn run_to_block(n: frame_system::pallet_prelude::BlockNumberFor) { while frame_system::Pallet::::block_number() < n { crate::Pallet::::on_finalize(frame_system::Pallet::::block_number()); frame_system::Pallet::::on_finalize(frame_system::Pallet::::block_number()); @@ -144,7 +144,7 @@ benchmarks! { vec![0u8; T::MaxTransactionSize::get() as usize], )?; run_to_block::(1u32.into()); - }: _(RawOrigin::Signed(caller.clone()), T::BlockNumber::zero(), 0) + }: _(RawOrigin::Signed(caller.clone()), BlockNumberFor::::zero(), 0) verify { assert_last_event::(Event::Renewed { index: 0 }.into()); } @@ -159,7 +159,7 @@ benchmarks! { vec![0u8; T::MaxTransactionSize::get() as usize], )?; } - run_to_block::(StoragePeriod::::get() + T::BlockNumber::one()); + run_to_block::(StoragePeriod::::get() + BlockNumberFor::::one()); let encoded_proof = proof(); let proof = TransactionStorageProof::decode(&mut &*encoded_proof).unwrap(); }: check_proof(RawOrigin::None, proof) diff --git a/frame/transaction-storage/src/lib.rs b/frame/transaction-storage/src/lib.rs index b99bc49fc5b6f..e784d20a0cfd7 100644 --- a/frame/transaction-storage/src/lib.rs +++ b/frame/transaction-storage/src/lib.rs @@ -145,7 +145,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: BlockNumberFor) -> Weight { // Drop obsolete roots. The proof for `obsolete` will be checked later // in this block, so we drop `obsolete` - 1. let period = >::get(); @@ -158,7 +158,7 @@ pub mod pallet { T::DbWeight::get().reads_writes(2, 4) } - fn on_finalize(n: T::BlockNumber) { + fn on_finalize(n: BlockNumberFor) { assert!( >::take() || { // Proof is not required for early or empty blocks. @@ -238,7 +238,7 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::renew())] pub fn renew( origin: OriginFor, - block: T::BlockNumber, + block: BlockNumberFor, index: u32, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; @@ -342,7 +342,7 @@ pub mod pallet { pub(super) type Transactions = StorageMap< _, Blake2_128Concat, - T::BlockNumber, + BlockNumberFor, BoundedVec, OptionQuery, >; @@ -350,7 +350,7 @@ pub mod pallet { /// Count indexed chunks for each block. #[pallet::storage] pub(super) type ChunkCount = - StorageMap<_, Blake2_128Concat, T::BlockNumber, u32, ValueQuery>; + StorageMap<_, Blake2_128Concat, BlockNumberFor, u32, ValueQuery>; #[pallet::storage] #[pallet::getter(fn byte_fee)] @@ -365,7 +365,7 @@ pub mod pallet { /// Storage period for data in blocks. Should match `sp_storage_proof::DEFAULT_STORAGE_PERIOD` /// for block authoring. #[pallet::storage] - pub(super) type StoragePeriod = StorageValue<_, T::BlockNumber, ValueQuery>; + pub(super) type StoragePeriod = StorageValue<_, BlockNumberFor, ValueQuery>; // Intermediates #[pallet::storage] @@ -380,7 +380,7 @@ pub mod pallet { pub struct GenesisConfig { pub byte_fee: BalanceOf, pub entry_fee: BalanceOf, - pub storage_period: T::BlockNumber, + pub storage_period: BlockNumberFor, } impl Default for GenesisConfig { @@ -394,7 +394,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { >::put(&self.byte_fee); >::put(&self.entry_fee); diff --git a/frame/transaction-storage/src/mock.rs b/frame/transaction-storage/src/mock.rs index 1f8a4e2d09ba8..243e26b559053 100644 --- a/frame/transaction-storage/src/mock.rs +++ b/frame/transaction-storage/src/mock.rs @@ -24,22 +24,17 @@ use crate::{ use frame_support::traits::{ConstU16, ConstU32, ConstU64, OnFinalize, OnInitialize}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; pub type Block = frame_system::mocking::MockBlock; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Config, Storage, Event}, TransactionStorage: pallet_transaction_storage::{ Pallet, Call, Storage, Config, Inherent, Event @@ -53,13 +48,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); diff --git a/frame/treasury/src/benchmarking.rs b/frame/treasury/src/benchmarking.rs index a3761083e4faa..449549d6c53b7 100644 --- a/frame/treasury/src/benchmarking.rs +++ b/frame/treasury/src/benchmarking.rs @@ -135,7 +135,7 @@ benchmarks_instance_pallet! { setup_pot_account::(); create_approved_proposals::(p)?; }: { - Treasury::::on_initialize(T::BlockNumber::zero()); + Treasury::::on_initialize(frame_system::pallet_prelude::BlockNumberFor::::zero()); } impl_benchmark_test_suite!(Treasury, crate::tests::new_test_ext(), crate::tests::Test); diff --git a/frame/treasury/src/lib.rs b/frame/treasury/src/lib.rs index 509ab933430bb..49be4d91a4568 100644 --- a/frame/treasury/src/lib.rs +++ b/frame/treasury/src/lib.rs @@ -175,7 +175,7 @@ pub mod pallet { /// Period between successive spends. #[pallet::constant] - type SpendPeriod: Get; + type SpendPeriod: Get>; /// Percentage of spare funds (if any) that are burnt per spend period. #[pallet::constant] @@ -234,24 +234,14 @@ pub mod pallet { StorageValue<_, BoundedVec, ValueQuery>; #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig; - - #[cfg(feature = "std")] - impl GenesisConfig { - /// Direct implementation of `GenesisBuild::assimilate_storage`. - #[deprecated(note = "Will be removed after July 2023; use \ - ` as GenesisBuild>::assimilate_storage` instead")] - pub fn assimilate_storage, I: 'static>( - &self, - storage: &mut sp_runtime::Storage, - ) -> Result<(), String> { - >::assimilate_storage(self, storage) - } + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig, I: 'static = ()> { + #[serde(skip)] + _config: sp_std::marker::PhantomData<(T, I)>, } #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { + impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { // Create Treasury account let account_id = >::account_id(); @@ -309,7 +299,7 @@ pub mod pallet { impl, I: 'static> Hooks> for Pallet { /// ## Complexity /// - `O(A)` where `A` is the number of approvals - fn on_initialize(n: T::BlockNumber) -> Weight { + fn on_initialize(n: frame_system::pallet_prelude::BlockNumberFor) -> Weight { let pot = Self::pot(); let deactivated = Deactivated::::get(); if pot != deactivated { diff --git a/frame/treasury/src/tests.rs b/frame/treasury/src/tests.rs index 0659c2f5941b1..79497d55867d6 100644 --- a/frame/treasury/src/tests.rs +++ b/frame/treasury/src/tests.rs @@ -21,14 +21,12 @@ use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BadOrigin, BlakeTwo256, Dispatchable, IdentityLookup}, + BuildStorage, }; use frame_support::{ - assert_err_ignore_postinfo, assert_noop, assert_ok, - pallet_prelude::GenesisBuild, - parameter_types, + assert_err_ignore_postinfo, assert_noop, assert_ok, parameter_types, traits::{ConstU32, ConstU64, OnInitialize}, PalletId, }; @@ -36,20 +34,16 @@ use frame_support::{ use super::*; use crate as treasury; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; type UtilityCall = pallet_utility::Call; type TreasuryCall = crate::Call; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Treasury: treasury::{Pallet, Call, Storage, Config, Event}, + Treasury: treasury::{Pallet, Call, Storage, Config, Event}, Utility: pallet_utility, } ); @@ -60,14 +54,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u128; // u64 is not enough to hold bytes used to generate bounty account type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -147,14 +140,14 @@ impl Config for Test { } pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { // Total issuance will be 200 with treasury account initialized at ED. balances: vec![(0, 100), (1, 98), (2, 1)], } .assimilate_storage(&mut t) .unwrap(); - GenesisBuild::::assimilate_storage(&crate::GenesisConfig, &mut t).unwrap(); + crate::GenesisConfig::::default().assimilate_storage(&mut t).unwrap(); t.into() } @@ -399,7 +392,7 @@ fn treasury_account_doesnt_get_deleted() { // This is useful for chain that will just update runtime. #[test] fn inexistent_account_works() { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(0, 100), (1, 99), (2, 1)] } .assimilate_storage(&mut t) .unwrap(); @@ -431,7 +424,7 @@ fn inexistent_account_works() { #[test] fn genesis_funding_works() { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let initial_funding = 100; pallet_balances::GenesisConfig:: { // Total issuance will be 200 with treasury account initialized with 100. @@ -439,7 +432,7 @@ fn genesis_funding_works() { } .assimilate_storage(&mut t) .unwrap(); - GenesisBuild::::assimilate_storage(&crate::GenesisConfig, &mut t).unwrap(); + crate::GenesisConfig::::default().assimilate_storage(&mut t).unwrap(); let mut t: sp_io::TestExternalities = t.into(); t.execute_with(|| { diff --git a/frame/uniques/src/mock.rs b/frame/uniques/src/mock.rs index e783f0b7cf4d9..5c44a7ed7a539 100644 --- a/frame/uniques/src/mock.rs +++ b/frame/uniques/src/mock.rs @@ -26,20 +26,16 @@ use frame_support::{ }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Uniques: pallet_uniques::{Pallet, Call, Storage, Event}, } @@ -51,13 +47,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type DbWeight = (); @@ -110,7 +105,7 @@ impl Config for Test { } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); diff --git a/frame/utility/src/tests.rs b/frame/utility/src/tests.rs index ced50f828d564..c2fd3a851c319 100644 --- a/frame/utility/src/tests.rs +++ b/frame/utility/src/tests.rs @@ -27,15 +27,14 @@ use frame_support::{ dispatch::{DispatchError, DispatchErrorWithPostInfo, Dispatchable, Pays}, error::BadOrigin, parameter_types, storage, - traits::{ConstU32, ConstU64, Contains, GenesisBuild}, + traits::{ConstU32, ConstU64, Contains}, weights::Weight, }; use pallet_collective::{EnsureProportionAtLeast, Instance1}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, Hash, IdentityLookup}, - TokenError, + BuildStorage, TokenError, }; type BlockNumber = u64; @@ -125,16 +124,12 @@ mod mock_democracy { } } -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Timestamp: pallet_timestamp::{Call, Inherent}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, RootTesting: pallet_root_testing::{Pallet, Call, Storage}, @@ -155,14 +150,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); @@ -265,7 +259,7 @@ use pallet_root_testing::Call as RootTestingCall; use pallet_timestamp::Call as TimestampCall; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 10), (3, 10), (4, 10), (5, 2)], } diff --git a/frame/vesting/src/benchmarking.rs b/frame/vesting/src/benchmarking.rs index 15be519842992..4af48f5d368db 100644 --- a/frame/vesting/src/benchmarking.rs +++ b/frame/vesting/src/benchmarking.rs @@ -21,7 +21,7 @@ use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller}; use frame_support::assert_ok; -use frame_system::{Pallet as System, RawOrigin}; +use frame_system::{pallet_prelude::BlockNumberFor, Pallet as System, RawOrigin}; use sp_runtime::traits::{Bounded, CheckedDiv, CheckedMul}; use super::*; @@ -55,7 +55,7 @@ fn add_vesting_schedules( let source_lookup = T::Lookup::unlookup(source.clone()); T::Currency::make_free_balance_be(&source, BalanceOf::::max_value()); - System::::set_block_number(T::BlockNumber::zero()); + System::::set_block_number(BlockNumberFor::::zero()); let mut total_locked: BalanceOf = Zero::zero(); for _ in 0..n { @@ -88,7 +88,7 @@ benchmarks! { let expected_balance = add_vesting_schedules::(caller_lookup, s)?; // At block zero, everything is vested. - assert_eq!(System::::block_number(), T::BlockNumber::zero()); + assert_eq!(System::::block_number(), BlockNumberFor::::zero()); assert_eq!( Vesting::::vesting_balance(&caller), Some(expected_balance), @@ -144,7 +144,7 @@ benchmarks! { let expected_balance = add_vesting_schedules::(other_lookup.clone(), s)?; // At block zero, everything is vested. - assert_eq!(System::::block_number(), T::BlockNumber::zero()); + assert_eq!(System::::block_number(), BlockNumberFor::::zero()); assert_eq!( Vesting::::vesting_balance(&other), Some(expected_balance), @@ -284,7 +284,7 @@ benchmarks! { let expected_balance = add_vesting_schedules::(caller_lookup, s)?; // Schedules are not vesting at block 0. - assert_eq!(System::::block_number(), T::BlockNumber::zero()); + assert_eq!(System::::block_number(), BlockNumberFor::::zero()); assert_eq!( Vesting::::vesting_balance(&caller), Some(expected_balance), diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index 8f98295dd385a..eb829121e9797 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -67,6 +67,7 @@ use frame_support::{ }, weights::Weight, }; +use frame_system::pallet_prelude::BlockNumberFor; use scale_info::TypeInfo; use sp_runtime::{ traits::{ @@ -127,8 +128,8 @@ impl VestingAction { /// Pick the schedules that this action dictates should continue vesting undisturbed. fn pick_schedules( &self, - schedules: Vec, T::BlockNumber>>, - ) -> impl Iterator, T::BlockNumber>> + '_ { + schedules: Vec, BlockNumberFor>>, + ) -> impl Iterator, BlockNumberFor>> + '_ { schedules.into_iter().enumerate().filter_map(move |(index, schedule)| { if self.should_remove(index) { None @@ -162,7 +163,7 @@ pub mod pallet { type Currency: LockableCurrency; /// Convert the block number into a balance. - type BlockNumberToBalance: Convert>; + type BlockNumberToBalance: Convert, BalanceOf>; /// The minimum amount transferred to call `vested_transfer`. #[pallet::constant] @@ -201,7 +202,7 @@ pub mod pallet { _, Blake2_128Concat, T::AccountId, - BoundedVec, T::BlockNumber>, MaxVestingSchedulesGet>, + BoundedVec, BlockNumberFor>, MaxVestingSchedulesGet>, >; /// Storage version of the pallet. @@ -216,11 +217,11 @@ pub mod pallet { #[pallet::genesis_config] #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { - pub vesting: Vec<(T::AccountId, T::BlockNumber, T::BlockNumber, BalanceOf)>, + pub vesting: Vec<(T::AccountId, BlockNumberFor, BlockNumberFor, BalanceOf)>, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { use sp_runtime::traits::Saturating; @@ -342,7 +343,7 @@ pub mod pallet { pub fn vested_transfer( origin: OriginFor, target: AccountIdLookupOf, - schedule: VestingInfo, T::BlockNumber>, + schedule: VestingInfo, BlockNumberFor>, ) -> DispatchResult { let transactor = ensure_signed(origin)?; let transactor = ::unlookup(transactor); @@ -371,7 +372,7 @@ pub mod pallet { origin: OriginFor, source: AccountIdLookupOf, target: AccountIdLookupOf, - schedule: VestingInfo, T::BlockNumber>, + schedule: VestingInfo, BlockNumberFor>, ) -> DispatchResult { ensure_root(origin)?; Self::do_vested_transfer(source, target, schedule) @@ -433,10 +434,10 @@ impl Pallet { // Create a new `VestingInfo`, based off of two other `VestingInfo`s. // NOTE: We assume both schedules have had funds unlocked up through the current block. fn merge_vesting_info( - now: T::BlockNumber, - schedule1: VestingInfo, T::BlockNumber>, - schedule2: VestingInfo, T::BlockNumber>, - ) -> Option, T::BlockNumber>> { + now: BlockNumberFor, + schedule1: VestingInfo, BlockNumberFor>, + schedule2: VestingInfo, BlockNumberFor>, + ) -> Option, BlockNumberFor>> { let schedule1_ending_block = schedule1.ending_block_as_balance::(); let schedule2_ending_block = schedule2.ending_block_as_balance::(); let now_as_balance = T::BlockNumberToBalance::convert(now); @@ -483,7 +484,7 @@ impl Pallet { fn do_vested_transfer( source: AccountIdLookupOf, target: AccountIdLookupOf, - schedule: VestingInfo, T::BlockNumber>, + schedule: VestingInfo, BlockNumberFor>, ) -> DispatchResult { // Validate user inputs. ensure!(schedule.locked() >= T::MinVestedTransfer::get(), Error::::AmountLow); @@ -531,9 +532,9 @@ impl Pallet { /// /// NOTE: the amount locked does not include any schedules that are filtered out via `action`. fn report_schedule_updates( - schedules: Vec, T::BlockNumber>>, + schedules: Vec, BlockNumberFor>>, action: VestingAction, - ) -> (Vec, T::BlockNumber>>, BalanceOf) { + ) -> (Vec, BlockNumberFor>>, BalanceOf) { let now = >::block_number(); let mut total_locked_now: BalanceOf = Zero::zero(); @@ -570,10 +571,10 @@ impl Pallet { /// Write an accounts updated vesting schedules to storage. fn write_vesting( who: &T::AccountId, - schedules: Vec, T::BlockNumber>>, + schedules: Vec, BlockNumberFor>>, ) -> Result<(), DispatchError> { let schedules: BoundedVec< - VestingInfo, T::BlockNumber>, + VestingInfo, BlockNumberFor>, MaxVestingSchedulesGet, > = schedules.try_into().map_err(|_| Error::::AtMaxVestingSchedules)?; @@ -602,9 +603,9 @@ impl Pallet { /// Execute a `VestingAction` against the given `schedules`. Returns the updated schedules /// and locked amount. fn exec_action( - schedules: Vec, T::BlockNumber>>, + schedules: Vec, BlockNumberFor>>, action: VestingAction, - ) -> Result<(Vec, T::BlockNumber>>, BalanceOf), DispatchError> { + ) -> Result<(Vec, BlockNumberFor>>, BalanceOf), DispatchError> { let (schedules, locked_now) = match action { VestingAction::Merge { index1: idx1, index2: idx2 } => { // The schedule index is based off of the schedule ordering prior to filtering out @@ -649,7 +650,7 @@ where BalanceOf: MaybeSerializeDeserialize + Debug, { type Currency = T::Currency; - type Moment = T::BlockNumber; + type Moment = BlockNumberFor; /// Get the amount that is currently being vested and cannot be transferred out of this account. fn vesting_balance(who: &T::AccountId) -> Option> { @@ -680,7 +681,7 @@ where who: &T::AccountId, locked: BalanceOf, per_block: BalanceOf, - starting_block: T::BlockNumber, + starting_block: BlockNumberFor, ) -> DispatchResult { if locked.is_zero() { return Ok(()) @@ -713,7 +714,7 @@ where who: &T::AccountId, locked: BalanceOf, per_block: BalanceOf, - starting_block: T::BlockNumber, + starting_block: BlockNumberFor, ) -> DispatchResult { // Check for `per_block` or `locked` of 0. if !VestingInfo::new(locked, per_block, starting_block).is_valid() { diff --git a/frame/vesting/src/migrations.rs b/frame/vesting/src/migrations.rs index 69bbc97296500..cac3c90b403ab 100644 --- a/frame/vesting/src/migrations.rs +++ b/frame/vesting/src/migrations.rs @@ -40,12 +40,12 @@ pub mod v1 { pub fn migrate() -> Weight { let mut reads_writes = 0; - Vesting::::translate::, T::BlockNumber>, _>( + Vesting::::translate::, BlockNumberFor>, _>( |_key, vesting_info| { reads_writes += 1; let v: Option< BoundedVec< - VestingInfo, T::BlockNumber>, + VestingInfo, BlockNumberFor>, MaxVestingSchedulesGet, >, > = vec![vesting_info].try_into().ok(); diff --git a/frame/vesting/src/mock.rs b/frame/vesting/src/mock.rs index 31f35bbdab604..fe1779475a69a 100644 --- a/frame/vesting/src/mock.rs +++ b/frame/vesting/src/mock.rs @@ -17,27 +17,23 @@ use frame_support::{ parameter_types, - traits::{ConstU32, ConstU64, GenesisBuild, WithdrawReasons}, + traits::{ConstU32, ConstU64, WithdrawReasons}, }; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, Identity, IdentityLookup}, + BuildStorage, }; use super::*; use crate as pallet_vesting; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Vesting: pallet_vesting::{Pallet, Call, Storage, Event, Config}, } @@ -49,15 +45,14 @@ impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockHashCount = ConstU64<250>; type BlockLength = (); - type BlockNumber = u64; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); type RuntimeEvent = RuntimeEvent; type Hash = H256; type Hashing = BlakeTwo256; - type Header = Header; - type Index = u64; + type Block = Block; + type Nonce = u64; type Lookup = IdentityLookup; type OnKilledAccount = (); type OnNewAccount = (); @@ -125,7 +120,7 @@ impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit); - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![ (1, 10 * self.existential_deposit), diff --git a/frame/whitelist/src/mock.rs b/frame/whitelist/src/mock.rs index afb9d00861563..d91f43b33af91 100644 --- a/frame/whitelist/src/mock.rs +++ b/frame/whitelist/src/mock.rs @@ -28,19 +28,14 @@ use frame_support::{ use frame_system::EnsureRoot; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { System: frame_system, Balances: pallet_balances, @@ -55,14 +50,13 @@ impl frame_system::Config for Test { type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type RuntimeCall = RuntimeCall; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<250>; type Version = (); diff --git a/primitives/api/Cargo.toml b/primitives/api/Cargo.toml index ded866ed48193..c6d197b8d35d5 100644 --- a/primitives/api/Cargo.toml +++ b/primitives/api/Cargo.toml @@ -18,6 +18,7 @@ sp-api-proc-macro = { version = "4.0.0-dev", path = "proc-macro" } sp-core = { version = "21.0.0", default-features = false, path = "../core" } sp-std = { version = "8.0.0", default-features = false, path = "../std" } sp-runtime = { version = "24.0.0", default-features = false, path = "../runtime" } +sp-externalities = { version = "0.19.0", default-features = false, optional = true, path = "../externalities" } sp-version = { version = "22.0.0", default-features = false, path = "../version" } sp-state-machine = { version = "0.28.0", default-features = false, optional = true, path = "../state-machine" } sp-trie = { version = "22.0.0", default-features = false, optional = true, path = "../trie" } @@ -35,6 +36,7 @@ default = ["std"] std = [ "codec/std", "sp-core/std", + "sp-externalities", "sp-std/std", "sp-runtime/std", "sp-state-machine/std", diff --git a/primitives/api/proc-macro/src/decl_runtime_apis.rs b/primitives/api/proc-macro/src/decl_runtime_apis.rs index 052dc896f2cc3..370735819f94c 100644 --- a/primitives/api/proc-macro/src/decl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/decl_runtime_apis.rs @@ -315,7 +315,6 @@ impl<'a> ToClientSideDecl<'a> { fn __runtime_api_internal_call_api_at( &self, at: #block_hash, - context: #crate_::ExecutionContext, params: std::vec::Vec, fn_name: &dyn Fn(#crate_::RuntimeVersion) -> &'static str, ) -> std::result::Result, #crate_::ApiError>; @@ -335,9 +334,8 @@ impl<'a> ToClientSideDecl<'a> { items.into_iter().for_each(|i| match i { TraitItem::Fn(method) => { - let (fn_decl, fn_decl_ctx) = self.fold_trait_item_fn(method, trait_generics_num); + let fn_decl = self.create_method_decl(method, trait_generics_num); result.push(fn_decl.into()); - result.push(fn_decl_ctx.into()); }, r => result.push(r), }); @@ -345,41 +343,12 @@ impl<'a> ToClientSideDecl<'a> { result } - fn fold_trait_item_fn( - &mut self, - method: TraitItemFn, - trait_generics_num: usize, - ) -> (TraitItemFn, TraitItemFn) { - let crate_ = self.crate_; - let context = quote!( #crate_::ExecutionContext::OffchainCall(None) ); - let fn_decl = self.create_method_decl(method.clone(), context, trait_generics_num); - let fn_decl_ctx = self.create_method_decl_with_context(method, trait_generics_num); - - (fn_decl, fn_decl_ctx) - } - - fn create_method_decl_with_context( - &mut self, - method: TraitItemFn, - trait_generics_num: usize, - ) -> TraitItemFn { - let crate_ = self.crate_; - let context_arg: syn::FnArg = parse_quote!( context: #crate_::ExecutionContext ); - let mut fn_decl_ctx = self.create_method_decl(method, quote!(context), trait_generics_num); - fn_decl_ctx.sig.ident = - Ident::new(&format!("{}_with_context", &fn_decl_ctx.sig.ident), Span::call_site()); - fn_decl_ctx.sig.inputs.insert(2, context_arg); - - fn_decl_ctx - } - /// Takes the method declared by the user and creates the declaration we require for the runtime /// api client side. This method will call by default the `method_runtime_api_impl` for doing /// the actual call into the runtime. fn create_method_decl( &mut self, mut method: TraitItemFn, - context: TokenStream, trait_generics_num: usize, ) -> TraitItemFn { let params = match extract_parameter_names_types_and_borrows( @@ -467,7 +436,6 @@ impl<'a> ToClientSideDecl<'a> { >::__runtime_api_internal_call_api_at( self, __runtime_api_at_param__, - #context, __runtime_api_impl_params_encoded__, &|_version| { #( diff --git a/primitives/api/proc-macro/src/impl_runtime_apis.rs b/primitives/api/proc-macro/src/impl_runtime_apis.rs index 028cc6a675ee5..e45f05029d9f3 100644 --- a/primitives/api/proc-macro/src/impl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/impl_runtime_apis.rs @@ -224,8 +224,8 @@ fn generate_runtime_api_base_structures() -> Result { Ok(quote!( pub struct RuntimeApi {} - /// Implements all runtime apis for the client side. #crate_::std_enabled! { + /// Implements all runtime apis for the client side. pub struct RuntimeApiImpl + 'static> { call: &'static C, transaction_depth: std::cell::RefCell, @@ -234,6 +234,9 @@ fn generate_runtime_api_base_structures() -> Result { #crate_::StorageTransactionCache >, recorder: std::option::Option<#crate_::ProofRecorder>, + call_context: #crate_::CallContext, + extensions: std::cell::RefCell<#crate_::Extensions>, + extensions_generated_for: std::cell::RefCell>, } impl> #crate_::ApiExt for @@ -321,6 +324,14 @@ fn generate_runtime_api_base_structures() -> Result { state_version, ) } + + fn set_call_context(&mut self, call_context: #crate_::CallContext) { + self.call_context = call_context; + } + + fn register_extension(&mut self, extension: E) { + std::cell::RefCell::borrow_mut(&self.extensions).register(extension); + } } impl #crate_::ConstructRuntimeApi @@ -339,6 +350,9 @@ fn generate_runtime_api_base_structures() -> Result { changes: std::default::Default::default(), recorder: std::default::Default::default(), storage_transaction_cache: std::default::Default::default(), + call_context: #crate_::CallContext::Offchain, + extensions: std::default::Default::default(), + extensions_generated_for: std::default::Default::default(), }.into() } } @@ -480,7 +494,6 @@ impl<'a> ApiRuntimeImplToApiRuntimeApiImpl<'a> { fn __runtime_api_internal_call_api_at( &self, at: <__SrApiBlock__ as #crate_::BlockT>::Hash, - context: #crate_::ExecutionContext, params: std::vec::Vec, fn_name: &dyn Fn(#crate_::RuntimeVersion) -> &'static str, ) -> std::result::Result, #crate_::ApiError> { @@ -498,14 +511,34 @@ impl<'a> ApiRuntimeImplToApiRuntimeApiImpl<'a> { at, )?; + match &mut *std::cell::RefCell::borrow_mut(&self.extensions_generated_for) { + Some(generated_for) => { + if *generated_for != at { + return std::result::Result::Err( + #crate_::ApiError::UsingSameInstanceForDifferentBlocks + ) + } + }, + generated_for @ None => { + #crate_::CallApiAt::<__SrApiBlock__>::initialize_extensions( + self.call, + at, + &mut std::cell::RefCell::borrow_mut(&self.extensions), + )?; + + *generated_for = Some(at); + } + } + let params = #crate_::CallApiAtParams { at, function: (*fn_name)(version), arguments: params, overlayed_changes: &self.changes, storage_transaction_cache: &self.storage_transaction_cache, - context, + call_context: self.call_context, recorder: &self.recorder, + extensions: &self.extensions, }; #crate_::CallApiAt::<__SrApiBlock__>::call_api_at( diff --git a/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs b/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs index be8c8ca0f8527..f85be81cc7f83 100644 --- a/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs @@ -121,13 +121,20 @@ fn implement_common_api_traits(block_type: TypePath, self_ty: Type) -> Result where Self: Sized { unimplemented!("`into_storage_changes` not implemented for runtime api mocks") } + + fn set_call_context(&mut self, _: #crate_::CallContext) { + unimplemented!("`set_call_context` not implemented for runtime api mocks") + } + + fn register_extension(&mut self, _: E) { + unimplemented!("`register_extension` not implemented for runtime api mocks") + } } impl #crate_::Core<#block_type> for #self_ty { fn __runtime_api_internal_call_api_at( &self, _: <#block_type as #crate_::BlockT>::Hash, - _: #crate_::ExecutionContext, _: std::vec::Vec, _: &dyn Fn(#crate_::RuntimeVersion) -> &'static str, ) -> std::result::Result, #crate_::ApiError> { @@ -141,14 +148,6 @@ fn implement_common_api_traits(block_type: TypePath, self_ty: Type) -> Result::Hash, - _: #crate_::ExecutionContext, - ) -> std::result::Result<#crate_::RuntimeVersion, #crate_::ApiError> { - unimplemented!("`Core::version` not implemented for runtime api mocks") - } - fn execute_block( &self, _: <#block_type as #crate_::BlockT>::Hash, @@ -157,15 +156,6 @@ fn implement_common_api_traits(block_type: TypePath, self_ty: Type) -> Result::Hash, - _: #crate_::ExecutionContext, - _: #block_type, - ) -> std::result::Result<(), #crate_::ApiError> { - unimplemented!("`Core::execute_block` not implemented for runtime api mocks") - } - fn initialize_block( &self, _: <#block_type as #crate_::BlockT>::Hash, @@ -173,15 +163,6 @@ fn implement_common_api_traits(block_type: TypePath, self_ty: Type) -> Result std::result::Result<(), #crate_::ApiError> { unimplemented!("`Core::initialize_block` not implemented for runtime api mocks") } - - fn initialize_block_with_context( - &self, - _: <#block_type as #crate_::BlockT>::Hash, - _: #crate_::ExecutionContext, - _: &<#block_type as #crate_::BlockT>::Header, - ) -> std::result::Result<(), #crate_::ApiError> { - unimplemented!("`Core::initialize_block` not implemented for runtime api mocks") - } } )) } @@ -255,26 +236,12 @@ impl<'a> FoldRuntimeApiImpl<'a> { let crate_ = generate_crate_access(); - // We also need to overwrite all the `_with_context` methods. To do this, - // we clone all methods and add them again with the new name plus one more argument. - impl_item.items.extend(impl_item.items.clone().into_iter().filter_map(|i| { - if let syn::ImplItem::Fn(mut m) = i { - m.sig.ident = quote::format_ident!("{}_with_context", m.sig.ident); - m.sig.inputs.insert(2, parse_quote!( _: #crate_::ExecutionContext )); - - Some(m.into()) - } else { - None - } - })); - let block_type = self.block_type; impl_item.items.push(parse_quote! { fn __runtime_api_internal_call_api_at( &self, _: <#block_type as #crate_::BlockT>::Hash, - _: #crate_::ExecutionContext, _: std::vec::Vec, _: &dyn Fn(#crate_::RuntimeVersion) -> &'static str, ) -> std::result::Result, #crate_::ApiError> { diff --git a/primitives/api/proc-macro/src/runtime_metadata.rs b/primitives/api/proc-macro/src/runtime_metadata.rs index 458248cbd3d16..d027e86fac4ef 100644 --- a/primitives/api/proc-macro/src/runtime_metadata.rs +++ b/primitives/api/proc-macro/src/runtime_metadata.rs @@ -30,13 +30,13 @@ use crate::{ /// Get the type parameter argument without lifetime or mutability /// of a runtime metadata function. /// -/// In the following example, both the `AccountId` and `Index` generic +/// In the following example, both the `AccountId` and `Nonce` generic /// type parameters must implement `scale_info::TypeInfo` because they /// are added into the metadata using `scale_info::meta_type`. /// /// ```ignore -/// trait ExampleAccountNonceApi { -/// fn account_nonce<'a>(account: &'a AccountId) -> Index; +/// trait ExampleAccountNonceApi { +/// fn account_nonce<'a>(account: &'a AccountId) -> Nonce; /// } /// ``` /// diff --git a/primitives/api/src/lib.rs b/primitives/api/src/lib.rs index 78c4cd73a18ae..e683d7aa637e9 100644 --- a/primitives/api/src/lib.rs +++ b/primitives/api/src/lib.rs @@ -78,11 +78,17 @@ pub use hash_db::Hasher; #[doc(hidden)] pub use scale_info; #[doc(hidden)] +pub use sp_core::offchain; +#[doc(hidden)] #[cfg(not(feature = "std"))] pub use sp_core::to_substrate_wasm_fn_return_value; +#[doc(hidden)] +#[cfg(feature = "std")] +pub use sp_core::traits::CallContext; use sp_core::OpaqueMetadata; #[doc(hidden)] -pub use sp_core::{offchain, ExecutionContext}; +#[cfg(feature = "std")] +pub use sp_externalities::{Extension, Extensions}; #[doc(hidden)] #[cfg(feature = "frame-metadata")] pub use sp_metadata_ir::{self as metadata_ir, frame_metadata as metadata}; @@ -518,6 +524,8 @@ pub enum ApiError { Application(#[from] Box), #[error("Api called for an unknown Block: {0}")] UnknownBlock(String), + #[error("Using the same api instance to call into multiple independent blocks.")] + UsingSameInstanceForDifferentBlocks, } /// Extends the runtime api implementation with some common functionality. @@ -581,6 +589,12 @@ pub trait ApiExt { ) -> Result, String> where Self: Sized; + + /// Set the [`CallContext`] to be used by the runtime api calls done by this instance. + fn set_call_context(&mut self, call_context: CallContext); + + /// Register an [`Extension`] that will be accessible while executing a runtime api call. + fn register_extension(&mut self, extension: E); } /// Parameters for [`CallApiAt::call_api_at`]. @@ -596,10 +610,12 @@ pub struct CallApiAtParams<'a, Block: BlockT, Backend: StateBackend, /// The cache for storage transactions. pub storage_transaction_cache: &'a RefCell>, - /// The context this function is executed in. - pub context: ExecutionContext, + /// The call context of this call. + pub call_context: CallContext, /// The optional proof recorder for recording storage accesses. pub recorder: &'a Option>, + /// The extensions that should be used for this call. + pub extensions: &'a RefCell, } /// Something that can call into the an api at a given block. @@ -620,6 +636,13 @@ pub trait CallApiAt { /// Get the state `at` the given block. fn state_at(&self, at: Block::Hash) -> Result; + + /// Initialize the `extensions` for the given block `at` by using the global extensions factory. + fn initialize_extensions( + &self, + at: Block::Hash, + extensions: &mut Extensions, + ) -> Result<(), ApiError>; } /// Auxiliary wrapper that holds an api instance and binds it to the given lifetime. diff --git a/primitives/api/test/benches/bench.rs b/primitives/api/test/benches/bench.rs index 88ebdbc6134aa..45bea08af6ded 100644 --- a/primitives/api/test/benches/bench.rs +++ b/primitives/api/test/benches/bench.rs @@ -17,7 +17,6 @@ use criterion::{criterion_group, criterion_main, Criterion}; use sp_api::ProvideRuntimeApi; -use sp_state_machine::ExecutionStrategy; use substrate_test_runtime_client::{ runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, }; @@ -56,17 +55,13 @@ fn sp_api_benchmark(c: &mut Criterion) { }); c.bench_function("calling function by function pointer in wasm", |b| { - let client = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::AlwaysWasm) - .build(); + let client = TestClientBuilder::new().build(); let best_hash = client.chain_info().best_hash; b.iter(|| client.runtime_api().benchmark_indirect_call(best_hash).unwrap()) }); - c.bench_function("calling function in wasm", |b| { - let client = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::AlwaysWasm) - .build(); + c.bench_function("calling function", |b| { + let client = TestClientBuilder::new().build(); let best_hash = client.chain_info().best_hash; b.iter(|| client.runtime_api().benchmark_direct_call(best_hash).unwrap()) }); diff --git a/primitives/api/test/tests/runtime_calls.rs b/primitives/api/test/tests/runtime_calls.rs index 344c2d31eb0a6..92118c16cdddc 100644 --- a/primitives/api/test/tests/runtime_calls.rs +++ b/primitives/api/test/tests/runtime_calls.rs @@ -22,9 +22,8 @@ use sp_runtime::{ traits::{HashFor, Header as HeaderT}, TransactionOutcome, }; -use sp_state_machine::{ - create_proof_check_backend, execution_proof_check_on_trie_backend, ExecutionStrategy, -}; +use sp_state_machine::{create_proof_check_backend, execution_proof_check_on_trie_backend}; + use substrate_test_runtime_client::{ prelude::*, runtime::{Block, Header, TestAPI, Transfer}, @@ -36,29 +35,18 @@ use sc_block_builder::BlockBuilderProvider; use sp_consensus::SelectChain; use substrate_test_runtime_client::sc_executor::WasmExecutor; -fn calling_function_with_strat(strat: ExecutionStrategy) { - let client = TestClientBuilder::new().set_execution_strategy(strat).build(); +#[test] +fn calling_runtime_function() { + let client = TestClientBuilder::new().build(); let runtime_api = client.runtime_api(); let best_hash = client.chain_info().best_hash; assert_eq!(runtime_api.benchmark_add_one(best_hash, &1).unwrap(), 2); } -#[test] -fn calling_native_runtime_function() { - calling_function_with_strat(ExecutionStrategy::NativeWhenPossible); -} - -#[test] -fn calling_wasm_runtime_function() { - calling_function_with_strat(ExecutionStrategy::AlwaysWasm); -} - #[test] fn calling_native_runtime_signature_changed_function() { - let client = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::NativeWhenPossible) - .build(); + let client = TestClientBuilder::new().build(); let runtime_api = client.runtime_api(); let best_hash = client.chain_info().best_hash; @@ -67,9 +55,7 @@ fn calling_native_runtime_signature_changed_function() { #[test] fn use_trie_function() { - let client = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::AlwaysWasm) - .build(); + let client = TestClientBuilder::new().build(); let runtime_api = client.runtime_api(); let best_hash = client.chain_info().best_hash; assert_eq!(runtime_api.use_trie(best_hash).unwrap(), 2); @@ -77,7 +63,7 @@ fn use_trie_function() { #[test] fn initialize_block_works() { - let client = TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::Both).build(); + let client = TestClientBuilder::new().build(); let runtime_api = client.runtime_api(); let best_hash = client.chain_info().best_hash; runtime_api @@ -97,9 +83,7 @@ fn initialize_block_works() { #[test] fn record_proof_works() { - let (client, longest_chain) = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::Both) - .build_with_longest_chain(); + let (client, longest_chain) = TestClientBuilder::new().build_with_longest_chain(); let storage_root = *futures::executor::block_on(longest_chain.best_chain()).unwrap().state_root(); @@ -151,7 +135,7 @@ fn record_proof_works() { #[test] fn call_runtime_api_with_multiple_arguments() { - let client = TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::Both).build(); + let client = TestClientBuilder::new().build(); let data = vec![1, 2, 4, 5, 6, 7, 8, 8, 10, 12]; let best_hash = client.chain_info().best_hash; @@ -166,8 +150,7 @@ fn disable_logging_works() { if std::env::var("RUN_TEST").is_ok() { sp_tracing::try_init_simple(); - let mut builder = - TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::AlwaysWasm); + let mut builder = TestClientBuilder::new(); builder.genesis_init_mut().set_wasm_code( substrate_test_runtime_client::runtime::wasm_binary_logging_disabled_unwrap().to_vec(), ); diff --git a/primitives/api/test/tests/ui/mock_only_self_reference.stderr b/primitives/api/test/tests/ui/mock_only_self_reference.stderr index 430f63eee1660..f088e8f2de59d 100644 --- a/primitives/api/test/tests/ui/mock_only_self_reference.stderr +++ b/primitives/api/test/tests/ui/mock_only_self_reference.stderr @@ -48,42 +48,3 @@ error[E0050]: method `test2` has 2 parameters but the declaration in trait `Api: | |_^ expected 3 parameters, found 2 | = note: this error originates in the macro `sp_api::mock_impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0050]: method `test_with_context` has 3 parameters but the declaration in trait `Api::test_with_context` has 4 - --> tests/ui/mock_only_self_reference.rs:12:1 - | -3 | / sp_api::decl_runtime_apis! { -4 | | pub trait Api { -5 | | fn test(data: u64); - | |_________________________- trait requires 4 parameters -... -12 | / sp_api::mock_impl_runtime_apis! { -13 | | impl Api for MockApi { -14 | | fn test(self, data: u64) {} -15 | | -16 | | fn test2(&mut self, data: u64) {} -17 | | } -18 | | } - | |_^ expected 4 parameters, found 3 - | - = note: this error originates in the macro `sp_api::mock_impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0050]: method `test2_with_context` has 3 parameters but the declaration in trait `Api::test2_with_context` has 4 - --> tests/ui/mock_only_self_reference.rs:12:1 - | -3 | / sp_api::decl_runtime_apis! { -4 | | pub trait Api { -5 | | fn test(data: u64); -6 | | fn test2(data: u64); - | |__________________________- trait requires 4 parameters -... -12 | / sp_api::mock_impl_runtime_apis! { -13 | | impl Api for MockApi { -14 | | fn test(self, data: u64) {} -15 | | -16 | | fn test2(&mut self, data: u64) {} -17 | | } -18 | | } - | |_^ expected 4 parameters, found 3 - | - = note: this error originates in the macro `sp_api::mock_impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/primitives/application-crypto/test/src/ecdsa.rs b/primitives/application-crypto/test/src/ecdsa.rs index 99ca6f4c4adf2..396683a91ac02 100644 --- a/primitives/application-crypto/test/src/ecdsa.rs +++ b/primitives/application-crypto/test/src/ecdsa.rs @@ -16,13 +16,13 @@ // limitations under the License. //! Integration tests for ecdsa -use sp_api::ProvideRuntimeApi; +use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_application_crypto::ecdsa::AppPair; use sp_core::{ crypto::{ByteArray, Pair}, testing::ECDSA, }; -use sp_keystore::{testing::MemoryKeystore, Keystore}; +use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt}; use std::sync::Arc; use substrate_test_runtime_client::{ runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, @@ -31,9 +31,12 @@ use substrate_test_runtime_client::{ #[test] fn ecdsa_works_in_runtime() { let keystore = Arc::new(MemoryKeystore::new()); - let test_client = TestClientBuilder::new().set_keystore(keystore.clone()).build(); - let (signature, public) = test_client - .runtime_api() + let test_client = TestClientBuilder::new().build(); + + let mut runtime_api = test_client.runtime_api(); + runtime_api.register_extension(KeystoreExt::new(keystore.clone())); + + let (signature, public) = runtime_api .test_ecdsa_crypto(test_client.chain_info().genesis_hash) .expect("Tests `ecdsa` crypto."); diff --git a/primitives/application-crypto/test/src/ed25519.rs b/primitives/application-crypto/test/src/ed25519.rs index f4553f95bf1f8..f0ceccdcebfcd 100644 --- a/primitives/application-crypto/test/src/ed25519.rs +++ b/primitives/application-crypto/test/src/ed25519.rs @@ -17,13 +17,13 @@ //! Integration tests for ed25519 -use sp_api::ProvideRuntimeApi; +use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_application_crypto::ed25519::AppPair; use sp_core::{ crypto::{ByteArray, Pair}, testing::ED25519, }; -use sp_keystore::{testing::MemoryKeystore, Keystore}; +use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt}; use std::sync::Arc; use substrate_test_runtime_client::{ runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, @@ -32,9 +32,12 @@ use substrate_test_runtime_client::{ #[test] fn ed25519_works_in_runtime() { let keystore = Arc::new(MemoryKeystore::new()); - let test_client = TestClientBuilder::new().set_keystore(keystore.clone()).build(); - let (signature, public) = test_client - .runtime_api() + let test_client = TestClientBuilder::new().build(); + + let mut runtime_api = test_client.runtime_api(); + runtime_api.register_extension(KeystoreExt::new(keystore.clone())); + + let (signature, public) = runtime_api .test_ed25519_crypto(test_client.chain_info().genesis_hash) .expect("Tests `ed25519` crypto."); diff --git a/primitives/application-crypto/test/src/sr25519.rs b/primitives/application-crypto/test/src/sr25519.rs index 736521d7d9f3a..3c62270395f04 100644 --- a/primitives/application-crypto/test/src/sr25519.rs +++ b/primitives/application-crypto/test/src/sr25519.rs @@ -17,13 +17,13 @@ //! Integration tests for sr25519 -use sp_api::ProvideRuntimeApi; +use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_application_crypto::sr25519::AppPair; use sp_core::{ crypto::{ByteArray, Pair}, testing::SR25519, }; -use sp_keystore::{testing::MemoryKeystore, Keystore}; +use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt}; use std::sync::Arc; use substrate_test_runtime_client::{ runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, @@ -32,9 +32,12 @@ use substrate_test_runtime_client::{ #[test] fn sr25519_works_in_runtime() { let keystore = Arc::new(MemoryKeystore::new()); - let test_client = TestClientBuilder::new().set_keystore(keystore.clone()).build(); - let (signature, public) = test_client - .runtime_api() + let test_client = TestClientBuilder::new().build(); + + let mut runtime_api = test_client.runtime_api(); + runtime_api.register_extension(KeystoreExt::new(keystore.clone())); + + let (signature, public) = runtime_api .test_sr25519_crypto(test_client.chain_info().genesis_hash) .expect("Tests `sr25519` crypto."); diff --git a/primitives/consensus/common/src/lib.rs b/primitives/consensus/common/src/lib.rs index 215b4448b4a8e..d47f3bafc4220 100644 --- a/primitives/consensus/common/src/lib.rs +++ b/primitives/consensus/common/src/lib.rs @@ -71,16 +71,6 @@ pub enum BlockOrigin { File, } -impl From for sp_core::ExecutionContext { - fn from(origin: BlockOrigin) -> Self { - if origin == BlockOrigin::NetworkInitialSync { - sp_core::ExecutionContext::Syncing - } else { - sp_core::ExecutionContext::Importing - } - } -} - /// Environment for a Consensus instance. /// /// Creates proposer instance. diff --git a/primitives/core/Cargo.toml b/primitives/core/Cargo.toml index 65c252a523114..f0da73e8ec789 100644 --- a/primitives/core/Cargo.toml +++ b/primitives/core/Cargo.toml @@ -39,6 +39,7 @@ sp-externalities = { version = "0.19.0", optional = true, path = "../externaliti futures = { version = "0.3.21", optional = true } dyn-clonable = { version = "0.9.0", optional = true } thiserror = { version = "1.0.30", optional = true } +tracing = { version = "0.1.29", optional = true } bitflags = "1.3" paste = "1.0.7" @@ -113,6 +114,7 @@ std = [ "futures/thread-pool", "libsecp256k1/std", "dyn-clonable", + "tracing", ] # Serde support without relying on std features. diff --git a/primitives/core/src/lib.rs b/primitives/core/src/lib.rs index 951b481253b4e..da3b438190954 100644 --- a/primitives/core/src/lib.rs +++ b/primitives/core/src/lib.rs @@ -98,45 +98,6 @@ pub use sp_storage as storage; #[doc(hidden)] pub use sp_std; -/// Context for executing a call into the runtime. -pub enum ExecutionContext { - /// Context used for general block import (including locally authored blocks). - Importing, - /// Context used for importing blocks as part of an initial sync of the blockchain. - /// - /// We distinguish between major sync and import so that validators who are running - /// their initial sync (or catching up after some time offline) can use the faster - /// native runtime (since we can reasonably assume the network as a whole has already - /// come to a broad consensus on the block and it probably hasn't been crafted - /// specifically to attack this node), but when importing blocks at the head of the - /// chain in normal operation they can use the safer Wasm version. - Syncing, - /// Context used for block construction. - BlockConstruction, - /// Context used for offchain calls. - /// - /// This allows passing offchain extension and customizing available capabilities. - OffchainCall(Option<(Box, offchain::Capabilities)>), -} - -impl ExecutionContext { - /// Returns the capabilities of particular context. - pub fn capabilities(&self) -> offchain::Capabilities { - use ExecutionContext::*; - - match self { - Importing | Syncing | BlockConstruction => offchain::Capabilities::empty(), - // Enable keystore, transaction pool and Offchain DB reads by default for offchain - // calls. - OffchainCall(None) => - offchain::Capabilities::KEYSTORE | - offchain::Capabilities::OFFCHAIN_DB_READ | - offchain::Capabilities::TRANSACTION_POOL, - OffchainCall(Some((_, capabilities))) => *capabilities, - } - } -} - /// Hex-serialized shim for `Vec`. #[derive(PartialEq, Eq, Clone, RuntimeDebug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize, Hash, PartialOrd, Ord))] diff --git a/primitives/core/src/offchain/mod.rs b/primitives/core/src/offchain/mod.rs index a6cef85e6ac1b..cef495dfaacdc 100644 --- a/primitives/core/src/offchain/mod.rs +++ b/primitives/core/src/offchain/mod.rs @@ -260,26 +260,22 @@ impl Timestamp { bitflags::bitflags! { /// Execution context extra capabilities. pub struct Capabilities: u32 { - /// Access to transaction pool. - const TRANSACTION_POOL = 0b0000_0000_0001; /// External http calls. - const HTTP = 0b0000_0000_0010; + const HTTP = 1 << 0; /// Keystore access. - const KEYSTORE = 0b0000_0000_0100; + const KEYSTORE = 1 << 2; /// Randomness source. - const RANDOMNESS = 0b0000_0000_1000; + const RANDOMNESS = 1 << 3; /// Access to opaque network state. - const NETWORK_STATE = 0b0000_0001_0000; + const NETWORK_STATE = 1 << 4; /// Access to offchain worker DB (read only). - const OFFCHAIN_DB_READ = 0b0000_0010_0000; + const OFFCHAIN_DB_READ = 1 << 5; /// Access to offchain worker DB (writes). - const OFFCHAIN_DB_WRITE = 0b0000_0100_0000; + const OFFCHAIN_DB_WRITE = 1 << 6; /// Manage the authorized nodes - const NODE_AUTHORIZATION = 0b0000_1000_0000; + const NODE_AUTHORIZATION = 1 << 7; /// Access time related functionality - const TIME = 0b0001_0000_0000; - /// Access the statement store. - const STATEMENT_STORE = 0b0010_0000_0000; + const TIME = 1 << 8; } } @@ -785,8 +781,8 @@ mod tests { assert!(!none.contains(Capabilities::KEYSTORE)); assert!(all.contains(Capabilities::KEYSTORE)); assert!(some.contains(Capabilities::KEYSTORE)); - assert!(!none.contains(Capabilities::TRANSACTION_POOL)); - assert!(all.contains(Capabilities::TRANSACTION_POOL)); - assert!(!some.contains(Capabilities::TRANSACTION_POOL)); + assert!(!none.contains(Capabilities::RANDOMNESS)); + assert!(all.contains(Capabilities::RANDOMNESS)); + assert!(!some.contains(Capabilities::TIME)); } } diff --git a/primitives/core/src/offchain/storage.rs b/primitives/core/src/offchain/storage.rs index 3a114de5bfa3c..4db839f1a451a 100644 --- a/primitives/core/src/offchain/storage.rs +++ b/primitives/core/src/offchain/storage.rs @@ -17,12 +17,14 @@ //! In-memory implementation of offchain workers database. -use crate::offchain::OffchainStorage; +use crate::offchain::{DbExternalities, OffchainStorage, StorageKind, STORAGE_PREFIX}; use std::{ collections::hash_map::{Entry, HashMap}, iter::Iterator, }; +const LOG_TARGET: &str = "offchain-worker::storage"; + /// In-memory storage for offchain workers. #[derive(Debug, Clone, Default)] pub struct InMemOffchainStorage { @@ -88,3 +90,95 @@ impl OffchainStorage for InMemOffchainStorage { } } } + +fn unavailable_yet(name: &str) -> R { + tracing::error!( + target: LOG_TARGET, + "The {:?} API is not available for offchain workers yet. Follow \ + https://github.com/paritytech/substrate/issues/1458 for details", + name + ); + Default::default() +} + +const LOCAL_DB: &str = "LOCAL (fork-aware) DB"; + +/// Offchain DB that implements [`DbExternalities`] for [`OffchainStorage`]. +#[derive(Debug, Clone)] +pub struct OffchainDb { + /// Persistent storage database. + persistent: Storage, +} + +impl OffchainDb { + /// Create new instance of Offchain DB. + pub fn new(persistent: Storage) -> Self { + Self { persistent } + } +} + +impl DbExternalities for OffchainDb { + fn local_storage_set(&mut self, kind: StorageKind, key: &[u8], value: &[u8]) { + tracing::debug!( + target: LOG_TARGET, + ?kind, + key = ?array_bytes::bytes2hex("", key), + value = ?array_bytes::bytes2hex("", value), + "Write", + ); + match kind { + StorageKind::PERSISTENT => self.persistent.set(STORAGE_PREFIX, key, value), + StorageKind::LOCAL => unavailable_yet(LOCAL_DB), + } + } + + fn local_storage_clear(&mut self, kind: StorageKind, key: &[u8]) { + tracing::debug!( + target: LOG_TARGET, + ?kind, + key = ?array_bytes::bytes2hex("", key), + "Clear", + ); + match kind { + StorageKind::PERSISTENT => self.persistent.remove(STORAGE_PREFIX, key), + StorageKind::LOCAL => unavailable_yet(LOCAL_DB), + } + } + + fn local_storage_compare_and_set( + &mut self, + kind: StorageKind, + key: &[u8], + old_value: Option<&[u8]>, + new_value: &[u8], + ) -> bool { + tracing::debug!( + target: LOG_TARGET, + ?kind, + key = ?array_bytes::bytes2hex("", key), + new_value = ?array_bytes::bytes2hex("", new_value), + old_value = ?old_value.as_ref().map(|s| array_bytes::bytes2hex("", s)), + "CAS", + ); + match kind { + StorageKind::PERSISTENT => + self.persistent.compare_and_set(STORAGE_PREFIX, key, old_value, new_value), + StorageKind::LOCAL => unavailable_yet(LOCAL_DB), + } + } + + fn local_storage_get(&mut self, kind: StorageKind, key: &[u8]) -> Option> { + let result = match kind { + StorageKind::PERSISTENT => self.persistent.get(STORAGE_PREFIX, key), + StorageKind::LOCAL => unavailable_yet(LOCAL_DB), + }; + tracing::debug!( + target: LOG_TARGET, + ?kind, + key = ?array_bytes::bytes2hex("", key), + result = ?result.as_ref().map(|s| array_bytes::bytes2hex("", s)), + "Read", + ); + result + } +} diff --git a/primitives/externalities/src/extensions.rs b/primitives/externalities/src/extensions.rs index 84155227a713e..8b0bbd2c5921b 100644 --- a/primitives/externalities/src/extensions.rs +++ b/primitives/externalities/src/extensions.rs @@ -42,6 +42,12 @@ pub trait Extension: Send + Any { fn as_mut_any(&mut self) -> &mut dyn Any; } +impl Extension for Box { + fn as_mut_any(&mut self) -> &mut dyn Any { + (**self).as_mut_any() + } +} + /// Macro for declaring an extension that usable with [`Extensions`]. /// /// The extension will be an unit wrapper struct that implements [`Extension`], `Deref` and @@ -190,6 +196,14 @@ impl Extensions { pub fn iter_mut(&mut self) -> impl Iterator)> { self.extensions.iter_mut() } + + /// Merge `other` into `self`. + /// + /// If both contain the same extension, the extension instance of `other` will overwrite the + /// instance found in `self`. + pub fn merge(&mut self, other: Self) { + self.extensions.extend(other.extensions); + } } impl Extend for Extensions { diff --git a/primitives/keystore/src/lib.rs b/primitives/keystore/src/lib.rs index 1d2a27cb8726c..07583d11d527a 100644 --- a/primitives/keystore/src/lib.rs +++ b/primitives/keystore/src/lib.rs @@ -174,37 +174,36 @@ pub trait Keystore: Send + Sync { msg: &[u8; 32], ) -> Result, Error>; - #[cfg(feature = "bls-experimental")] /// Returns all bls12-381 public keys for the given key type. + #[cfg(feature = "bls-experimental")] fn bls381_public_keys(&self, id: KeyTypeId) -> Vec; - #[cfg(feature = "bls-experimental")] /// Returns all bls12-377 public keys for the given key type. + #[cfg(feature = "bls-experimental")] fn bls377_public_keys(&self, id: KeyTypeId) -> Vec; - #[cfg(feature = "bls-experimental")] /// Generate a new bls381 key pair for the given key type and an optional seed. /// /// Returns an `bls381::Public` key of the generated key pair or an `Err` if /// something failed during key generation. + #[cfg(feature = "bls-experimental")] fn bls381_generate_new( &self, key_type: KeyTypeId, seed: Option<&str>, ) -> Result; - #[cfg(feature = "bls-experimental")] /// Generate a new bls377 key pair for the given key type and an optional seed. /// /// Returns an `bls377::Public` key of the generated key pair or an `Err` if /// something failed during key generation. + #[cfg(feature = "bls-experimental")] fn bls377_generate_new( &self, key_type: KeyTypeId, seed: Option<&str>, ) -> Result; - #[cfg(feature = "bls-experimental")] /// Generate a bls381 signature for a given message. /// /// Receives [`KeyTypeId`] and a [`bls381::Public`] key to be able to map @@ -213,6 +212,7 @@ pub trait Keystore: Send + Sync { /// Returns an [`bls381::Signature`] or `None` in case the given `key_type` /// and `public` combination doesn't exist in the keystore. /// An `Err` will be returned if generating the signature itself failed. + #[cfg(feature = "bls-experimental")] fn bls381_sign( &self, key_type: KeyTypeId, @@ -220,7 +220,6 @@ pub trait Keystore: Send + Sync { msg: &[u8], ) -> Result, Error>; - #[cfg(feature = "bls-experimental")] /// Generate a bls377 signature for a given message. /// /// Receives [`KeyTypeId`] and a [`bls377::Public`] key to be able to map @@ -229,6 +228,7 @@ pub trait Keystore: Send + Sync { /// Returns an [`bls377::Signature`] or `None` in case the given `key_type` /// and `public` combination doesn't exist in the keystore. /// An `Err` will be returned if generating the signature itself failed. + #[cfg(feature = "bls-experimental")] fn bls377_sign( &self, key_type: KeyTypeId, @@ -309,6 +309,158 @@ pub trait Keystore: Send + Sync { } } +impl Keystore for Arc { + fn sr25519_public_keys(&self, key_type: KeyTypeId) -> Vec { + (**self).sr25519_public_keys(key_type) + } + + fn sr25519_generate_new( + &self, + key_type: KeyTypeId, + seed: Option<&str>, + ) -> Result { + (**self).sr25519_generate_new(key_type, seed) + } + + fn sr25519_sign( + &self, + key_type: KeyTypeId, + public: &sr25519::Public, + msg: &[u8], + ) -> Result, Error> { + (**self).sr25519_sign(key_type, public, msg) + } + + fn sr25519_vrf_sign( + &self, + key_type: KeyTypeId, + public: &sr25519::Public, + data: &sr25519::vrf::VrfSignData, + ) -> Result, Error> { + (**self).sr25519_vrf_sign(key_type, public, data) + } + + fn sr25519_vrf_output( + &self, + key_type: KeyTypeId, + public: &sr25519::Public, + input: &sr25519::vrf::VrfInput, + ) -> Result, Error> { + (**self).sr25519_vrf_output(key_type, public, input) + } + + fn ed25519_public_keys(&self, key_type: KeyTypeId) -> Vec { + (**self).ed25519_public_keys(key_type) + } + + fn ed25519_generate_new( + &self, + key_type: KeyTypeId, + seed: Option<&str>, + ) -> Result { + (**self).ed25519_generate_new(key_type, seed) + } + + fn ed25519_sign( + &self, + key_type: KeyTypeId, + public: &ed25519::Public, + msg: &[u8], + ) -> Result, Error> { + (**self).ed25519_sign(key_type, public, msg) + } + + fn ecdsa_public_keys(&self, key_type: KeyTypeId) -> Vec { + (**self).ecdsa_public_keys(key_type) + } + + fn ecdsa_generate_new( + &self, + key_type: KeyTypeId, + seed: Option<&str>, + ) -> Result { + (**self).ecdsa_generate_new(key_type, seed) + } + + fn ecdsa_sign( + &self, + key_type: KeyTypeId, + public: &ecdsa::Public, + msg: &[u8], + ) -> Result, Error> { + (**self).ecdsa_sign(key_type, public, msg) + } + + fn ecdsa_sign_prehashed( + &self, + key_type: KeyTypeId, + public: &ecdsa::Public, + msg: &[u8; 32], + ) -> Result, Error> { + (**self).ecdsa_sign_prehashed(key_type, public, msg) + } + + fn insert(&self, key_type: KeyTypeId, suri: &str, public: &[u8]) -> Result<(), ()> { + (**self).insert(key_type, suri, public) + } + + fn keys(&self, key_type: KeyTypeId) -> Result>, Error> { + (**self).keys(key_type) + } + + fn has_keys(&self, public_keys: &[(Vec, KeyTypeId)]) -> bool { + (**self).has_keys(public_keys) + } + + #[cfg(feature = "bls-experimental")] + fn bls381_public_keys(&self, id: KeyTypeId) -> Vec { + (**self).bls381_public_keys(id) + } + + #[cfg(feature = "bls-experimental")] + fn bls377_public_keys(&self, id: KeyTypeId) -> Vec { + (**self).bls377_public_keys(id) + } + + #[cfg(feature = "bls-experimental")] + fn bls381_generate_new( + &self, + key_type: KeyTypeId, + seed: Option<&str>, + ) -> Result { + (**self).bls381_generate_new(key_type, seed) + } + + #[cfg(feature = "bls-experimental")] + fn bls377_generate_new( + &self, + key_type: KeyTypeId, + seed: Option<&str>, + ) -> Result { + (**self).bls377_generate_new(key_type, seed) + } + + #[cfg(feature = "bls-experimental")] + fn bls381_sign( + &self, + key_type: KeyTypeId, + public: &bls381::Public, + msg: &[u8], + ) -> Result, Error> { + (**self).bls381_sign(key_type, public, msg) + } + + #[cfg(feature = "bls-experimental")] + fn bls377_sign( + &self, + key_type: KeyTypeId, + public: &bls377::Public, + msg: &[u8], + ) -> Result, Error> { + (**self).bls377_sign(key_type, public, msg) + } +} + /// A shared pointer to a keystore implementation. pub type KeystorePtr = Arc; @@ -319,6 +471,13 @@ sp_externalities::decl_extension! { impl KeystoreExt { /// Create a new instance of `KeystoreExt` + /// + /// This is more performant as we don't need to wrap keystore in another [`Arc`]. + pub fn from(keystore: KeystorePtr) -> Self { + Self(keystore) + } + + /// Create a new instance of `KeystoreExt` using the given `keystore`. pub fn new(keystore: T) -> Self { Self(Arc::new(keystore)) } diff --git a/primitives/runtime/src/generic/block.rs b/primitives/runtime/src/generic/block.rs index 6261e412eb8ad..05146e880cb16 100644 --- a/primitives/runtime/src/generic/block.rs +++ b/primitives/runtime/src/generic/block.rs @@ -25,7 +25,10 @@ use serde::{Deserialize, Serialize}; use crate::{ codec::{Codec, Decode, Encode}, - traits::{self, Block as BlockT, Header as HeaderT, MaybeSerialize, Member, NumberFor}, + traits::{ + self, Block as BlockT, Header as HeaderT, MaybeSerialize, MaybeSerializeDeserialize, + Member, NumberFor, + }, Justifications, }; use sp_core::RuntimeDebug; @@ -79,16 +82,23 @@ impl fmt::Display for BlockId { #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] #[cfg_attr(feature = "serde", serde(deny_unknown_fields))] -pub struct Block { +pub struct Block { /// The block header. pub header: Header, /// The accompanying extrinsics. pub extrinsics: Vec, } -impl traits::Block for Block +impl traits::HeaderProvider for Block where Header: HeaderT, +{ + type HeaderT = Header; +} + +impl traits::Block for Block +where + Header: HeaderT + MaybeSerializeDeserialize, Extrinsic: Member + Codec + traits::Extrinsic, { type Extrinsic = Extrinsic; diff --git a/primitives/runtime/src/generic/header.rs b/primitives/runtime/src/generic/header.rs index 6fdf43ac08105..82ab9a61f96d8 100644 --- a/primitives/runtime/src/generic/header.rs +++ b/primitives/runtime/src/generic/header.rs @@ -26,6 +26,7 @@ use crate::{ MaybeSerializeDeserialize, Member, }, }; +use codec::{FullCodec, MaxEncodedLen}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use sp_core::U256; @@ -33,6 +34,7 @@ use sp_std::fmt::Debug; /// Abstraction over a block header for a substrate chain. #[derive(Encode, Decode, PartialEq, Eq, Clone, sp_core::RuntimeDebug, TypeInfo)] +#[scale_info(skip_type_params(Hash))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] #[cfg_attr(feature = "serde", serde(deny_unknown_fields))] @@ -81,13 +83,16 @@ where + MaybeSerializeDeserialize + MaybeFromStr + Debug + + Default + sp_std::hash::Hash + MaybeDisplay + AtLeast32BitUnsigned - + Codec + + FullCodec + Copy + + MaxEncodedLen + Into - + TryFrom, + + TryFrom + + TypeInfo, Hash: HashT, { type Number = Number; diff --git a/primitives/runtime/src/lib.rs b/primitives/runtime/src/lib.rs index d29938d0a8610..e2f890a46b3db 100644 --- a/primitives/runtime/src/lib.rs +++ b/primitives/runtime/src/lib.rs @@ -199,6 +199,9 @@ pub trait BuildStorage { /// Something that can build the genesis storage of a module. #[cfg(feature = "std")] +#[deprecated( + note = "`BuildModuleGenesisStorage` is planned to be removed in December 2023. Use `BuildStorage` instead of it." +)] pub trait BuildModuleGenesisStorage: Sized { /// Create the module genesis storage into the given `storage` and `child_storage`. fn build_module_genesis_storage( diff --git a/primitives/runtime/src/runtime_logger.rs b/primitives/runtime/src/runtime_logger.rs index 63e96a52a527f..b7374b8b6f6c8 100644 --- a/primitives/runtime/src/runtime_logger.rs +++ b/primitives/runtime/src/runtime_logger.rs @@ -68,8 +68,7 @@ mod tests { use sp_api::ProvideRuntimeApi; use std::{env, str::FromStr}; use substrate_test_runtime_client::{ - runtime::TestAPI, DefaultTestClientBuilderExt, ExecutionStrategy, TestClientBuilder, - TestClientBuilderExt, + runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, }; #[test] @@ -78,9 +77,7 @@ mod tests { sp_tracing::try_init_simple(); log::set_max_level(log::LevelFilter::from_str(&env::var("RUST_LOG").unwrap()).unwrap()); - let client = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::AlwaysWasm) - .build(); + let client = TestClientBuilder::new().build(); let runtime_api = client.runtime_api(); runtime_api .do_trace_log(client.chain_info().genesis_hash) diff --git a/primitives/runtime/src/testing.rs b/primitives/runtime/src/testing.rs index abf4d81634691..5f94c834a8f29 100644 --- a/primitives/runtime/src/testing.rs +++ b/primitives/runtime/src/testing.rs @@ -235,7 +235,7 @@ impl Deref for ExtrinsicWrapper { } /// Testing block -#[derive(PartialEq, Eq, Clone, Serialize, Debug, Encode, Decode)] +#[derive(PartialEq, Eq, Clone, Serialize, Debug, Encode, Decode, TypeInfo)] pub struct Block { /// Block header pub header: Header, @@ -243,6 +243,10 @@ pub struct Block { pub extrinsics: Vec, } +impl traits::HeaderProvider for Block { + type HeaderT = Header; +} + impl< Xt: 'static + Codec + Sized + Send + Sync + Serialize + Clone + Eq + Debug + traits::Extrinsic, > traits::Block for Block diff --git a/primitives/runtime/src/traits.rs b/primitives/runtime/src/traits.rs index 3aa27234fbce2..51d91958ab533 100644 --- a/primitives/runtime/src/traits.rs +++ b/primitives/runtime/src/traits.rs @@ -26,7 +26,7 @@ use crate::{ }, DispatchResult, }; -use codec::{Codec, Decode, Encode, EncodeLike, MaxEncodedLen}; +use codec::{Codec, Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen}; use impl_trait_for_tuples::impl_for_tuples; #[cfg(feature = "serde")] use serde::{de::DeserializeOwned, Deserialize, Serialize}; @@ -1154,7 +1154,9 @@ pub trait IsMember { /// `parent_hash`, as well as a `digest` and a block `number`. /// /// You can also create a `new` one from those fields. -pub trait Header: Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + 'static { +pub trait Header: + Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + TypeInfo + 'static +{ /// Header number. type Number: Member + MaybeSerializeDeserialize @@ -1164,7 +1166,10 @@ pub trait Header: Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + 's + Copy + MaybeDisplay + AtLeast32BitUnsigned - + Codec; + + Default + + TypeInfo + + MaxEncodedLen + + FullCodec; /// Header hash type type Hash: HashOutput; /// Hashing algorithm @@ -1210,15 +1215,50 @@ pub trait Header: Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + 's } } +// Something that provides the Header Type. Only for internal usage and should only be used +// via `HeaderFor` or `BlockNumberFor`. +// +// This is needed to fix the "cyclical" issue in loading Header/BlockNumber as part of a +// `pallet::call`. Essentially, `construct_runtime` aggregates all calls to create a `RuntimeCall` +// that is then used to define `UncheckedExtrinsic`. +// ```ignore +// pub type UncheckedExtrinsic = +// generic::UncheckedExtrinsic; +// ``` +// This `UncheckedExtrinsic` is supplied to the `Block`. +// ```ignore +// pub type Block = generic::Block; +// ``` +// So, if we do not create a trait outside of `Block` that doesn't have `Extrinsic`, we go into a +// recursive loop leading to a build error. +// +// Note that this is a workaround for a compiler bug and should be removed when the compiler +// bug is fixed. +#[doc(hidden)] +pub trait HeaderProvider { + /// Header type. + type HeaderT: Header; +} + /// Something which fulfills the abstract idea of a Substrate block. It has types for /// `Extrinsic` pieces of information as well as a `Header`. /// /// You can get an iterator over each of the `extrinsics` and retrieve the `header`. -pub trait Block: Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + 'static { +pub trait Block: + HeaderProvider::Header> + + Clone + + Send + + Sync + + Codec + + Eq + + MaybeSerialize + + Debug + + 'static +{ /// Type for extrinsics. type Extrinsic: Member + Codec + Extrinsic + MaybeSerialize; /// Header type. - type Header: Header; + type Header: Header + MaybeSerializeDeserialize; /// Block hash type. type Hash: HashOutput; diff --git a/primitives/session/Cargo.toml b/primitives/session/Cargo.toml index f43390f0a1069..dc99c356cc197 100644 --- a/primitives/session/Cargo.toml +++ b/primitives/session/Cargo.toml @@ -20,6 +20,7 @@ sp-core = { version = "21.0.0", default-features = false, path = "../core" } sp-runtime = { version = "24.0.0", optional = true, path = "../runtime" } sp-staking = { version = "4.0.0-dev", default-features = false, path = "../staking" } sp-std = { version = "8.0.0", default-features = false, path = "../std" } +sp-keystore = { version = "0.27.0", path = "../keystore", optional = true } [features] default = [ "std" ] @@ -31,4 +32,5 @@ std = [ "sp-runtime/std", "sp-staking/std", "sp-std/std", + "sp-keystore", ] diff --git a/primitives/session/src/lib.rs b/primitives/session/src/lib.rs index 642aa2a21143e..45395e9766f55 100644 --- a/primitives/session/src/lib.rs +++ b/primitives/session/src/lib.rs @@ -112,17 +112,22 @@ pub fn generate_initial_session_keys( client: std::sync::Arc, at: Block::Hash, seeds: Vec, + keystore: sp_keystore::KeystorePtr, ) -> Result<(), sp_api::ApiError> where Block: BlockT, T: ProvideRuntimeApi, T::Api: SessionKeys, { + use sp_api::ApiExt; + if seeds.is_empty() { return Ok(()) } - let runtime_api = client.runtime_api(); + let mut runtime_api = client.runtime_api(); + + runtime_api.register_extension(sp_keystore::KeystoreExt::from(keystore)); for seed in seeds { runtime_api.generate_session_keys(at, Some(seed.as_bytes().to_vec()))?; diff --git a/primitives/state-machine/src/lib.rs b/primitives/state-machine/src/lib.rs index cc7de9080e3d0..3ef923851ffd8 100644 --- a/primitives/state-machine/src/lib.rs +++ b/primitives/state-machine/src/lib.rs @@ -168,14 +168,7 @@ mod execution { traits::{CallContext, CodeExecutor, RuntimeCode}, }; use sp_externalities::Extensions; - use std::{ - collections::{HashMap, HashSet}, - fmt, - }; - - const PROOF_CLOSE_TRANSACTION: &str = "\ - Closing a transaction that was started in this function. Client initiated transactions - are protected from being closed by the runtime. qed"; + use std::collections::{HashMap, HashSet}; pub(crate) type CallResult = Result, E>; @@ -185,21 +178,6 @@ mod execution { /// Trie backend with in-memory storage. pub type InMemoryBackend = TrieBackend, H>; - /// Strategy for executing a call into the runtime. - #[derive(Copy, Clone, Eq, PartialEq, Debug)] - pub enum ExecutionStrategy { - /// Execute with the native equivalent if it is compatible with the given wasm module; - /// otherwise fall back to the wasm. - NativeWhenPossible, - /// Use the given wasm module. - AlwaysWasm, - /// Run with both the wasm and the native variant (if compatible). Report any discrepancy - /// as an error. - Both, - /// First native, then if that fails or is not possible, wasm. - NativeElseWasm, - } - /// Storage backend trust level. #[derive(Debug, Clone)] pub enum BackendTrustLevel { @@ -211,73 +189,6 @@ mod execution { Untrusted, } - /// Like `ExecutionStrategy` only it also stores a handler in case of consensus failure. - #[derive(Clone)] - pub enum ExecutionManager { - /// Execute with the native equivalent if it is compatible with the given wasm module; - /// otherwise fall back to the wasm. - NativeWhenPossible, - /// Use the given wasm module. The backend on which code is executed code could be - /// trusted to provide all storage or not (i.e. the light client cannot be trusted to - /// provide for all storage queries since the storage entries it has come from an external - /// node). - AlwaysWasm(BackendTrustLevel), - /// Run with both the wasm and the native variant (if compatible). Call `F` in the case of - /// any discrepancy. - Both(F), - /// First native, then if that fails or is not possible, wasm. - NativeElseWasm, - } - - impl<'a, F> From<&'a ExecutionManager> for ExecutionStrategy { - fn from(s: &'a ExecutionManager) -> Self { - match *s { - ExecutionManager::NativeWhenPossible => ExecutionStrategy::NativeWhenPossible, - ExecutionManager::AlwaysWasm(_) => ExecutionStrategy::AlwaysWasm, - ExecutionManager::NativeElseWasm => ExecutionStrategy::NativeElseWasm, - ExecutionManager::Both(_) => ExecutionStrategy::Both, - } - } - } - - impl ExecutionStrategy { - /// Gets the corresponding manager for the execution strategy. - pub fn get_manager(self) -> ExecutionManager> { - match self { - ExecutionStrategy::AlwaysWasm => - ExecutionManager::AlwaysWasm(BackendTrustLevel::Trusted), - ExecutionStrategy::NativeWhenPossible => ExecutionManager::NativeWhenPossible, - ExecutionStrategy::NativeElseWasm => ExecutionManager::NativeElseWasm, - ExecutionStrategy::Both => ExecutionManager::Both(|wasm_result, native_result| { - warn!( - "Consensus error between wasm {:?} and native {:?}. Using wasm.", - wasm_result, native_result, - ); - warn!(" Native result {:?}", native_result); - warn!(" Wasm result {:?}", wasm_result); - wasm_result - }), - } - } - } - - /// Evaluate to ExecutionManager::NativeElseWasm, without having to figure out the type. - pub fn native_else_wasm() -> ExecutionManager> { - ExecutionManager::NativeElseWasm - } - - /// Evaluate to ExecutionManager::AlwaysWasm with trusted backend, without having to figure out - /// the type. - fn always_wasm() -> ExecutionManager> { - ExecutionManager::AlwaysWasm(BackendTrustLevel::Trusted) - } - - /// Evaluate ExecutionManager::AlwaysWasm with untrusted backend, without having to figure out - /// the type. - fn always_untrusted_wasm() -> ExecutionManager> { - ExecutionManager::AlwaysWasm(BackendTrustLevel::Untrusted) - } - /// The substrate state machine. pub struct StateMachine<'a, B, H, Exec> where @@ -289,7 +200,7 @@ mod execution { method: &'a str, call_data: &'a [u8], overlay: &'a mut OverlayedChanges, - extensions: Extensions, + extensions: &'a mut Extensions, storage_transaction_cache: Option<&'a mut StorageTransactionCache>, runtime_code: &'a RuntimeCode<'a>, stats: StateMachineStats, @@ -324,7 +235,7 @@ mod execution { exec: &'a Exec, method: &'a str, call_data: &'a [u8], - extensions: Extensions, + extensions: &'a mut Extensions, runtime_code: &'a RuntimeCode, context: CallContext, ) -> Self { @@ -372,13 +283,7 @@ mod execution { /// blocks (e.g. a transaction at a time), ensure a different method is used. /// /// Returns the SCALE encoded result of the executed function. - pub fn execute(&mut self, strategy: ExecutionStrategy) -> Result, Box> { - // We are not giving a native call and thus we are sure that the result can never be a - // native value. - self.execute_using_consensus_failure_handler(strategy.get_manager()) - } - - fn execute_aux(&mut self, use_native: bool) -> (CallResult, bool) { + pub fn execute(&mut self) -> Result, Box> { let mut cache = StorageTransactionCache::default(); let cache = match self.storage_transaction_cache.as_mut() { @@ -390,7 +295,7 @@ mod execution { .enter_runtime() .expect("StateMachine is never called from the runtime; qed"); - let mut ext = Ext::new(self.overlay, cache, self.backend, Some(&mut self.extensions)); + let mut ext = Ext::new(self.overlay, cache, self.backend, Some(self.extensions)); let ext_id = ext.id; @@ -403,14 +308,10 @@ mod execution { "Call", ); - let (result, was_native) = self.exec.call( - &mut ext, - self.runtime_code, - self.method, - self.call_data, - use_native, - self.context, - ); + let result = self + .exec + .call(&mut ext, self.runtime_code, self.method, self.call_data, false, self.context) + .0; self.overlay .exit_runtime() @@ -419,92 +320,11 @@ mod execution { trace!( target: "state", ext_id = %HexDisplay::from(&ext_id.to_le_bytes()), - ?was_native, ?result, "Return", ); - (result, was_native) - } - - fn execute_call_with_both_strategy( - &mut self, - on_consensus_failure: Handler, - ) -> CallResult - where - Handler: - FnOnce(CallResult, CallResult) -> CallResult, - { - self.overlay.start_transaction(); - let (result, was_native) = self.execute_aux(true); - - if was_native { - self.overlay.rollback_transaction().expect(PROOF_CLOSE_TRANSACTION); - let (wasm_result, _) = self.execute_aux(false); - - if (result.is_ok() && - wasm_result.is_ok() && result.as_ref().ok() == wasm_result.as_ref().ok()) || - result.is_err() && wasm_result.is_err() - { - result - } else { - on_consensus_failure(wasm_result, result) - } - } else { - self.overlay.commit_transaction().expect(PROOF_CLOSE_TRANSACTION); - result - } - } - - fn execute_call_with_native_else_wasm_strategy(&mut self) -> CallResult { - self.overlay.start_transaction(); - let (result, was_native) = self.execute_aux(true); - - if !was_native || result.is_ok() { - self.overlay.commit_transaction().expect(PROOF_CLOSE_TRANSACTION); - result - } else { - self.overlay.rollback_transaction().expect(PROOF_CLOSE_TRANSACTION); - self.execute_aux(false).0 - } - } - - /// Execute a call using the given state backend, overlayed changes, and call executor. - /// - /// On an error, no prospective changes are written to the overlay. - /// - /// Note: changes to code will be in place if this call is made again. For running partial - /// blocks (e.g. a transaction at a time), ensure a different method is used. - /// - /// Returns the result of the executed function either in native representation `R` or - /// in SCALE encoded representation. - pub fn execute_using_consensus_failure_handler( - &mut self, - manager: ExecutionManager, - ) -> Result, Box> - where - Handler: - FnOnce(CallResult, CallResult) -> CallResult, - { - let result = { - match manager { - ExecutionManager::Both(on_consensus_failure) => - self.execute_call_with_both_strategy(on_consensus_failure), - ExecutionManager::NativeElseWasm => - self.execute_call_with_native_else_wasm_strategy(), - ExecutionManager::AlwaysWasm(trust_level) => { - let _abort_guard = match trust_level { - BackendTrustLevel::Trusted => None, - BackendTrustLevel::Untrusted => - Some(sp_panic_handler::AbortGuard::never_abort()), - }; - self.execute_aux(false).0 - }, - ExecutionManager::NativeWhenPossible => self.execute_aux(true).0, - } - }; - - result.map_err(|e| Box::new(e) as _) + result.map_err(|e| Box::new(e) as Box<_>) } } @@ -531,7 +351,7 @@ mod execution { method, call_data, runtime_code, - Default::default(), + &mut Default::default(), ) } @@ -551,7 +371,7 @@ mod execution { method: &str, call_data: &[u8], runtime_code: &RuntimeCode, - extensions: Extensions, + extensions: &mut Extensions, ) -> Result<(Vec, StorageProof), Box> where S: trie_backend_essence::TrieBackendStorage, @@ -572,7 +392,7 @@ mod execution { runtime_code, CallContext::Offchain, ) - .execute_using_consensus_failure_handler::<_>(always_wasm())?; + .execute()?; let proof = proving_backend .extract_proof() @@ -627,11 +447,11 @@ mod execution { exec, method, call_data, - Extensions::default(), + &mut Extensions::default(), runtime_code, CallContext::Offchain, ) - .execute_using_consensus_failure_handler(always_untrusted_wasm()) + .execute() } /// Generate storage read proof. @@ -1356,6 +1176,7 @@ mod tests { let backend = trie_backend::tests::test_trie(state_version, None, None); let mut overlayed_changes = Default::default(); let wasm_code = RuntimeCode::empty(); + let mut execution_extensions = &mut Default::default(); let mut state_machine = StateMachine::new( &backend, @@ -1367,12 +1188,12 @@ mod tests { }, "test", &[], - Default::default(), + &mut execution_extensions, &wasm_code, CallContext::Offchain, ); - assert_eq!(state_machine.execute(ExecutionStrategy::NativeWhenPossible).unwrap(), vec![66]); + assert_eq!(state_machine.execute().unwrap(), vec![66]); } #[test] @@ -1384,6 +1205,7 @@ mod tests { let backend = trie_backend::tests::test_trie(state_version, None, None); let mut overlayed_changes = Default::default(); let wasm_code = RuntimeCode::empty(); + let mut execution_extensions = &mut Default::default(); let mut state_machine = StateMachine::new( &backend, @@ -1395,47 +1217,12 @@ mod tests { }, "test", &[], - Default::default(), - &wasm_code, - CallContext::Offchain, - ); - - assert_eq!(state_machine.execute(ExecutionStrategy::NativeElseWasm).unwrap(), vec![66]); - } - - #[test] - fn dual_execution_strategy_detects_consensus_failure() { - dual_execution_strategy_detects_consensus_failure_inner(StateVersion::V0); - dual_execution_strategy_detects_consensus_failure_inner(StateVersion::V1); - } - fn dual_execution_strategy_detects_consensus_failure_inner(state_version: StateVersion) { - let mut consensus_failed = false; - let backend = trie_backend::tests::test_trie(state_version, None, None); - let mut overlayed_changes = Default::default(); - let wasm_code = RuntimeCode::empty(); - - let mut state_machine = StateMachine::new( - &backend, - &mut overlayed_changes, - &DummyCodeExecutor { - native_available: true, - native_succeeds: true, - fallback_succeeds: false, - }, - "test", - &[], - Default::default(), + &mut execution_extensions, &wasm_code, CallContext::Offchain, ); - assert!(state_machine - .execute_using_consensus_failure_handler(ExecutionManager::Both(|we, _ne| { - consensus_failed = true; - we - }),) - .is_err()); - assert!(consensus_failed); + assert_eq!(state_machine.execute().unwrap(), vec![66]); } #[test] diff --git a/primitives/test-primitives/src/lib.rs b/primitives/test-primitives/src/lib.rs index 913cb762d92a5..82bdb6967b842 100644 --- a/primitives/test-primitives/src/lib.rs +++ b/primitives/test-primitives/src/lib.rs @@ -71,7 +71,7 @@ pub type Hash = H256; /// The block number type used in this runtime. pub type BlockNumber = u64; /// Index of a transaction. -pub type Index = u64; +pub type Nonce = u64; /// The item of a block digest. pub type DigestItem = sp_runtime::generic::DigestItem; /// The digest of a block. diff --git a/scripts/ci/gitlab/pipeline/test.yml b/scripts/ci/gitlab/pipeline/test.yml index dc41895b3a16e..8995f5aab7811 100644 --- a/scripts/ci/gitlab/pipeline/test.yml +++ b/scripts/ci/gitlab/pipeline/test.yml @@ -115,8 +115,8 @@ cargo-check-benches: rusty-cachier cache upload ;; 2) - cargo run --locked --release -p node-bench -- ::node::import::native::sr25519::transfer_keep_alive::paritydb::small --json - | tee ./artifacts/benches/$CI_COMMIT_REF_NAME-$CI_COMMIT_SHORT_SHA/::node::import::native::sr25519::transfer_keep_alive::paritydb::small.json + cargo run --locked --release -p node-bench -- ::node::import::sr25519::transfer_keep_alive::paritydb::small --json + | tee ./artifacts/benches/$CI_COMMIT_REF_NAME-$CI_COMMIT_SHORT_SHA/::node::import::sr25519::transfer_keep_alive::paritydb::small.json ;; esac @@ -304,7 +304,7 @@ quick-benchmarks: WASM_BUILD_RUSTFLAGS: "-C debug-assertions -D warnings" script: - rusty-cachier snapshot create - - time cargo run --locked --release --features runtime-benchmarks -- benchmark pallet --execution wasm --wasm-execution compiled --chain dev --pallet "*" --extrinsic "*" --steps 2 --repeat 1 + - time cargo run --locked --release --features runtime-benchmarks -- benchmark pallet --wasm-execution compiled --chain dev --pallet "*" --extrinsic "*" --steps 2 --repeat 1 - rusty-cachier cache upload test-frame-examples-compile-to-wasm: diff --git a/scripts/run_all_benchmarks.sh b/scripts/run_all_benchmarks.sh index 727b49e26afe5..83848100a7e51 100755 --- a/scripts/run_all_benchmarks.sh +++ b/scripts/run_all_benchmarks.sh @@ -119,7 +119,6 @@ for PALLET in "${PALLETS[@]}"; do --repeat=20 \ --pallet="$PALLET" \ --extrinsic="*" \ - --execution=wasm \ --wasm-execution=compiled \ --heap-pages=4096 \ --output="$WEIGHT_FILE" \ @@ -137,7 +136,6 @@ echo "[+] Benchmarking block and extrinsic overheads..." OUTPUT=$( $SUBSTRATE benchmark overhead \ --chain=dev \ - --execution=wasm \ --wasm-execution=compiled \ --weight-path="./frame/support/src/weights/" \ --header="./HEADER-APACHE2" \ diff --git a/test-utils/client/src/lib.rs b/test-utils/client/src/lib.rs index 94006fd9acb8e..90e15e0f8d53e 100644 --- a/test-utils/client/src/lib.rs +++ b/test-utils/client/src/lib.rs @@ -22,10 +22,7 @@ pub mod client_ext; pub use self::client_ext::{ClientBlockImportExt, ClientExt}; -pub use sc_client_api::{ - execution_extensions::{ExecutionExtensions, ExecutionStrategies}, - BadBlocks, ForkBlocks, -}; +pub use sc_client_api::{execution_extensions::ExecutionExtensions, BadBlocks, ForkBlocks}; pub use sc_client_db::{self, Backend, BlocksPruning}; pub use sc_executor::{self, NativeElseWasmExecutor, WasmExecutionMethod, WasmExecutor}; pub use sc_service::{client, RpcHandlers}; @@ -35,7 +32,6 @@ pub use sp_keyring::{ }; pub use sp_keystore::{Keystore, KeystorePtr}; pub use sp_runtime::{Storage, StorageChild}; -pub use sp_state_machine::ExecutionStrategy; use futures::{future::Future, stream::StreamExt}; use sc_client_api::BlockchainEvents; @@ -67,14 +63,12 @@ impl GenesisInit for () { /// A builder for creating a test client instance. pub struct TestClientBuilder { - execution_strategies: ExecutionStrategies, genesis_init: G, /// The key is an unprefixed storage key, this only contains /// default child trie content. child_storage_extension: HashMap, StorageChild>, backend: Arc, _executor: std::marker::PhantomData, - keystore: Option, fork_blocks: ForkBlocks, bad_blocks: BadBlocks, enable_offchain_indexing_api: bool, @@ -119,11 +113,9 @@ impl pub fn with_backend(backend: Arc) -> Self { TestClientBuilder { backend, - execution_strategies: ExecutionStrategies::default(), child_storage_extension: Default::default(), genesis_init: Default::default(), _executor: Default::default(), - keystore: None, fork_blocks: None, bad_blocks: None, enable_offchain_indexing_api: false, @@ -131,12 +123,6 @@ impl } } - /// Set the keystore that should be used by the externalities. - pub fn set_keystore(mut self, keystore: KeystorePtr) -> Self { - self.keystore = Some(keystore); - self - } - /// Alter the genesis storage parameters. pub fn genesis_init_mut(&mut self) -> &mut G { &mut self.genesis_init @@ -162,18 +148,6 @@ impl self } - /// Set the execution strategy that should be used by all contexts. - pub fn set_execution_strategy(mut self, execution_strategy: ExecutionStrategy) -> Self { - self.execution_strategies = ExecutionStrategies { - syncing: execution_strategy, - importing: execution_strategy, - block_construction: execution_strategy, - offchain_worker: execution_strategy, - other: execution_strategy, - }; - self - } - /// Sets custom block rules. pub fn set_block_rules( mut self, @@ -296,12 +270,7 @@ impl self.backend.clone(), executor.clone(), Default::default(), - ExecutionExtensions::new( - self.execution_strategies.clone(), - self.keystore.clone(), - sc_offchain::OffchainDb::factory_from_backend(&*self.backend), - Arc::new(executor), - ), + ExecutionExtensions::new(None, Arc::new(executor)), ) .expect("Creates LocalCallExecutor"); diff --git a/test-utils/runtime/src/extrinsic.rs b/test-utils/runtime/src/extrinsic.rs index a6e13226face0..05ffb7db5d5b9 100644 --- a/test-utils/runtime/src/extrinsic.rs +++ b/test-utils/runtime/src/extrinsic.rs @@ -19,7 +19,7 @@ use crate::{ substrate_test_pallet::pallet::Call as PalletCall, AccountId, Balance, BalancesCall, - CheckSubstrateCall, Extrinsic, Index, Pair, RuntimeCall, SignedPayload, TransferData, + CheckSubstrateCall, Extrinsic, Nonce, Pair, RuntimeCall, SignedPayload, TransferData, }; use codec::Encode; use frame_system::{CheckNonce, CheckWeight}; @@ -81,7 +81,7 @@ impl TryFrom<&Extrinsic> for TransferData { pub struct ExtrinsicBuilder { function: RuntimeCall, signer: Option, - nonce: Option, + nonce: Option, } impl ExtrinsicBuilder { @@ -176,7 +176,7 @@ impl ExtrinsicBuilder { } /// Given `nonce` will be set in `Extrinsic` - pub fn nonce(mut self, nonce: Index) -> Self { + pub fn nonce(mut self, nonce: Nonce) -> Self { self.nonce = Some(nonce); self } diff --git a/test-utils/runtime/src/genesismap.rs b/test-utils/runtime/src/genesismap.rs index f1289ce41a583..97504c232aef5 100644 --- a/test-utils/runtime/src/genesismap.rs +++ b/test-utils/runtime/src/genesismap.rs @@ -119,6 +119,7 @@ impl GenesisStorageBuilder { let genesis_config = RuntimeGenesisConfig { system: frame_system::GenesisConfig { code: self.wasm_code.clone().unwrap_or(wasm_binary_unwrap().to_vec()), + ..Default::default() }, babe: pallet_babe::GenesisConfig { authorities: authorities_sr25519 @@ -127,9 +128,11 @@ impl GenesisStorageBuilder { .map(|x| (x.into(), 1)) .collect(), epoch_config: Some(crate::TEST_RUNTIME_BABE_EPOCH_CONFIGURATION), + ..Default::default() }, substrate_test: substrate_test_pallet::GenesisConfig { authorities: authorities_sr25519.clone(), + ..Default::default() }, balances: pallet_balances::GenesisConfig { balances: self.balances.clone() }, }; @@ -138,10 +141,9 @@ impl GenesisStorageBuilder { .build_storage() .expect("Build storage from substrate-test-runtime GenesisConfig"); - storage.top.insert( - well_known_keys::HEAP_PAGES.into(), - self.heap_pages_override.unwrap_or(16_u64).encode(), - ); + if let Some(heap_pages) = self.heap_pages_override { + storage.top.insert(well_known_keys::HEAP_PAGES.into(), heap_pages.encode()); + } storage.top.extend(self.extra_storage.top.clone()); storage.children_default.extend(self.extra_storage.children_default.clone()); diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index d02b378e154f2..ee391a6ec2147 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -130,7 +130,7 @@ pub struct TransferData { pub from: AccountId, pub to: AccountId, pub amount: Balance, - pub nonce: Index, + pub nonce: Nonce, } /// The address format for describing accounts. @@ -156,7 +156,7 @@ pub type Hashing = BlakeTwo256; /// The block number type used in this runtime. pub type BlockNumber = u64; /// Index of a transaction. -pub type Index = u64; +pub type Nonce = u64; /// The item of a block digest. pub type DigestItem = sp_runtime::generic::DigestItem; /// The digest of a block. @@ -293,10 +293,7 @@ impl sp_runtime::traits::SignedExtension for CheckSubstrateCall { } construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = Extrinsic + pub enum Runtime { System: frame_system, Babe: pallet_babe, @@ -348,13 +345,12 @@ impl frame_system::pallet::Config for Runtime { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = Index; - type BlockNumber = BlockNumber; + type Nonce = Nonce; type Hash = H256; type Hashing = Hashing; type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU64<2400>; type DbWeight = (); @@ -530,8 +526,8 @@ impl_runtime_apis! { } } - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Index { + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { System::account_nonce(account) } } @@ -845,8 +841,12 @@ pub mod storage_key_generator { /// Generate the hashed storage keys from the raw literals. These keys are expected to be be in /// storage with given substrate-test runtime. - pub fn generate_expected_storage_hashed_keys() -> Vec { - let literals: Vec<&[u8]> = vec![b":code", b":extrinsic_index", b":heappages"]; + pub fn generate_expected_storage_hashed_keys(custom_heap_pages: bool) -> Vec { + let mut literals: Vec<&[u8]> = vec![b":code", b":extrinsic_index"]; + + if custom_heap_pages { + literals.push(b":heappages"); + } let keys: Vec> = vec![ vec![b"Babe", b"Authorities"], @@ -906,8 +906,11 @@ pub mod storage_key_generator { /// that would be generated by `generate_expected_storage_hashed_keys`. This list is provided /// for the debugging convenience only. Value of each hex-string is documented with the literal /// origin. - pub fn get_expected_storage_hashed_keys() -> Vec { - [ + /// + /// `custom_heap_pages`: Should be set to `true` when the state contains the `:heap_pages` key + /// aka when overriding the heap pages to be used by the executor. + pub fn get_expected_storage_hashed_keys(custom_heap_pages: bool) -> Vec<&'static str> { + let mut res = vec![ //System|:__STORAGE_VERSION__: "00771836bebdd29870ff246d305c578c4e7b9012096b41c4eb3aaf947f6ea429", //SubstrateTest|Authorities @@ -977,20 +980,25 @@ pub mod storage_key_generator { "3a636f6465", // :extrinsic_index "3a65787472696e7369635f696e646578", - // :heappages - "3a686561707061676573", // Balances|:__STORAGE_VERSION__: "c2261276cc9d1f8598ea4b6a74b15c2f4e7b9012096b41c4eb3aaf947f6ea429", // Balances|TotalIssuance "c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80", - ].into_iter().map(String::from).collect::>() + ]; + + if custom_heap_pages { + // :heappages + res.push("3a686561707061676573"); + } + + res } #[test] fn expected_keys_vec_are_matching() { assert_eq!( - storage_key_generator::get_expected_storage_hashed_keys(), - storage_key_generator::generate_expected_storage_hashed_keys(), + storage_key_generator::get_expected_storage_hashed_keys(false), + storage_key_generator::generate_expected_storage_hashed_keys(false), ); } } @@ -1001,15 +1009,14 @@ mod tests { use codec::Encode; use frame_support::dispatch::DispatchInfo; use sc_block_builder::BlockBuilderProvider; - use sp_api::ProvideRuntimeApi; + use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_consensus::BlockOrigin; - use sp_core::{storage::well_known_keys::HEAP_PAGES, ExecutionContext}; + use sp_core::{storage::well_known_keys::HEAP_PAGES, traits::CallContext}; use sp_keyring::AccountKeyring; use sp_runtime::{ traits::{Hash as _, SignedExtension}, transaction_validity::{InvalidTransaction, ValidTransaction}, }; - use sp_state_machine::ExecutionStrategy; use substrate_test_runtime_client::{ prelude::*, runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, }; @@ -1019,20 +1026,15 @@ mod tests { // This tests that the on-chain `HEAP_PAGES` parameter is respected. // Create a client devoting only 8 pages of wasm memory. This gives us ~512k of heap memory. - let mut client = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::AlwaysWasm) - .set_heap_pages(8) - .build(); + let mut client = TestClientBuilder::new().set_heap_pages(8).build(); let best_hash = client.chain_info().best_hash; // Try to allocate 1024k of memory on heap. This is going to fail since it is twice larger // than the heap. - let ret = client.runtime_api().vec_with_capacity_with_context( - best_hash, - // Use `BlockImport` to ensure we use the on chain heap pages as configured above. - ExecutionContext::Importing, - 1048576, - ); + let mut runtime_api = client.runtime_api(); + // This is currently required to allocate the 1024k of memory as configured above. + runtime_api.set_call_context(CallContext::Onchain); + let ret = runtime_api.vec_with_capacity(best_hash, 1048576); assert!(ret.is_err()); // Create a block that sets the `:heap_pages` to 32 pages of memory which corresponds to @@ -1054,8 +1056,7 @@ mod tests { #[test] fn test_storage() { - let client = - TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::Both).build(); + let client = TestClientBuilder::new().build(); let runtime_api = client.runtime_api(); let best_hash = client.chain_info().best_hash; @@ -1080,8 +1081,7 @@ mod tests { let backend = sp_state_machine::TrieBackendBuilder::<_, crate::Hashing>::new(db, root).build(); let proof = sp_state_machine::prove_read(backend, vec![b"value3"]).unwrap(); - let client = - TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::Both).build(); + let client = TestClientBuilder::new().build(); let runtime_api = client.runtime_api(); let best_hash = client.chain_info().best_hash; @@ -1108,7 +1108,7 @@ mod tests { .cloned() .map(storage_key_generator::hex) .collect::>(), - storage_key_generator::get_expected_storage_hashed_keys() + storage_key_generator::get_expected_storage_hashed_keys(false) ); } diff --git a/test-utils/runtime/src/substrate_test_pallet.rs b/test-utils/runtime/src/substrate_test_pallet.rs index 0864c952b70c4..ed1ad990472ba 100644 --- a/test-utils/runtime/src/substrate_test_pallet.rs +++ b/test-utils/runtime/src/substrate_test_pallet.rs @@ -24,7 +24,7 @@ use frame_support::{pallet_prelude::*, storage}; use sp_core::sr25519::Public; use sp_runtime::{ - traits::{BlakeTwo256, Hash}, + traits::Hash, transaction_validity::{ InvalidTransaction, TransactionSource, TransactionValidity, ValidTransaction, }, @@ -41,7 +41,7 @@ pub mod pallet { use crate::TransferData; use frame_system::pallet_prelude::*; use sp_core::storage::well_known_keys; - use sp_runtime::{transaction_validity::TransactionPriority, Perbill}; + use sp_runtime::{traits::BlakeTwo256, transaction_validity::TransactionPriority, Perbill}; #[pallet::pallet] #[pallet::without_storage_info] @@ -55,13 +55,15 @@ pub mod pallet { pub type Authorities = StorageValue<_, Vec, ValueQuery>; #[pallet::genesis_config] - #[derive(Default)] - pub struct GenesisConfig { + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { pub authorities: Vec, + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { >::put(self.authorities.clone()); } diff --git a/test-utils/runtime/transaction-pool/src/lib.rs b/test-utils/runtime/transaction-pool/src/lib.rs index 8e28449661650..7b52920044027 100644 --- a/test-utils/runtime/transaction-pool/src/lib.rs +++ b/test-utils/runtime/transaction-pool/src/lib.rs @@ -36,7 +36,7 @@ use sp_runtime::{ use std::collections::{BTreeMap, HashMap, HashSet}; use substrate_test_runtime_client::{ runtime::{ - AccountId, Block, BlockNumber, Extrinsic, ExtrinsicBuilder, Hash, Header, Index, Transfer, + AccountId, Block, BlockNumber, Extrinsic, ExtrinsicBuilder, Hash, Header, Nonce, Transfer, TransferData, }, AccountKeyring::{self, *}, @@ -377,7 +377,7 @@ impl sp_blockchain::HeaderMetadata for TestApi { /// Generate transfer extrinsic with a given nonce. /// /// Part of the test api. -pub fn uxt(who: AccountKeyring, nonce: Index) -> Extrinsic { +pub fn uxt(who: AccountKeyring, nonce: Nonce) -> Extrinsic { let dummy = codec::Decode::decode(&mut TrailingZeroInput::zeroes()).unwrap(); let transfer = Transfer { from: who.into(), to: dummy, nonce, amount: 1 }; ExtrinsicBuilder::new_transfer(transfer).build() diff --git a/utils/frame/benchmarking-cli/src/block/cmd.rs b/utils/frame/benchmarking-cli/src/block/cmd.rs index 0192372fa33a7..90b71cd78c2a4 100644 --- a/utils/frame/benchmarking-cli/src/block/cmd.rs +++ b/utils/frame/benchmarking-cli/src/block/cmd.rs @@ -39,12 +39,12 @@ use super::bench::{Benchmark, BenchmarkParams}; /// did not use more weight than declared which would otherwise be an issue. /// To test this with a dev node, first create one with a temp directory: /// -/// $ substrate --dev -d /tmp/my-dev --execution wasm --wasm-execution compiled +/// $ substrate --dev -d /tmp/my-dev --wasm-execution compiled /// /// And wait some time to let it produce 3 blocks. Then benchmark them with: /// /// $ substrate benchmark-block --from 1 --to 3 --dev -d /tmp/my-dev -/// --execution wasm --wasm-execution compiled --pruning archive +/// --wasm-execution compiled --pruning archive /// /// The output will be similar to this: /// diff --git a/utils/frame/benchmarking-cli/src/overhead/README.md b/utils/frame/benchmarking-cli/src/overhead/README.md index 85bcc7fa36f2d..390bc09e41701 100644 --- a/utils/frame/benchmarking-cli/src/overhead/README.md +++ b/utils/frame/benchmarking-cli/src/overhead/README.md @@ -103,12 +103,12 @@ Writing weights to "extrinsic_weights.rs" The complete command for Polkadot looks like this: ```sh -cargo run --profile=production -- benchmark overhead --chain=polkadot-dev --execution=wasm --wasm-execution=compiled --weight-path=runtime/polkadot/constants/src/weights/ +cargo run --profile=production -- benchmark overhead --chain=polkadot-dev --wasm-execution=compiled --weight-path=runtime/polkadot/constants/src/weights/ ``` This will overwrite the the [block_weights.rs](https://github.com/paritytech/polkadot/blob/c254e5975711a6497af256f6831e9a6c752d28f5/runtime/polkadot/constants/src/weights/block_weights.rs) and [extrinsic_weights.rs](https://github.com/paritytech/polkadot/blob/c254e5975711a6497af256f6831e9a6c752d28f5/runtime/polkadot/constants/src/weights/extrinsic_weights.rs) files in the Polkadot runtime directory. You can try the same for *Rococo* and to see that the results slightly differ. -👉 It is paramount to use `--profile=production`, `--execution=wasm` and `--wasm-execution=compiled` as the results are otherwise useless. +👉 It is paramount to use `--profile=production` and `--wasm-execution=compiled` as the results are otherwise useless. ## Output Interpretation @@ -122,7 +122,6 @@ Minimizing this is important to have a large transaction throughput. - `--weight-path` Set the output directory or file to write the weights to. - `--repeat` Set the repetitions of both benchmarks. - `--warmup` Set the rounds of warmup before measuring. -- `--execution` Should be set to `wasm` for correct results. - `--wasm-execution` Should be set to `compiled` for correct results. - [`--mul`](../shared/README.md#arguments) - [`--add`](../shared/README.md#arguments) diff --git a/utils/frame/benchmarking-cli/src/pallet/command.rs b/utils/frame/benchmarking-cli/src/pallet/command.rs index 7f587d9c7fa6a..1d2d81e357724 100644 --- a/utils/frame/benchmarking-cli/src/pallet/command.rs +++ b/utils/frame/benchmarking-cli/src/pallet/command.rs @@ -23,9 +23,7 @@ use frame_benchmarking::{ }; use frame_support::traits::StorageInfo; use linked_hash_map::LinkedHashMap; -use sc_cli::{ - execution_method_from_cli, CliConfiguration, ExecutionStrategy, Result, SharedParams, -}; +use sc_cli::{execution_method_from_cli, CliConfiguration, Result, SharedParams}; use sc_client_db::BenchmarkingState; use sc_executor::WasmExecutor; use sc_service::Configuration; @@ -182,7 +180,6 @@ impl PalletCmd { } let spec = config.chain_spec; - let strategy = self.execution.unwrap_or(ExecutionStrategy::Wasm); let pallet = self.pallet.clone().unwrap_or_default(); let pallet = pallet.as_bytes(); let extrinsic = self.extrinsic.clone().unwrap_or_default(); @@ -243,11 +240,11 @@ impl PalletCmd { &executor, "Benchmark_benchmark_metadata", &(self.extra).encode(), - extensions(), + &mut extensions(), &sp_state_machine::backend::BackendRuntimeCode::new(state).runtime_code()?, CallContext::Offchain, ) - .execute(strategy.into()) + .execute() .map_err(|e| format!("{}: {}", ERROR_METADATA_NOT_FOUND, e))?; let (list, storage_info) = @@ -379,12 +376,12 @@ impl PalletCmd { 1, // no need to do internal repeats ) .encode(), - extensions(), + &mut extensions(), &sp_state_machine::backend::BackendRuntimeCode::new(state) .runtime_code()?, CallContext::Offchain, ) - .execute(strategy.into()) + .execute() .map_err(|e| { format!("Error executing and verifying runtime benchmark: {}", e) })?; @@ -419,12 +416,12 @@ impl PalletCmd { self.repeat, ) .encode(), - extensions(), + &mut extensions(), &sp_state_machine::backend::BackendRuntimeCode::new(state) .runtime_code()?, CallContext::Offchain, ) - .execute(strategy.into()) + .execute() .map_err(|e| format!("Error executing runtime benchmark: {}", e))?; let batch = @@ -451,12 +448,12 @@ impl PalletCmd { self.repeat, ) .encode(), - extensions(), + &mut extensions(), &sp_state_machine::backend::BackendRuntimeCode::new(state) .runtime_code()?, CallContext::Offchain, ) - .execute(strategy.into()) + .execute() .map_err(|e| format!("Error executing runtime benchmark: {}", e))?; let batch = diff --git a/utils/frame/benchmarking-cli/src/pallet/mod.rs b/utils/frame/benchmarking-cli/src/pallet/mod.rs index ca87ddebb32be..5090a601f0c9a 100644 --- a/utils/frame/benchmarking-cli/src/pallet/mod.rs +++ b/utils/frame/benchmarking-cli/src/pallet/mod.rs @@ -20,8 +20,8 @@ mod writer; use crate::shared::HostInfoParams; use sc_cli::{ - ExecutionStrategy, WasmExecutionMethod, WasmtimeInstantiationStrategy, - DEFAULT_WASMTIME_INSTANTIATION_STRATEGY, DEFAULT_WASM_EXECUTION_METHOD, + WasmExecutionMethod, WasmtimeInstantiationStrategy, DEFAULT_WASMTIME_INSTANTIATION_STRATEGY, + DEFAULT_WASM_EXECUTION_METHOD, }; use std::{fmt::Debug, path::PathBuf}; @@ -129,10 +129,6 @@ pub struct PalletCmd { #[clap(flatten)] pub shared_params: sc_cli::SharedParams, - /// The execution strategy that should be used for benchmarks. - #[arg(long, value_name = "STRATEGY", value_enum, ignore_case = true)] - pub execution: Option, - /// Method for executing Wasm runtime code. #[arg( long = "wasm-execution", diff --git a/utils/frame/benchmarking-cli/src/pallet/writer.rs b/utils/frame/benchmarking-cli/src/pallet/writer.rs index fd1b92b90c181..69c95d13c0985 100644 --- a/utils/frame/benchmarking-cli/src/pallet/writer.rs +++ b/utils/frame/benchmarking-cli/src/pallet/writer.rs @@ -90,7 +90,6 @@ struct CmdData { repeat: u32, lowest_range_values: Vec, highest_range_values: Vec, - execution: String, wasm_execution: String, chain: String, db_cache: u32, @@ -425,7 +424,6 @@ pub(crate) fn write_results( repeat: cmd.repeat, lowest_range_values: cmd.lowest_range_values.clone(), highest_range_values: cmd.highest_range_values.clone(), - execution: format!("{:?}", cmd.execution), wasm_execution: cmd.wasm_method.to_string(), chain: format!("{:?}", cmd.shared_params.chain), db_cache: cmd.database_cache_size, diff --git a/utils/frame/rpc/support/src/lib.rs b/utils/frame/rpc/support/src/lib.rs index 431bcdab03288..2d8e45cbfc69f 100644 --- a/utils/frame/rpc/support/src/lib.rs +++ b/utils/frame/rpc/support/src/lib.rs @@ -40,12 +40,9 @@ use sp_storage::{StorageData, StorageKey}; /// # use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::Header}; /// # /// # construct_runtime!( -/// # pub enum TestRuntime where -/// # Block = frame_system::mocking::MockBlock, -/// # NodeBlock = frame_system::mocking::MockBlock, -/// # UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic, +/// # pub enum TestRuntime /// # { -/// # System: frame_system::{Pallet, Call, Config, Storage, Event}, +/// # System: frame_system::{Pallet, Call, Config, Storage, Event}, /// # Test: pallet_test::{Pallet, Storage}, /// # } /// # ); @@ -58,13 +55,12 @@ use sp_storage::{StorageData, StorageKey}; /// # type BlockLength = (); /// # type RuntimeOrigin = RuntimeOrigin; /// # type RuntimeCall = RuntimeCall; -/// # type Index = u64; -/// # type BlockNumber = u64; +/// # type Nonce = u64; /// # type Hash = Hash; /// # type Hashing = BlakeTwo256; /// # type AccountId = u64; /// # type Lookup = IdentityLookup; -/// # type Header = Header; +/// # type Block = frame_system::mocking::MockBlock; /// # type RuntimeEvent = RuntimeEvent; /// # type BlockHashCount = (); /// # type DbWeight = (); diff --git a/utils/frame/rpc/system/src/lib.rs b/utils/frame/rpc/system/src/lib.rs index 26efa02970efe..1eff71e3390a3 100644 --- a/utils/frame/rpc/system/src/lib.rs +++ b/utils/frame/rpc/system/src/lib.rs @@ -38,14 +38,14 @@ pub use frame_system_rpc_runtime_api::AccountNonceApi; /// System RPC methods. #[rpc(client, server)] -pub trait SystemApi { +pub trait SystemApi { /// Returns the next valid index (aka nonce) for given account. /// /// This method takes into consideration all pending transactions /// currently in the pool and if no transactions are found in the pool /// it fallbacks to query the index from the runtime (aka. state nonce). #[method(name = "system_accountNextIndex", aliases = ["account_nextIndex"])] - async fn nonce(&self, account: AccountId) -> RpcResult; + async fn nonce(&self, account: AccountId) -> RpcResult; /// Dry run an extrinsic at a given block. Return SCALE encoded ApplyExtrinsicResult. #[method(name = "system_dryRun", aliases = ["system_dryRunAt"])] @@ -85,20 +85,20 @@ impl System { } #[async_trait] -impl - SystemApiServer<::Hash, AccountId, Index> for System +impl + SystemApiServer<::Hash, AccountId, Nonce> for System where C: sp_api::ProvideRuntimeApi, C: HeaderBackend, C: Send + Sync + 'static, - C::Api: AccountNonceApi, + C::Api: AccountNonceApi, C::Api: BlockBuilder, P: TransactionPool + 'static, Block: traits::Block, AccountId: Clone + Display + Codec + Send + 'static, - Index: Clone + Display + Codec + Send + traits::AtLeast32Bit + 'static, + Nonce: Clone + Display + Codec + Send + traits::AtLeast32Bit + 'static, { - async fn nonce(&self, account: AccountId) -> RpcResult { + async fn nonce(&self, account: AccountId) -> RpcResult { let api = self.client.runtime_api(); let best = self.client.info().best_hash; @@ -176,11 +176,11 @@ where /// Adjust account nonce from state, so that tx with the nonce will be /// placed after all ready txpool transactions. -fn adjust_nonce(pool: &P, account: AccountId, nonce: Index) -> Index +fn adjust_nonce(pool: &P, account: AccountId, nonce: Nonce) -> Nonce where P: TransactionPool, AccountId: Clone + std::fmt::Display + Encode, - Index: Clone + std::fmt::Display + Encode + traits::AtLeast32Bit + 'static, + Nonce: Clone + std::fmt::Display + Encode + traits::AtLeast32Bit + 'static, { log::debug!(target: "rpc", "State nonce for {}: {}", account, nonce); // Now we need to query the transaction pool diff --git a/utils/frame/try-runtime/cli/src/lib.rs b/utils/frame/try-runtime/cli/src/lib.rs index fb4a644e2004c..fbc55ad1dce6f 100644 --- a/utils/frame/try-runtime/cli/src/lib.rs +++ b/utils/frame/try-runtime/cli/src/lib.rs @@ -858,7 +858,7 @@ pub(crate) fn state_machine_call( executor: &WasmExecutor, method: &'static str, data: &[u8], - extensions: Extensions, + mut extensions: Extensions, ) -> sc_cli::Result<(OverlayedChanges, Vec)> { let mut changes = Default::default(); let encoded_results = StateMachine::new( @@ -867,11 +867,11 @@ pub(crate) fn state_machine_call( executor, method, data, - extensions, + &mut extensions, &sp_state_machine::backend::BackendRuntimeCode::new(&ext.backend).runtime_code()?, CallContext::Offchain, ) - .execute(sp_state_machine::ExecutionStrategy::AlwaysWasm) + .execute() .map_err(|e| format!("failed to execute '{}': {}", method, e)) .map_err::(Into::into)?; @@ -887,7 +887,7 @@ pub(crate) fn state_machine_call_with_proof, method: &'static str, data: &[u8], - extensions: Extensions, + mut extensions: Extensions, maybe_export_proof: Option, ) -> sc_cli::Result<(OverlayedChanges, Vec)> { use parity_scale_codec::Encode; @@ -906,11 +906,11 @@ pub(crate) fn state_machine_call_with_proof(Into::into)?;