Files
pezkuwi-subxt/substrate/frame/support/test/tests/construct_runtime.rs
T
Gavin Wood fd5f9292f5 FRAME: Create TransactionExtension as a replacement for SignedExtension (#2280)
Closes #2160

First part of [Extrinsic
Horizon](https://github.com/paritytech/polkadot-sdk/issues/2415)

Introduces a new trait `TransactionExtension` to replace
`SignedExtension`. Introduce the idea of transactions which obey the
runtime's extensions and have according Extension data (né Extra data)
yet do not have hard-coded signatures.

Deprecate the terminology of "Unsigned" when used for
transactions/extrinsics owing to there now being "proper" unsigned
transactions which obey the extension framework and "old-style" unsigned
which do not. Instead we have __*General*__ for the former and
__*Bare*__ for the latter. (Ultimately, the latter will be phased out as
a type of transaction, and Bare will only be used for Inherents.)

Types of extrinsic are now therefore:
- Bare (no hardcoded signature, no Extra data; used to be known as
"Unsigned")
- Bare transactions (deprecated): Gossiped, validated with
`ValidateUnsigned` (deprecated) and the `_bare_compat` bits of
`TransactionExtension` (deprecated).
  - Inherents: Not gossiped, validated with `ProvideInherent`.
- Extended (Extra data): Gossiped, validated via `TransactionExtension`.
  - Signed transactions (with a hardcoded signature).
  - General transactions (without a hardcoded signature).

`TransactionExtension` differs from `SignedExtension` because:
- A signature on the underlying transaction may validly not be present.
- It may alter the origin during validation.
- `pre_dispatch` is renamed to `prepare` and need not contain the checks
present in `validate`.
- `validate` and `prepare` is passed an `Origin` rather than a
`AccountId`.
- `validate` may pass arbitrary information into `prepare` via a new
user-specifiable type `Val`.
- `AdditionalSigned`/`additional_signed` is renamed to
`Implicit`/`implicit`. It is encoded *for the entire transaction* and
passed in to each extension as a new argument to `validate`. This
facilitates the ability of extensions to acts as underlying crypto.

There is a new `DispatchTransaction` trait which contains only default
function impls and is impl'ed for any `TransactionExtension` impler. It
provides several utility functions which reduce some of the tedium from
using `TransactionExtension` (indeed, none of its regular functions
should now need to be called directly).

Three transaction version discriminator ("versions") are now
permissible:
- 0b000000100: Bare (used to be called "Unsigned"): contains Signature
or Extra (extension data). After bare transactions are no longer
supported, this will strictly identify an Inherents only.
- 0b100000100: Old-school "Signed" Transaction: contains Signature and
Extra (extension data).
- 0b010000100: New-school "General" Transaction: contains Extra
(extension data), but no Signature.

For the New-school General Transaction, it becomes trivial for authors
to publish extensions to the mechanism for authorizing an Origin, e.g.
through new kinds of key-signing schemes, ZK proofs, pallet state,
mutations over pre-authenticated origins or any combination of the
above.

## Code Migration

### NOW: Getting it to build

Wrap your `SignedExtension`s in `AsTransactionExtension`. This should be
accompanied by renaming your aggregate type in line with the new
terminology. E.g. Before:

```rust
/// The SignedExtension to the basic transaction logic.
pub type SignedExtra = (
	/* snip */
	MySpecialSignedExtension,
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
```

After:

```rust
/// The extension to the basic transaction logic.
pub type TxExtension = (
	/* snip */
	AsTransactionExtension<MySpecialSignedExtension>,
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
```

You'll also need to alter any transaction building logic to add a
`.into()` to make the conversion happen. E.g. Before:

```rust
fn construct_extrinsic(
		/* snip */
) -> UncheckedExtrinsic {
	let extra: SignedExtra = (
		/* snip */
		MySpecialSignedExtension::new(/* snip */),
	);
	let payload = SignedPayload::new(call.clone(), extra.clone()).unwrap();
	let signature = payload.using_encoded(|e| sender.sign(e));
	UncheckedExtrinsic::new_signed(
		/* snip */
		Signature::Sr25519(signature),
		extra,
	)
}
```

After:

```rust
fn construct_extrinsic(
		/* snip */
) -> UncheckedExtrinsic {
	let tx_ext: TxExtension = (
		/* snip */
		MySpecialSignedExtension::new(/* snip */).into(),
	);
	let payload = SignedPayload::new(call.clone(), tx_ext.clone()).unwrap();
	let signature = payload.using_encoded(|e| sender.sign(e));
	UncheckedExtrinsic::new_signed(
		/* snip */
		Signature::Sr25519(signature),
		tx_ext,
	)
}
```

### SOON: Migrating to `TransactionExtension`

Most `SignedExtension`s can be trivially converted to become a
`TransactionExtension`. There are a few things to know.

- Instead of a single trait like `SignedExtension`, you should now
implement two traits individually: `TransactionExtensionBase` and
`TransactionExtension`.
- Weights are now a thing and must be provided via the new function `fn
weight`.

#### `TransactionExtensionBase`

This trait takes care of anything which is not dependent on types
specific to your runtime, most notably `Call`.

- `AdditionalSigned`/`additional_signed` is renamed to
`Implicit`/`implicit`.
- Weight must be returned by implementing the `weight` function. If your
extension is associated with a pallet, you'll probably want to do this
via the pallet's existing benchmarking infrastructure.

#### `TransactionExtension`

Generally:
- `pre_dispatch` is now `prepare` and you *should not reexecute the
`validate` functionality in there*!
- You don't get an account ID any more; you get an origin instead. If
you need to presume an account ID, then you can use the trait function
`AsSystemOriginSigner::as_system_origin_signer`.
- You get an additional ticket, similar to `Pre`, called `Val`. This
defines data which is passed from `validate` into `prepare`. This is
important since you should not be duplicating logic from `validate` to
`prepare`, you need a way of passing your working from the former into
the latter. This is it.
- This trait takes two type parameters: `Call` and `Context`. `Call` is
the runtime call type which used to be an associated type; you can just
move it to become a type parameter for your trait impl. `Context` is not
currently used and you can safely implement over it as an unbounded
type.
- There's no `AccountId` associated type any more. Just remove it.

Regarding `validate`:
- You get three new parameters in `validate`; all can be ignored when
migrating from `SignedExtension`.
- `validate` returns a tuple on success; the second item in the tuple is
the new ticket type `Self::Val` which gets passed in to `prepare`. If
you use any information extracted during `validate` (off-chain and
on-chain, non-mutating) in `prepare` (on-chain, mutating) then you can
pass it through with this. For the tuple's last item, just return the
`origin` argument.

Regarding `prepare`:
- This is renamed from `pre_dispatch`, but there is one change:
- FUNCTIONALITY TO VALIDATE THE TRANSACTION NEED NOT BE DUPLICATED FROM
`validate`!!
- (This is different to `SignedExtension` which was required to run the
same checks in `pre_dispatch` as in `validate`.)

Regarding `post_dispatch`:
- Since there are no unsigned transactions handled by
`TransactionExtension`, `Pre` is always defined, so the first parameter
is `Self::Pre` rather than `Option<Self::Pre>`.

If you make use of `SignedExtension::validate_unsigned` or
`SignedExtension::pre_dispatch_unsigned`, then:
- Just use the regular versions of these functions instead.
- Have your logic execute in the case that the `origin` is `None`.
- Ensure your transaction creation logic creates a General Transaction
rather than a Bare Transaction; this means having to include all
`TransactionExtension`s' data.
- `ValidateUnsigned` can still be used (for now) if you need to be able
to construct transactions which contain none of the extension data,
however these will be phased out in stage 2 of the Transactions Horizon,
so you should consider moving to an extension-centric design.

## TODO

- [x] Introduce `CheckSignature` impl of `TransactionExtension` to
ensure it's possible to have crypto be done wholly in a
`TransactionExtension`.
- [x] Deprecate `SignedExtension` and move all uses in codebase to
`TransactionExtension`.
  - [x] `ChargeTransactionPayment`
  - [x] `DummyExtension`
  - [x] `ChargeAssetTxPayment` (asset-tx-payment)
  - [x] `ChargeAssetTxPayment` (asset-conversion-tx-payment)
  - [x] `CheckWeight`
  - [x] `CheckTxVersion`
  - [x] `CheckSpecVersion`
  - [x] `CheckNonce`
  - [x] `CheckNonZeroSender`
  - [x] `CheckMortality`
  - [x] `CheckGenesis`
  - [x] `CheckOnlySudoAccount`
  - [x] `WatchDummy`
  - [x] `PrevalidateAttests`
  - [x] `GenericSignedExtension`
  - [x] `SignedExtension` (chain-polkadot-bulletin)
  - [x] `RefundSignedExtensionAdapter`
- [x] Implement `fn weight` across the board.
- [ ] Go through all pre-existing extensions which assume an account
signer and explicitly handle the possibility of another kind of origin.
- [x] `CheckNonce` should probably succeed in the case of a non-account
origin.
- [x] `CheckNonZeroSender` should succeed in the case of a non-account
origin.
- [x] `ChargeTransactionPayment` and family should fail in the case of a
non-account origin.
  - [ ] 
- [x] Fix any broken tests.

---------

Signed-off-by: georgepisaltu <george.pisaltu@parity.io>
Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Signed-off-by: Alexandru Gheorghe <alexandru.gheorghe@parity.io>
Signed-off-by: Andrei Sandu <andrei-mihail@parity.io>
Co-authored-by: Nikhil Gupta <17176722+gupnik@users.noreply.github.com>
Co-authored-by: georgepisaltu <52418509+georgepisaltu@users.noreply.github.com>
Co-authored-by: Chevdor <chevdor@users.noreply.github.com>
Co-authored-by: Bastian Köcher <git@kchr.de>
Co-authored-by: Maciej <maciej.zyszkiewicz@parity.io>
Co-authored-by: Javier Viola <javier@parity.io>
Co-authored-by: Marcin S. <marcin@realemail.net>
Co-authored-by: Tsvetomir Dimitrov <tsvetomir@parity.io>
Co-authored-by: Javier Bullrich <javier@bullrich.dev>
Co-authored-by: Koute <koute@users.noreply.github.com>
Co-authored-by: Adrian Catangiu <adrian@parity.io>
Co-authored-by: Vladimir Istyufeev <vladimir@parity.io>
Co-authored-by: Ross Bulat <ross@parity.io>
Co-authored-by: Gonçalo Pestana <g6pestana@gmail.com>
Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
Co-authored-by: Svyatoslav Nikolsky <svyatonik@gmail.com>
Co-authored-by: André Silva <123550+andresilva@users.noreply.github.com>
Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: s0me0ne-unkn0wn <48632512+s0me0ne-unkn0wn@users.noreply.github.com>
Co-authored-by: ordian <write@reusable.software>
Co-authored-by: Sebastian Kunert <skunert49@gmail.com>
Co-authored-by: Aaro Altonen <48052676+altonen@users.noreply.github.com>
Co-authored-by: Dmitry Markin <dmitry@markin.tech>
Co-authored-by: Alexandru Vasile <60601340+lexnv@users.noreply.github.com>
Co-authored-by: Alexander Samusev <41779041+alvicsam@users.noreply.github.com>
Co-authored-by: Julian Eager <eagr@tutanota.com>
Co-authored-by: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com>
Co-authored-by: Davide Galassi <davxy@datawok.net>
Co-authored-by: Dónal Murray <donal.murray@parity.io>
Co-authored-by: yjh <yjh465402634@gmail.com>
Co-authored-by: Tom Mi <tommi@niemi.lol>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Will | Paradox | ParaNodes.io <79228812+paradox-tt@users.noreply.github.com>
Co-authored-by: Bastian Köcher <info@kchr.de>
Co-authored-by: Joshy Orndorff <JoshOrndorff@users.noreply.github.com>
Co-authored-by: Joshy Orndorff <git-user-email.h0ly5@simplelogin.com>
Co-authored-by: PG Herveou <pgherveou@gmail.com>
Co-authored-by: Alexander Theißen <alex.theissen@me.com>
Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
Co-authored-by: Juan Girini <juangirini@gmail.com>
Co-authored-by: bader y <ibnbassem@gmail.com>
Co-authored-by: James Wilson <james@jsdw.me>
Co-authored-by: joe petrowski <25483142+joepetrowski@users.noreply.github.com>
Co-authored-by: asynchronous rob <rphmeier@gmail.com>
Co-authored-by: Parth <desaiparth08@gmail.com>
Co-authored-by: Andrew Jones <ascjones@gmail.com>
Co-authored-by: Jonathan Udd <jonathan@dwellir.com>
Co-authored-by: Serban Iorga <serban@parity.io>
Co-authored-by: Egor_P <egor@parity.io>
Co-authored-by: Branislav Kontur <bkontur@gmail.com>
Co-authored-by: Evgeny Snitko <evgeny@parity.io>
Co-authored-by: Just van Stam <vstam1@users.noreply.github.com>
Co-authored-by: Francisco Aguirre <franciscoaguirreperez@gmail.com>
Co-authored-by: gupnik <nikhilgupta.iitk@gmail.com>
Co-authored-by: dzmitry-lahoda <dzmitry@lahoda.pro>
Co-authored-by: zhiqiangxu <652732310@qq.com>
Co-authored-by: Nazar Mokrynskyi <nazar@mokrynskyi.com>
Co-authored-by: Anwesh <anweshknayak@gmail.com>
Co-authored-by: cheme <emericchevalier.pro@gmail.com>
Co-authored-by: Sam Johnson <sam@durosoft.com>
Co-authored-by: kianenigma <kian@parity.io>
Co-authored-by: Jegor Sidorenko <5252494+jsidorenko@users.noreply.github.com>
Co-authored-by: Muharem <ismailov.m.h@gmail.com>
Co-authored-by: joepetrowski <joe@parity.io>
Co-authored-by: Alexandru Gheorghe <49718502+alexggh@users.noreply.github.com>
Co-authored-by: Gabriel Facco de Arruda <arrudagates@gmail.com>
Co-authored-by: Squirrel <gilescope@gmail.com>
Co-authored-by: Andrei Sandu <54316454+sandreim@users.noreply.github.com>
Co-authored-by: georgepisaltu <george.pisaltu@parity.io>
Co-authored-by: command-bot <>
2024-03-04 19:12:43 +00:00

898 lines
28 KiB
Rust

// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! General tests for construct_runtime macro, test for:
//! * error declared with decl_error works
//! * integrity test is generated
#![recursion_limit = "128"]
use codec::MaxEncodedLen;
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, ConstU64};
use sp_runtime::{
generic,
traits::{BlakeTwo256, Verify},
DispatchError, ModuleError,
};
use sp_version::RuntimeVersion;
parameter_types! {
pub static IntegrityTestExec: u32 = 0;
}
#[frame_support::pallet(dev_mode)]
mod module1 {
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::pallet]
pub struct Pallet<T, I = ()>(_);
#[pallet::config]
pub trait Config<I: 'static = ()>: frame_system::Config {
type RuntimeEvent: From<Event<Self, I>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
}
#[pallet::call]
impl<T: Config<I>, I: 'static> Pallet<T, I> {
pub fn fail(_origin: OriginFor<T>) -> DispatchResult {
Err(Error::<T, I>::Something.into())
}
}
#[pallet::origin]
#[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]
#[scale_info(skip_type_params(I))]
pub struct Origin<T, I = ()>(pub PhantomData<(T, I)>);
#[pallet::event]
pub enum Event<T: Config<I>, I: 'static = ()> {
A(<T as frame_system::Config>::AccountId),
}
#[pallet::error]
pub enum Error<T, I = ()> {
Something,
}
}
#[frame_support::pallet(dev_mode)]
mod module2 {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn integrity_test() {
IntegrityTestExec::mutate(|i| *i += 1);
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
pub fn fail(_origin: OriginFor<T>) -> DispatchResult {
Err(Error::<T>::Something.into())
}
}
#[pallet::origin]
#[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]
pub struct Origin;
#[pallet::event]
pub enum Event<T> {
A,
}
#[pallet::error]
pub enum Error<T> {
Something,
}
}
mod nested {
use super::*;
#[frame_support::pallet(dev_mode)]
pub mod module3 {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn integrity_test() {
IntegrityTestExec::mutate(|i| *i += 1);
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
pub fn fail(_origin: OriginFor<T>) -> DispatchResult {
Err(Error::<T>::Something.into())
}
}
#[pallet::origin]
#[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]
pub struct Origin;
#[pallet::event]
pub enum Event<T> {
A,
}
#[pallet::error]
pub enum Error<T> {
Something,
}
#[pallet::genesis_config]
#[derive(frame_support::DefaultNoBound)]
pub struct GenesisConfig<T: Config> {
#[serde(skip)]
pub _config: sp_std::marker::PhantomData<T>,
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {}
}
}
}
#[frame_support::pallet(dev_mode)]
pub mod module3 {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
}
#[pallet::call]
impl<T: Config> Pallet<T> {
pub fn fail(_origin: OriginFor<T>) -> DispatchResult {
Err(Error::<T>::Something.into())
}
pub fn aux_1(_origin: OriginFor<T>, #[pallet::compact] _data: u32) -> DispatchResult {
unreachable!()
}
pub fn aux_2(
_origin: OriginFor<T>,
_data: i32,
#[pallet::compact] _data2: u32,
) -> DispatchResult {
unreachable!()
}
#[pallet::weight(0)]
pub fn aux_3(_origin: OriginFor<T>, _data: i32, _data2: String) -> DispatchResult {
unreachable!()
}
#[pallet::weight(3)]
pub fn aux_4(_origin: OriginFor<T>) -> DispatchResult {
unreachable!()
}
#[pallet::weight((5, DispatchClass::Operational))]
pub fn operational(_origin: OriginFor<T>) -> DispatchResult {
unreachable!()
}
}
#[pallet::origin]
#[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]
pub struct Origin<T>(pub PhantomData<T>);
#[pallet::event]
pub enum Event<T> {
A,
}
#[pallet::error]
pub enum Error<T> {
Something,
}
#[pallet::genesis_config]
#[derive(frame_support::DefaultNoBound)]
pub struct GenesisConfig<T: Config> {
#[serde(skip)]
pub _config: sp_std::marker::PhantomData<T>,
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {}
}
}
pub type BlockNumber = u64;
pub type Signature = sr25519::Signature;
pub type AccountId = <Signature as Verify>::Signer;
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<u32, RuntimeCall, Signature, ()>;
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
frame_support::construct_runtime!(
pub struct Runtime
{
System: frame_system::{Pallet, Call, Event<T>, Origin<T>} = 30,
Module1_1: module1::<Instance1>::{Pallet, Call, Storage, Event<T>, Origin<T>},
Module2: module2::{Pallet, Call, Storage, Event<T>, Origin},
Module1_2: module1::<Instance2>::{Pallet, Call, Storage, Event<T>, Origin<T>},
NestedModule3: nested::module3::{Pallet, Call, Config<T>, Storage, Event<T>, Origin},
Module3: self::module3::{Pallet, Call, Config<T>, Storage, Event<T>, Origin<T>},
Module1_3: module1::<Instance3>::{Pallet, Storage, Event<T> } = 6,
Module1_4: module1::<Instance4>::{Pallet, Call, Event<T> } = 3,
Module1_5: module1::<Instance5>::{Pallet, Event<T>},
Module1_6: module1::<Instance6>::{Pallet, Call, Storage, Event<T>, Origin<T>} = 1,
Module1_7: module1::<Instance7>::{Pallet, Call, Storage, Event<T>, Origin<T>},
Module1_8: module1::<Instance8>::{Pallet, Call, Storage, Event<T>, Origin<T>} = 12,
Module1_9: module1::<Instance9>::{Pallet, Call, Storage, Event<T>, Origin<T>},
}
);
#[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<AccountId>;
type BaseCallFilter = frame_support::traits::Everything;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type PalletInfo = PalletInfo;
type OnSetCode = ();
type Block = Block;
type BlockHashCount = ConstU64<10>;
}
impl module1::Config<module1::Instance1> for Runtime {
type RuntimeEvent = RuntimeEvent;
}
impl module1::Config<module1::Instance2> for Runtime {
type RuntimeEvent = RuntimeEvent;
}
impl module1::Config<module1::Instance3> for Runtime {
type RuntimeEvent = RuntimeEvent;
}
impl module1::Config<module1::Instance4> for Runtime {
type RuntimeEvent = RuntimeEvent;
}
impl module1::Config<module1::Instance5> for Runtime {
type RuntimeEvent = RuntimeEvent;
}
impl module1::Config<module1::Instance6> for Runtime {
type RuntimeEvent = RuntimeEvent;
}
impl module1::Config<module1::Instance7> for Runtime {
type RuntimeEvent = RuntimeEvent;
}
impl module1::Config<module1::Instance8> for Runtime {
type RuntimeEvent = RuntimeEvent;
}
impl module1::Config<module1::Instance9> for Runtime {
type RuntimeEvent = RuntimeEvent;
}
impl module2::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
}
impl nested::module3::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
}
impl module3::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
}
fn test_pub() -> AccountId {
AccountId::from_raw([0; 32])
}
#[test]
fn check_modules_error_type() {
sp_io::TestExternalities::default().execute_with(|| {
assert_eq!(
Module1_1::fail(frame_system::Origin::<Runtime>::Root.into()),
Err(DispatchError::Module(ModuleError {
index: 31,
error: [0; 4],
message: Some("Something")
})),
);
assert_eq!(
Module2::fail(frame_system::Origin::<Runtime>::Root.into()),
Err(DispatchError::Module(ModuleError {
index: 32,
error: [0; 4],
message: Some("Something")
})),
);
assert_eq!(
Module1_2::fail(frame_system::Origin::<Runtime>::Root.into()),
Err(DispatchError::Module(ModuleError {
index: 33,
error: [0; 4],
message: Some("Something")
})),
);
assert_eq!(
NestedModule3::fail(frame_system::Origin::<Runtime>::Root.into()),
Err(DispatchError::Module(ModuleError {
index: 34,
error: [0; 4],
message: Some("Something")
})),
);
assert_eq!(
Module1_3::fail(frame_system::Origin::<Runtime>::Root.into()),
Err(DispatchError::Module(ModuleError {
index: 6,
error: [0; 4],
message: Some("Something")
})),
);
assert_eq!(
Module1_4::fail(frame_system::Origin::<Runtime>::Root.into()),
Err(DispatchError::Module(ModuleError {
index: 3,
error: [0; 4],
message: Some("Something")
})),
);
assert_eq!(
Module1_5::fail(frame_system::Origin::<Runtime>::Root.into()),
Err(DispatchError::Module(ModuleError {
index: 4,
error: [0; 4],
message: Some("Something")
})),
);
assert_eq!(
Module1_6::fail(frame_system::Origin::<Runtime>::Root.into()),
Err(DispatchError::Module(ModuleError {
index: 1,
error: [0; 4],
message: Some("Something")
})),
);
assert_eq!(
Module1_7::fail(frame_system::Origin::<Runtime>::Root.into()),
Err(DispatchError::Module(ModuleError {
index: 2,
error: [0; 4],
message: Some("Something")
})),
);
assert_eq!(
Module1_8::fail(frame_system::Origin::<Runtime>::Root.into()),
Err(DispatchError::Module(ModuleError {
index: 12,
error: [0; 4],
message: Some("Something")
})),
);
assert_eq!(
Module1_9::fail(frame_system::Origin::<Runtime>::Root.into()),
Err(DispatchError::Module(ModuleError {
index: 13,
error: [0; 4],
message: Some("Something")
})),
);
})
}
#[test]
fn integrity_test_works() {
__construct_runtime_integrity_test::runtime_integrity_tests();
assert_eq!(IntegrityTestExec::get(), 2);
}
#[test]
fn origin_codec() {
use codec::Encode;
let origin = OriginCaller::system(frame_system::RawOrigin::None);
assert_eq!(origin.encode()[0], 30);
let origin = OriginCaller::Module1_1(module1::Origin(Default::default()));
assert_eq!(origin.encode()[0], 31);
let origin = OriginCaller::Module2(module2::Origin);
assert_eq!(origin.encode()[0], 32);
let origin = OriginCaller::Module1_2(module1::Origin(Default::default()));
assert_eq!(origin.encode()[0], 33);
let origin = OriginCaller::NestedModule3(nested::module3::Origin);
assert_eq!(origin.encode()[0], 34);
let origin = OriginCaller::Module3(module3::Origin(Default::default()));
assert_eq!(origin.encode()[0], 35);
let origin = OriginCaller::Module1_6(module1::Origin(Default::default()));
assert_eq!(origin.encode()[0], 1);
let origin = OriginCaller::Module1_7(module1::Origin(Default::default()));
assert_eq!(origin.encode()[0], 2);
let origin = OriginCaller::Module1_8(module1::Origin(Default::default()));
assert_eq!(origin.encode()[0], 12);
let origin = OriginCaller::Module1_9(module1::Origin(Default::default()));
assert_eq!(origin.encode()[0], 13);
}
#[test]
fn event_codec() {
use codec::Encode;
let event =
frame_system::Event::<Runtime>::ExtrinsicSuccess { dispatch_info: Default::default() };
assert_eq!(RuntimeEvent::from(event).encode()[0], 30);
let event = module1::Event::<Runtime, module1::Instance1>::A(test_pub());
assert_eq!(RuntimeEvent::from(event).encode()[0], 31);
let event = module2::Event::A;
assert_eq!(RuntimeEvent::from(event).encode()[0], 32);
let event = module1::Event::<Runtime, module1::Instance2>::A(test_pub());
assert_eq!(RuntimeEvent::from(event).encode()[0], 33);
let event = nested::module3::Event::A;
assert_eq!(RuntimeEvent::from(event).encode()[0], 34);
let event = module3::Event::A;
assert_eq!(RuntimeEvent::from(event).encode()[0], 35);
let event = module1::Event::<Runtime, module1::Instance5>::A(test_pub());
assert_eq!(RuntimeEvent::from(event).encode()[0], 4);
let event = module1::Event::<Runtime, module1::Instance6>::A(test_pub());
assert_eq!(RuntimeEvent::from(event).encode()[0], 1);
let event = module1::Event::<Runtime, module1::Instance7>::A(test_pub());
assert_eq!(RuntimeEvent::from(event).encode()[0], 2);
let event = module1::Event::<Runtime, module1::Instance8>::A(test_pub());
assert_eq!(RuntimeEvent::from(event).encode()[0], 12);
let event = module1::Event::<Runtime, module1::Instance9>::A(test_pub());
assert_eq!(RuntimeEvent::from(event).encode()[0], 13);
}
#[test]
fn call_codec() {
use codec::Encode;
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);
assert_eq!(RuntimeCall::NestedModule3(nested::module3::Call::fail {}).encode()[0], 34);
assert_eq!(RuntimeCall::Module3(module3::Call::fail {}).encode()[0], 35);
assert_eq!(RuntimeCall::Module1_4(module1::Call::fail {}).encode()[0], 3);
assert_eq!(RuntimeCall::Module1_6(module1::Call::fail {}).encode()[0], 1);
assert_eq!(RuntimeCall::Module1_7(module1::Call::fail {}).encode()[0], 2);
assert_eq!(RuntimeCall::Module1_8(module1::Call::fail {}).encode()[0], 12);
assert_eq!(RuntimeCall::Module1_9(module1::Call::fail {}).encode()[0], 13);
}
#[test]
fn call_compact_attr() {
use codec::Encode;
let call: module3::Call<Runtime> = module3::Call::aux_1 { data: 1 };
let encoded = call.encode();
assert_eq!(2, encoded.len());
assert_eq!(vec![1, 4], encoded);
let call: module3::Call<Runtime> = module3::Call::aux_2 { data: 1, data2: 2 };
let encoded = call.encode();
assert_eq!(6, encoded.len());
assert_eq!(vec![2, 1, 0, 0, 0, 8], encoded);
}
#[test]
fn call_encode_is_correct_and_decode_works() {
use codec::{Decode, Encode};
let call: module3::Call<Runtime> = module3::Call::fail {};
let encoded = call.encode();
assert_eq!(vec![0], encoded);
let decoded = module3::Call::<Runtime>::decode(&mut &encoded[..]).unwrap();
assert_eq!(decoded, call);
let call: module3::Call<Runtime> = module3::Call::aux_3 { data: 32, data2: "hello".into() };
let encoded = call.encode();
assert_eq!(vec![3, 32, 0, 0, 0, 20, 104, 101, 108, 108, 111], encoded);
let decoded = module3::Call::<Runtime>::decode(&mut &encoded[..]).unwrap();
assert_eq!(decoded, call);
}
#[test]
fn call_weight_should_attach_to_call_enum() {
use frame_support::{
dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, Pays},
weights::Weight,
};
// operational.
assert_eq!(
module3::Call::<Runtime>::operational {}.get_dispatch_info(),
DispatchInfo {
weight: Weight::from_parts(5, 0),
class: DispatchClass::Operational,
pays_fee: Pays::Yes
},
);
// custom basic
assert_eq!(
module3::Call::<Runtime>::aux_4 {}.get_dispatch_info(),
DispatchInfo {
weight: Weight::from_parts(3, 0),
class: DispatchClass::Normal,
pays_fee: Pays::Yes
},
);
}
#[test]
fn call_name() {
use frame_support::traits::GetCallName;
let name = module3::Call::<Runtime>::aux_4 {}.get_call_name();
assert_eq!("aux_4", name);
}
#[test]
fn call_metadata() {
use frame_support::traits::{CallMetadata, GetCallMetadata};
let call = RuntimeCall::Module3(module3::Call::<Runtime>::aux_4 {});
let metadata = call.get_call_metadata();
let expected = CallMetadata { function_name: "aux_4".into(), pallet_name: "Module3".into() };
assert_eq!(metadata, expected);
}
#[test]
fn get_call_names() {
use frame_support::traits::GetCallName;
let call_names = module3::Call::<Runtime>::get_call_names();
assert_eq!(["fail", "aux_1", "aux_2", "aux_3", "aux_4", "operational"], call_names);
}
#[test]
fn get_module_names() {
use frame_support::traits::GetCallMetadata;
let module_names = RuntimeCall::get_module_names();
assert_eq!(
[
"System",
"Module1_1",
"Module2",
"Module1_2",
"NestedModule3",
"Module3",
"Module1_4",
"Module1_6",
"Module1_7",
"Module1_8",
"Module1_9",
],
module_names
);
}
#[test]
fn call_subtype_conversion() {
use frame_support::{dispatch::CallableCallFor, traits::IsSubType};
let call = RuntimeCall::Module3(module3::Call::<Runtime>::fail {});
let subcall: Option<&CallableCallFor<Module3, Runtime>> = call.is_sub_type();
let subcall_none: Option<&CallableCallFor<Module2, Runtime>> = call.is_sub_type();
assert_eq!(Some(&module3::Call::<Runtime>::fail {}), subcall);
assert_eq!(None, subcall_none);
let from = RuntimeCall::from(subcall.unwrap().clone());
assert_eq!(from, call);
}
#[test]
fn test_metadata() {
use frame_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::<frame_system::Call<Runtime>>().into()),
event: Some(meta_type::<frame_system::Event<Runtime>>().into()),
constants: vec![
PalletConstantMetadata {
name: "BlockWeights",
ty: meta_type::<BlockWeights>(),
value: BlockWeights::default().encode(),
docs: maybe_docs(vec![" Block & extrinsics weights: base values and limits."]),
},
PalletConstantMetadata {
name: "BlockLength",
ty: meta_type::<BlockLength>(),
value: BlockLength::default().encode(),
docs: maybe_docs(vec![" The maximum length of a block (in bytes)."]),
},
PalletConstantMetadata {
name: "BlockHashCount",
ty: meta_type::<u64>(),
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::<RuntimeDbWeight>(),
value: RuntimeDbWeight::default().encode(),
docs: maybe_docs(vec![" The weight of runtime database operations the runtime can invoke.",]),
},
PalletConstantMetadata {
name: "Version",
ty: meta_type::<RuntimeVersion>(),
value: RuntimeVersion::default().encode(),
docs: maybe_docs(vec![ " Get the chain's in-code version."]),
},
PalletConstantMetadata {
name: "SS58Prefix",
ty: meta_type::<u16>(),
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::<frame_system::Error<Runtime>>().into()),
index: 30,
},
PalletMetadata {
name: "Module1_1",
storage: Some(PalletStorageMetadata { prefix: "Module1_1", entries: vec![] }),
calls: Some(meta_type::<module1::Call<Runtime, module1::Instance1>>().into()),
event: Some(meta_type::<module1::Event<Runtime, module1::Instance1>>().into()),
constants: vec![],
error: Some(meta_type::<module1::Error<Runtime>>().into()),
index: 31,
},
PalletMetadata {
name: "Module2",
storage: Some(PalletStorageMetadata { prefix: "Module2", entries: vec![] }),
calls: Some(meta_type::<module2::Call<Runtime>>().into()),
event: Some(meta_type::<module2::Event<Runtime>>().into()),
constants: vec![],
error: Some(meta_type::<module2::Error<Runtime>>().into()),
index: 32,
},
PalletMetadata {
name: "Module1_2",
storage: Some(PalletStorageMetadata { prefix: "Module1_2", entries: vec![] }),
calls: Some(meta_type::<module1::Call<Runtime, module1::Instance2>>().into()),
event: Some(meta_type::<module1::Event<Runtime, module1::Instance2>>().into()),
constants: vec![],
error: Some(meta_type::<module1::Error<Runtime, module1::Instance2>>().into()),
index: 33,
},
PalletMetadata {
name: "NestedModule3",
storage: Some(PalletStorageMetadata { prefix: "NestedModule3", entries: vec![] }),
calls: Some(meta_type::<nested::module3::Call<Runtime>>().into()),
event: Some(meta_type::<nested::module3::Event<Runtime>>().into()),
constants: vec![],
error: Some(meta_type::<nested::module3::Error<Runtime>>().into()),
index: 34,
},
PalletMetadata {
name: "Module3",
storage: Some(PalletStorageMetadata { prefix: "Module3", entries: vec![] }),
calls: Some(meta_type::<module3::Call<Runtime>>().into()),
event: Some(meta_type::<module3::Event<Runtime>>().into()),
constants: vec![],
error: Some(meta_type::<module3::Error<Runtime>>().into()),
index: 35,
},
PalletMetadata {
name: "Module1_3",
storage: Some(PalletStorageMetadata { prefix: "Module1_3", entries: vec![] }),
calls: None,
event: Some(meta_type::<module1::Event<Runtime, module1::Instance3>>().into()),
constants: vec![],
error: Some(meta_type::<module1::Error<Runtime, module1::Instance3>>().into()),
index: 6,
},
PalletMetadata {
name: "Module1_4",
storage: None,
calls: Some(meta_type::<module1::Call<Runtime, module1::Instance4>>().into()),
event: Some(meta_type::<module1::Event<Runtime, module1::Instance4>>().into()),
constants: vec![],
error: Some(meta_type::<module1::Error<Runtime, module1::Instance4>>().into()),
index: 3,
},
PalletMetadata {
name: "Module1_5",
storage: None,
calls: None,
event: Some(meta_type::<module1::Event<Runtime, module1::Instance5>>().into()),
constants: vec![],
error: Some(meta_type::<module1::Error<Runtime, module1::Instance5>>().into()),
index: 4,
},
PalletMetadata {
name: "Module1_6",
storage: Some(PalletStorageMetadata { prefix: "Module1_6", entries: vec![] }),
calls: Some(meta_type::<module1::Call<Runtime, module1::Instance6>>().into()),
event: Some(meta_type::<module1::Event<Runtime, module1::Instance6>>().into()),
constants: vec![],
error: Some(meta_type::<module1::Error<Runtime, module1::Instance6>>().into()),
index: 1,
},
PalletMetadata {
name: "Module1_7",
storage: Some(PalletStorageMetadata { prefix: "Module1_7", entries: vec![] }),
calls: Some(meta_type::<module1::Call<Runtime, module1::Instance7>>().into()),
event: Some(meta_type::<module1::Event<Runtime, module1::Instance7>>().into()),
constants: vec![],
error: Some(meta_type::<module1::Error<Runtime, module1::Instance7>>().into()),
index: 2,
},
PalletMetadata {
name: "Module1_8",
storage: Some(PalletStorageMetadata { prefix: "Module1_8", entries: vec![] }),
calls: Some(meta_type::<module1::Call<Runtime, module1::Instance8>>().into()),
event: Some(meta_type::<module1::Event<Runtime, module1::Instance8>>().into()),
constants: vec![],
error: Some(meta_type::<module1::Error<Runtime, module1::Instance8>>().into()),
index: 12,
},
PalletMetadata {
name: "Module1_9",
storage: Some(PalletStorageMetadata { prefix: "Module1_9", entries: vec![] }),
calls: Some(meta_type::<module1::Call<Runtime, module1::Instance9>>().into()),
event: Some(meta_type::<module1::Event<Runtime, module1::Instance9>>().into()),
constants: vec![],
error: Some(meta_type::<module1::Error<Runtime, module1::Instance9>>().into()),
index: 13,
},
];
let extrinsic = ExtrinsicMetadata {
ty: meta_type::<UncheckedExtrinsic>(),
version: 4,
signed_extensions: vec![SignedExtensionMetadata {
identifier: "UnitTransactionExtension",
ty: meta_type::<()>(),
additional_signed: meta_type::<()>(),
}],
};
let expected_metadata: RuntimeMetadataPrefixed =
RuntimeMetadataLastVersion::new(pallets, extrinsic, meta_type::<Runtime>()).into();
let actual_metadata = Runtime::metadata();
pretty_assertions::assert_eq!(actual_metadata, expected_metadata);
}
#[test]
fn pallet_in_runtime_is_correct() {
assert_eq!(PalletInfo::index::<System>().unwrap(), 30);
assert_eq!(PalletInfo::name::<System>().unwrap(), "System");
assert_eq!(PalletInfo::module_name::<System>().unwrap(), "frame_system");
assert!(PalletInfo::crate_version::<System>().is_some());
assert_eq!(PalletInfo::index::<Module1_1>().unwrap(), 31);
assert_eq!(PalletInfo::name::<Module1_1>().unwrap(), "Module1_1");
assert_eq!(PalletInfo::module_name::<Module1_1>().unwrap(), "module1");
assert!(PalletInfo::crate_version::<Module1_1>().is_some());
assert_eq!(PalletInfo::index::<Module2>().unwrap(), 32);
assert_eq!(PalletInfo::name::<Module2>().unwrap(), "Module2");
assert_eq!(PalletInfo::module_name::<Module2>().unwrap(), "module2");
assert!(PalletInfo::crate_version::<Module2>().is_some());
assert_eq!(PalletInfo::index::<Module1_2>().unwrap(), 33);
assert_eq!(PalletInfo::name::<Module1_2>().unwrap(), "Module1_2");
assert_eq!(PalletInfo::module_name::<Module1_2>().unwrap(), "module1");
assert!(PalletInfo::crate_version::<Module1_2>().is_some());
assert_eq!(PalletInfo::index::<NestedModule3>().unwrap(), 34);
assert_eq!(PalletInfo::name::<NestedModule3>().unwrap(), "NestedModule3");
assert_eq!(PalletInfo::module_name::<NestedModule3>().unwrap(), "nested::module3");
assert!(PalletInfo::crate_version::<NestedModule3>().is_some());
assert_eq!(PalletInfo::index::<Module3>().unwrap(), 35);
assert_eq!(PalletInfo::name::<Module3>().unwrap(), "Module3");
assert_eq!(PalletInfo::module_name::<Module3>().unwrap(), "self::module3");
assert!(PalletInfo::crate_version::<Module3>().is_some());
assert_eq!(PalletInfo::index::<Module1_3>().unwrap(), 6);
assert_eq!(PalletInfo::name::<Module1_3>().unwrap(), "Module1_3");
assert_eq!(PalletInfo::module_name::<Module1_3>().unwrap(), "module1");
assert!(PalletInfo::crate_version::<Module1_3>().is_some());
assert_eq!(PalletInfo::index::<Module1_4>().unwrap(), 3);
assert_eq!(PalletInfo::name::<Module1_4>().unwrap(), "Module1_4");
assert_eq!(PalletInfo::module_name::<Module1_4>().unwrap(), "module1");
assert!(PalletInfo::crate_version::<Module1_4>().is_some());
assert_eq!(PalletInfo::index::<Module1_5>().unwrap(), 4);
assert_eq!(PalletInfo::name::<Module1_5>().unwrap(), "Module1_5");
assert_eq!(PalletInfo::module_name::<Module1_5>().unwrap(), "module1");
assert!(PalletInfo::crate_version::<Module1_5>().is_some());
assert_eq!(PalletInfo::index::<Module1_6>().unwrap(), 1);
assert_eq!(PalletInfo::name::<Module1_6>().unwrap(), "Module1_6");
assert_eq!(PalletInfo::module_name::<Module1_6>().unwrap(), "module1");
assert!(PalletInfo::crate_version::<Module1_6>().is_some());
assert_eq!(PalletInfo::index::<Module1_7>().unwrap(), 2);
assert_eq!(PalletInfo::name::<Module1_7>().unwrap(), "Module1_7");
assert_eq!(PalletInfo::module_name::<Module1_7>().unwrap(), "module1");
assert!(PalletInfo::crate_version::<Module1_7>().is_some());
assert_eq!(PalletInfo::index::<Module1_8>().unwrap(), 12);
assert_eq!(PalletInfo::name::<Module1_8>().unwrap(), "Module1_8");
assert_eq!(PalletInfo::module_name::<Module1_8>().unwrap(), "module1");
assert!(PalletInfo::crate_version::<Module1_8>().is_some());
assert_eq!(PalletInfo::index::<Module1_9>().unwrap(), 13);
assert_eq!(PalletInfo::name::<Module1_9>().unwrap(), "Module1_9");
assert_eq!(PalletInfo::module_name::<Module1_9>().unwrap(), "module1");
assert!(PalletInfo::crate_version::<Module1_9>().is_some());
}