From 6f67add0fa2efbaa25c4b3e2eea3de58699c10e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timoth=C3=A9e=20Delabrouille?= <34384633+tdelabro@users.noreply.github.com> Date: Tue, 11 Feb 2025 21:45:32 +0100 Subject: [PATCH] Revert "Update to latest Substrate version (#1)" This reverts commit 53273e1df815860cad9871ffd8cfcafb90af4cb3. --- Cargo.toml | 1 - exercises/ex00-testing/README.md | 12 +- exercises/ex00-testing/flipper/Cargo.toml | 11 +- exercises/ex00-testing/flipper/src/lib.rs | 11 +- .../ex00-testing/flipper/src/tests/flipper.rs | 6 +- .../ex00-testing/flipper/src/tests/mock.rs | 40 +- exercises/ex01-pallet-easy/README.md | 2 +- exercises/ex01-pallet-easy/assets/Cargo.toml | 13 +- exercises/ex01-pallet-easy/assets/src/lib.rs | 24 +- .../assets/src/tests/assets.rs | 94 +-- .../ex01-pallet-easy/assets/src/tests/mock.rs | 39 +- .../ex01-pallet-easy/assets/src/types.rs | 2 +- exercises/ex02-runtime/README.md | 21 +- .../ex03-pallet-intermediate/nft/Cargo.toml | 13 +- .../ex03-pallet-intermediate/nft/src/lib.rs | 21 +- .../nft/src/tests/mock.rs | 39 +- .../nft/src/tests/unique_assets.rs | 50 +- .../ex03-pallet-intermediate/nft/src/types.rs | 2 +- .../loosely-coupled-marketplace/Cargo.toml | 14 +- .../loosely-coupled-marketplace/src/lib.rs | 6 +- .../src/tests/marketplace.rs | 32 +- .../src/tests/mock.rs | 49 +- .../loosely-coupled-marketplace/src/types.rs | 2 +- .../marketplace-nfts/Cargo.toml | 13 +- .../marketplace-nfts/src/lib.rs | 16 +- .../marketplace-nfts/src/tests/mock.rs | 39 +- .../src/tests/unique_assets.rs | 40 +- .../marketplace-nfts/src/types.rs | 2 +- .../tightly-coupled-marketplace/Cargo.toml | 14 +- .../tightly-coupled-marketplace/src/lib.rs | 11 +- .../src/tests/marketplace.rs | 32 +- .../src/tests/mock.rs | 48 +- .../tightly-coupled-marketplace/src/types.rs | 2 +- exercises/ex05-hooks/reminder/Cargo.toml | 12 +- exercises/ex05-hooks/reminder/src/lib.rs | 23 +- exercises/ex05-hooks/reminder/src/mock.rs | 37 +- exercises/ex05-hooks/reminder/src/tests.rs | 20 +- exercises/ex06-weights/weights/Cargo.toml | 17 +- exercises/ex06-weights/weights/src/lib.rs | 6 +- exercises/ex06-weights/weights/src/mock.rs | 44 +- exercises/ex06-weights/weights/src/tests.rs | 15 +- .../ex07-imbalances/imbalances/Cargo.toml | 15 +- .../ex07-imbalances/imbalances/src/lib.rs | 6 +- .../imbalances/src/tests/mint.rs | 8 +- .../imbalances/src/tests/mock.rs | 45 +- .../imbalances/src/tests/sack.rs | 8 +- .../imbalances/src/tests/slash.rs | 8 +- .../nft-with-genesis-config/Cargo.toml | 13 +- .../nft-with-genesis-config/src/lib.rs | 7 +- .../nft-with-genesis-config/src/tests/mock.rs | 44 +- .../src/tests/unique_assets.rs | 50 +- .../nft-with-genesis-config/src/types.rs | 2 +- exercises/ex09-mock/pallet-to-mock/Cargo.toml | 17 +- exercises/ex09-mock/pallet-to-mock/src/lib.rs | 6 +- .../pallet-price-oracle/Cargo.toml | 22 +- .../pallet-price-oracle/src/lib.rs | 7 +- .../pallet-price-oracle/src/tests/mock.rs | 36 +- .../src/tests/offchain_worker.rs | 4 +- polkadot-sdk-solochain-template/.gitignore | 1 - polkadot-sdk-solochain-template/Cargo.toml | 74 --- polkadot-sdk-solochain-template/Dockerfile | 28 - polkadot-sdk-solochain-template/LICENSE | 24 - polkadot-sdk-solochain-template/README.md | 224 ------- .../docs/rust-setup.md | 218 ------- .../env-setup/README.md | 9 - .../env-setup/flake.lock | 43 -- .../env-setup/flake.nix | 22 - .../env-setup/rust-toolchain.toml | 14 - .../node/Cargo.toml | 107 ---- polkadot-sdk-solochain-template/node/build.rs | 7 - .../node/src/benchmarking.rs | 161 ----- .../node/src/chain_spec.rs | 117 ---- .../node/src/cli.rs | 46 -- .../node/src/command.rs | 195 ------ .../node/src/main.rs | 13 - .../node/src/rpc.rs | 64 -- .../node/src/service.rs | 332 ---------- .../pallets/template/Cargo.toml | 48 -- .../pallets/template/README.md | 1 - .../pallets/template/src/benchmarking.rs | 35 -- .../pallets/template/src/lib.rs | 202 ------ .../pallets/template/src/mock.rs | 29 - .../pallets/template/src/tests.rs | 27 - .../pallets/template/src/weights.rs | 90 --- .../runtime/Cargo.toml | 122 ---- .../runtime/build.rs | 6 - .../runtime/src/lib.rs | 594 ------------------ substrate-node-template | 1 + 88 files changed, 562 insertions(+), 3485 deletions(-) delete mode 100644 polkadot-sdk-solochain-template/.gitignore delete mode 100644 polkadot-sdk-solochain-template/Cargo.toml delete mode 100644 polkadot-sdk-solochain-template/Dockerfile delete mode 100644 polkadot-sdk-solochain-template/LICENSE delete mode 100644 polkadot-sdk-solochain-template/README.md delete mode 100644 polkadot-sdk-solochain-template/docs/rust-setup.md delete mode 100644 polkadot-sdk-solochain-template/env-setup/README.md delete mode 100644 polkadot-sdk-solochain-template/env-setup/flake.lock delete mode 100644 polkadot-sdk-solochain-template/env-setup/flake.nix delete mode 100644 polkadot-sdk-solochain-template/env-setup/rust-toolchain.toml delete mode 100644 polkadot-sdk-solochain-template/node/Cargo.toml delete mode 100644 polkadot-sdk-solochain-template/node/build.rs delete mode 100644 polkadot-sdk-solochain-template/node/src/benchmarking.rs delete mode 100644 polkadot-sdk-solochain-template/node/src/chain_spec.rs delete mode 100644 polkadot-sdk-solochain-template/node/src/cli.rs delete mode 100644 polkadot-sdk-solochain-template/node/src/command.rs delete mode 100644 polkadot-sdk-solochain-template/node/src/main.rs delete mode 100644 polkadot-sdk-solochain-template/node/src/rpc.rs delete mode 100644 polkadot-sdk-solochain-template/node/src/service.rs delete mode 100644 polkadot-sdk-solochain-template/pallets/template/Cargo.toml delete mode 100644 polkadot-sdk-solochain-template/pallets/template/README.md delete mode 100644 polkadot-sdk-solochain-template/pallets/template/src/benchmarking.rs delete mode 100644 polkadot-sdk-solochain-template/pallets/template/src/lib.rs delete mode 100644 polkadot-sdk-solochain-template/pallets/template/src/mock.rs delete mode 100644 polkadot-sdk-solochain-template/pallets/template/src/tests.rs delete mode 100644 polkadot-sdk-solochain-template/pallets/template/src/weights.rs delete mode 100644 polkadot-sdk-solochain-template/runtime/Cargo.toml delete mode 100644 polkadot-sdk-solochain-template/runtime/build.rs delete mode 100644 polkadot-sdk-solochain-template/runtime/src/lib.rs create mode 160000 substrate-node-template diff --git a/Cargo.toml b/Cargo.toml index 456bc91..fa48cc9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,4 @@ [workspace] -resolver = "2" members = ['exercises/*/*'] [profile.release] panic = 'unwind' diff --git a/exercises/ex00-testing/README.md b/exercises/ex00-testing/README.md index d299414..c8d8ae2 100644 --- a/exercises/ex00-testing/README.md +++ b/exercises/ex00-testing/README.md @@ -9,12 +9,12 @@ We created a really simple pallet, `flipper`, that you will have to test. This pallet allows the users to store a boolean in the storage, calling the `set_value` extrinsic, and then flip its value by calling the `flip_value` extrinsic. ## To do -In `ex00-writing-tests/flipper/src/` you will find a `lib.rs` file that defines the pallet configuration, storage, and dispatchable functions. -In `ex00-writing-tests/flipper/src/tests/` you will find the `mock.rs` file, which simulates the runtime execution. Your test will run against this specific implementation of your pallet. You don't need to update it. All you have to do is write the missing code in the `flipper.rs` file. The goal is to check the correct behavior of the `set_value()` and `flip_value()` functions. -1. Fill the `set_value_ok()` test to ensure `set_value()` is storing the value passed as an argument. -2. Fill the `set_value_err_already_set()` test to ensure that this extrinsic cannot be called twice successfully. -3. Fill the `flip_value_ok()` test to ensure calls to `flip_value()` lead to the boolean value being inverted. -4. Read `flip_function()` code and imagine a scenario that will lead to an error when calling it +In ```ex00-writing-tests/flipper/src/``` you will find a ```.lib``` file that defines the pallet configuration, storage, and dispatchable functions. +In ```ex00-writing-tests/flipper/src/tests/``` you will find the ```mock.rs``` file, which simulates the runtime execution. Your test will run against this specific implementation of your pallet. You don't need to update it. All you have to do is write the missing code in the ```flipper.rs``` file. The goal is to check the correct behavior of the ```set_value()``` and ```flip_value()``` functions. +1. Fill the ```set_value_ok()``` test to ensure ```set_value()``` is storing the value passed as an argument. +2. Fill the ```set_value_err_already_set()``` test to ensure that this extrinsic cannot be called twice successfully. +3. Fill the ```flip_value_ok()``` test to ensure calls to ```flip_value()``` lead to the boolean value being inverted. +4. Read ```flip_function()``` code and imagine a scenario that will lead to an error when calling it ## Some links * Awesome Rusty: https://github.com/rusty-crewmates/awesome-rusty diff --git a/exercises/ex00-testing/flipper/Cargo.toml b/exercises/ex00-testing/flipper/Cargo.toml index fc9ed5c..209ad29 100644 --- a/exercises/ex00-testing/flipper/Cargo.toml +++ b/exercises/ex00-testing/flipper/Cargo.toml @@ -12,13 +12,14 @@ codec = { package = "parity-scale-codec", version = "3.0.0", default-features = scale-info = { version = "2.0.1", default-features = false, features = [ "derive", ] } -frame-support = "38.0.0" -frame-system = "38.0.0" + +frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } [dev-dependencies] -sp-core = "34.0.0" -sp-io = "38.0.0" -sp-runtime = "39.0.2" +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } [features] default = ["std"] diff --git a/exercises/ex00-testing/flipper/src/lib.rs b/exercises/ex00-testing/flipper/src/lib.rs index 4c4890f..2f8ad27 100644 --- a/exercises/ex00-testing/flipper/src/lib.rs +++ b/exercises/ex00-testing/flipper/src/lib.rs @@ -5,7 +5,6 @@ pub use pallet::*; #[cfg(test)] mod tests; -#[allow(unexpected_cfgs)] // skip warning "unexpected `cfg` condition value: `try-runtime`" #[frame_support::pallet] pub mod pallet { use frame_support::pallet_prelude::*; @@ -13,11 +12,11 @@ pub mod pallet { #[pallet::config] pub trait Config: frame_system::Config { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; + type Event: From> + IsType<::Event>; } #[pallet::pallet] - #[pallet::without_storage_info] + #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(_); // The pallet's runtime storage items. @@ -52,8 +51,7 @@ pub mod pallet { impl Pallet { /// This function sets a value to the Value storage and emits an event, it should be used /// once, if something is already present in the storage, it returns an error. - #[pallet::weight({0})] - #[pallet::call_index(0)] + #[pallet::weight(0)] pub fn set_value(origin: OriginFor, value: bool) -> DispatchResult { // Checks that the extrinsic is signed and gets the signer. // This function will return an error if the extrinsic isn't signed. @@ -79,8 +77,7 @@ pub mod pallet { /// This function flips the value and emits an event, if there is no value in the storage /// then it returns an error. - #[pallet::weight({0})] - #[pallet::call_index(1)] + #[pallet::weight(0)] pub fn flip_value(origin: OriginFor) -> DispatchResult { let who = ensure_signed(origin)?; diff --git a/exercises/ex00-testing/flipper/src/tests/flipper.rs b/exercises/ex00-testing/flipper/src/tests/flipper.rs index 8104587..15f3276 100644 --- a/exercises/ex00-testing/flipper/src/tests/flipper.rs +++ b/exercises/ex00-testing/flipper/src/tests/flipper.rs @@ -1,11 +1,11 @@ use super::mock::*; -use frame_support::{assert_noop, assert_ok, assert_err}; -type Error = crate::Error::; +use crate::{pallet, Error}; +use frame_support::{assert_noop, assert_ok}; #[test] fn set_value_ok() { new_test_ext().execute_with(|| { - assert_ok!(Flipper::set_value(RuntimeOrigin::signed(ALICE), false)); + assert_ok!(Flipper::set_value(Origin::signed(ALICE), false)); assert_eq!(Flipper::value(), Some(false)); }); } diff --git a/exercises/ex00-testing/flipper/src/tests/mock.rs b/exercises/ex00-testing/flipper/src/tests/mock.rs index b609be5..88e8fb5 100644 --- a/exercises/ex00-testing/flipper/src/tests/mock.rs +++ b/exercises/ex00-testing/flipper/src/tests/mock.rs @@ -1,18 +1,22 @@ use crate as pallet_flipper; use frame_support::parameter_types; -use frame_system::GenesisConfig; use sp_core::H256; use sp_runtime::{ - BuildStorage, - traits::{BlakeTwo256, IdentityLookup}, Storage, + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, }; +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 TestRuntime { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + pub enum TestRuntime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event}, Flipper: pallet_flipper::{Pallet, Call, Storage, Event}, } ); @@ -28,41 +32,37 @@ impl frame_system::Config for TestRuntime { type BaseCallFilter = frame_support::traits::Everything; type BlockHashCount = BlockHashCount; type BlockLength = (); + type BlockNumber = u64; type BlockWeights = (); - type RuntimeCall = RuntimeCall; + type Call = Call; type DbWeight = (); - type RuntimeEvent = RuntimeEvent; + type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; + type Header = Header; + type Index = u64; type Lookup = IdentityLookup; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); + type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = SS58Prefix; type SystemWeightInfo = (); type Version = (); - - type RuntimeOrigin = RuntimeOrigin; - type RuntimeTask = (); - type Nonce = u64; - type Block = Block; - type SingleBlockMigrations = (); - type MultiBlockMigrator = (); - type PreInherents = (); - type PostInherents = (); - type PostTransactions = (); } impl pallet_flipper::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; + type Event = Event; } // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - let storage: Storage = as BuildStorage>::build_storage(&GenesisConfig::default()).unwrap(); - storage.into() + frame_system::GenesisConfig::default() + .build_storage::() + .unwrap() + .into() } pub const ALICE: u64 = 0; diff --git a/exercises/ex01-pallet-easy/README.md b/exercises/ex01-pallet-easy/README.md index 2133c42..599570c 100644 --- a/exercises/ex01-pallet-easy/README.md +++ b/exercises/ex01-pallet-easy/README.md @@ -4,7 +4,7 @@ In this exercise, you will build a simple fungible asset pallet. ## What to do? -Edit the code in `ex01-pallet-easy/assets/src/lib.rs` until all tests pass. +Edit the code in `ex01-fungible-token/assets/src/lib.rs` until all tests pass. We placed some helpful comments in the code 😉. Launch the tests by running: diff --git a/exercises/ex01-pallet-easy/assets/Cargo.toml b/exercises/ex01-pallet-easy/assets/Cargo.toml index 17483e2..7a35a8a 100644 --- a/exercises/ex01-pallet-easy/assets/Cargo.toml +++ b/exercises/ex01-pallet-easy/assets/Cargo.toml @@ -13,14 +13,15 @@ scale-info = { version = "2.0.1", default-features = false, features = [ "derive", ] } -frame-support = "38.0.0" -frame-system = "38.0.0" -sp-std = "14.0.0" -sp-core = "34.0.0" +frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } + [dev-dependencies] -sp-io = "38.0.0" -sp-runtime = "39.0.2" +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } [features] default = ["std"] diff --git a/exercises/ex01-pallet-easy/assets/src/lib.rs b/exercises/ex01-pallet-easy/assets/src/lib.rs index 476d558..57e8ced 100644 --- a/exercises/ex01-pallet-easy/assets/src/lib.rs +++ b/exercises/ex01-pallet-easy/assets/src/lib.rs @@ -10,27 +10,24 @@ use types::*; #[cfg(test)] mod tests; -#[allow(unexpected_cfgs)] // skip warning "unexpected `cfg` condition value: `try-runtime`" #[frame_support::pallet] pub mod pallet { use super::*; - use frame_support::{pallet_prelude::*, traits::StorageVersion}; + use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); - /// Configure the pallet by specifying the parameters and types on which it depends. #[pallet::config] pub trait Config: frame_system::Config { /// Because this pallet emits events, it depends on the runtime's definition of an event. - type RuntimeEvent: From> + IsType<::RuntimeEvent>; + type Event: From> + IsType<::Event>; #[pallet::constant] type MaxLength: Get; } #[pallet::pallet] - #[pallet::storage_version(STORAGE_VERSION)] + #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(_); // The pallet's runtime storage items. @@ -118,8 +115,7 @@ pub mod pallet { // Dispatchable functions must be annotated with a weight and must return a DispatchResult. #[pallet::call] impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight({0})] + #[pallet::weight(0)] pub fn create(origin: OriginFor) -> DispatchResult { let origin = ensure_signed(origin)?; @@ -137,8 +133,7 @@ pub mod pallet { Ok(()) } - #[pallet::call_index(1)] - #[pallet::weight({0})] + #[pallet::weight(0)] pub fn set_metadata( origin: OriginFor, asset_id: AssetId, @@ -156,8 +151,7 @@ pub mod pallet { Ok(()) } - #[pallet::call_index(2)] - #[pallet::weight({0})] + #[pallet::weight(0)] pub fn mint( origin: OriginFor, asset_id: AssetId, @@ -189,8 +183,7 @@ pub mod pallet { Ok(()) } - #[pallet::call_index(3)] - #[pallet::weight({0})] + #[pallet::weight(0)] pub fn burn(origin: OriginFor, asset_id: AssetId, amount: u128) -> DispatchResult { // TODO: // - Ensure the extrinsic origin is a signed transaction. @@ -201,8 +194,7 @@ pub mod pallet { Ok(()) } - #[pallet::call_index(4)] - #[pallet::weight({0})] + #[pallet::weight(0)] pub fn transfer( origin: OriginFor, asset_id: AssetId, diff --git a/exercises/ex01-pallet-easy/assets/src/tests/assets.rs b/exercises/ex01-pallet-easy/assets/src/tests/assets.rs index 2492870..9c2437e 100644 --- a/exercises/ex01-pallet-easy/assets/src/tests/assets.rs +++ b/exercises/ex01-pallet-easy/assets/src/tests/assets.rs @@ -1,7 +1,7 @@ use crate::{tests::mock::*, Error}; use frame_support::{assert_noop, assert_ok, error::BadOrigin, BoundedVec}; -pub fn last_event() -> RuntimeEvent { +pub fn last_event() -> Event { frame_system::Pallet::::events() .pop() .expect("Event expected") @@ -15,7 +15,7 @@ mod create { fn ok() { new_test_ext().execute_with(|| { // The execution went through without error. - assert_ok!(Assets::create(RuntimeOrigin::signed(ALICE))); + assert_ok!(Assets::create(Origin::signed(ALICE))); // The nonce was increased. assert!(Assets::nonce() == 1); @@ -32,7 +32,7 @@ mod create { // The event was deposited assert_eq!( last_event(), - RuntimeEvent::Assets(crate::Event::Created { + Event::Assets(crate::Event::Created { owner: ALICE, asset_id: 0 }) @@ -43,7 +43,7 @@ mod create { #[test] fn must_be_signed() { new_test_ext().execute_with(|| { - assert_noop!(Assets::create(RuntimeOrigin::none()), BadOrigin); + assert_noop!(Assets::create(Origin::none()), BadOrigin); }) } } @@ -55,7 +55,7 @@ mod set_metadata { #[test] fn ok() { new_test_ext().execute_with(|| { - assert_ok!(Assets::create(RuntimeOrigin::signed(ALICE))); + assert_ok!(Assets::create(Origin::signed(ALICE))); let name: BoundedVec::MaxLength> = BoundedVec::try_from("TestAsset".as_bytes().to_vec()).unwrap(); @@ -63,7 +63,7 @@ mod set_metadata { BoundedVec::try_from("TASS".as_bytes().to_vec()).unwrap(); assert_ok!(Assets::set_metadata( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 0, name.clone(), symbol.clone() @@ -78,7 +78,7 @@ mod set_metadata { // The event was deposited assert_eq!( last_event(), - RuntimeEvent::Assets(crate::Event::MetadataSet { + Event::Assets(crate::Event::MetadataSet { asset_id: 0, name, symbol @@ -94,9 +94,9 @@ mod set_metadata { BoundedVec::try_from("TestAsset".as_bytes().to_vec()).unwrap(); let symbol: BoundedVec::MaxLength> = BoundedVec::try_from("TASS".as_bytes().to_vec()).unwrap(); - assert_ok!(Assets::create(RuntimeOrigin::signed(ALICE))); + assert_ok!(Assets::create(Origin::signed(ALICE))); assert_noop!( - Assets::set_metadata(RuntimeOrigin::none(), 0, name, symbol), + Assets::set_metadata(Origin::none(), 0, name, symbol), BadOrigin ); }) @@ -110,7 +110,7 @@ mod set_metadata { let symbol: BoundedVec::MaxLength> = BoundedVec::try_from("TASS".as_bytes().to_vec()).unwrap(); assert_noop!( - Assets::set_metadata(RuntimeOrigin::signed(ALICE), 0, name, symbol,), + Assets::set_metadata(Origin::signed(ALICE), 0, name, symbol,), Error::::UnknownAssetId ); }) @@ -119,14 +119,14 @@ mod set_metadata { #[test] fn must_be_owner() { new_test_ext().execute_with(|| { - assert_ok!(Assets::create(RuntimeOrigin::signed(ALICE))); + assert_ok!(Assets::create(Origin::signed(ALICE))); let name: BoundedVec::MaxLength> = BoundedVec::try_from("TestAsset".as_bytes().to_vec()).unwrap(); let symbol: BoundedVec::MaxLength> = BoundedVec::try_from("TASS".as_bytes().to_vec()).unwrap(); assert_noop!( - Assets::set_metadata(RuntimeOrigin::signed(BOB), 0, name, symbol,), + Assets::set_metadata(Origin::signed(BOB), 0, name, symbol,), Error::::NoPermission ); }) @@ -139,7 +139,7 @@ mod mint { #[test] fn ok() { new_test_ext().execute_with(|| { - assert_ok!(Assets::create(RuntimeOrigin::signed(ALICE))); + assert_ok!(Assets::create(Origin::signed(ALICE))); let mut total_supply = Assets::asset(0).unwrap().supply; assert_eq!(total_supply, 0); @@ -150,7 +150,7 @@ mod mint { let amount = 100; // Can mint to itself. - assert_ok!(Assets::mint(RuntimeOrigin::signed(ALICE), 0, amount, ALICE)); + assert_ok!(Assets::mint(Origin::signed(ALICE), 0, amount, ALICE)); total_supply += amount; // Total supply has been increased. assert_eq!(Assets::asset(0).unwrap().supply, total_supply); @@ -159,7 +159,7 @@ mod mint { // The event was deposited assert_eq!( last_event(), - RuntimeEvent::Assets(crate::Event::Minted { + Event::Assets(crate::Event::Minted { asset_id: 0, owner: ALICE, total_supply @@ -167,7 +167,7 @@ mod mint { ); // Can mint to somebody else. - assert_ok!(Assets::mint(RuntimeOrigin::signed(ALICE), 0, amount, BOB)); + assert_ok!(Assets::mint(Origin::signed(ALICE), 0, amount, BOB)); total_supply += amount; assert_eq!(Assets::asset(0).unwrap().supply, total_supply); assert_eq!(Assets::account(0, BOB), amount); @@ -175,7 +175,7 @@ mod mint { // The event was deposited assert_eq!( last_event(), - RuntimeEvent::Assets(crate::Event::Minted { + Event::Assets(crate::Event::Minted { asset_id: 0, owner: BOB, total_supply @@ -187,18 +187,18 @@ mod mint { #[test] fn ok_saturating() { new_test_ext().execute_with(|| { - assert_ok!(Assets::create(RuntimeOrigin::signed(ALICE))); + assert_ok!(Assets::create(Origin::signed(ALICE))); let first_mint_amount = std::u128::MAX - 50; let second_mint_amount = 100; assert_ok!(Assets::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 0, first_mint_amount, ALICE )); assert_ok!(Assets::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 0, second_mint_amount, BOB @@ -212,8 +212,8 @@ mod mint { #[test] fn must_be_signed() { new_test_ext().execute_with(|| { - assert_ok!(Assets::create(RuntimeOrigin::signed(ALICE))); - assert_noop!(Assets::mint(RuntimeOrigin::none(), 0, 100, BOB), BadOrigin); + assert_ok!(Assets::create(Origin::signed(ALICE))); + assert_noop!(Assets::mint(Origin::none(), 0, 100, BOB), BadOrigin); }) } @@ -221,7 +221,7 @@ mod mint { fn must_exist() { new_test_ext().execute_with(|| { assert_noop!( - Assets::mint(RuntimeOrigin::signed(ALICE), 0, 100, BOB), + Assets::mint(Origin::signed(ALICE), 0, 100, BOB), Error::::UnknownAssetId ); }) @@ -230,10 +230,10 @@ mod mint { #[test] fn must_be_owner() { new_test_ext().execute_with(|| { - assert_ok!(Assets::create(RuntimeOrigin::signed(ALICE))); + assert_ok!(Assets::create(Origin::signed(ALICE))); assert_noop!( - Assets::mint(RuntimeOrigin::signed(BOB), 0, 100, BOB), + Assets::mint(Origin::signed(BOB), 0, 100, BOB), Error::::NoPermission ); }) @@ -246,15 +246,15 @@ mod burn { #[test] fn ok() { new_test_ext().execute_with(|| { - assert_ok!(Assets::create(RuntimeOrigin::signed(ALICE))); + assert_ok!(Assets::create(Origin::signed(ALICE))); let mint_amount = 100; let burn_amount = 50; - assert_ok!(Assets::mint(RuntimeOrigin::signed(ALICE), 0, mint_amount, BOB)); + assert_ok!(Assets::mint(Origin::signed(ALICE), 0, mint_amount, BOB)); let mut total_supply = Assets::asset(0).unwrap().supply; - assert_ok!(Assets::burn(RuntimeOrigin::signed(BOB), 0, burn_amount)); + assert_ok!(Assets::burn(Origin::signed(BOB), 0, burn_amount)); total_supply -= burn_amount; // Total supply and account have been reduced by burn_amount. assert_eq!(Assets::asset(0).unwrap().supply, total_supply); @@ -263,7 +263,7 @@ mod burn { // The event was deposited assert_eq!( last_event(), - RuntimeEvent::Assets(crate::Event::Burned { + Event::Assets(crate::Event::Burned { asset_id: 0, owner: BOB, total_supply @@ -275,16 +275,16 @@ mod burn { #[test] fn ok_saturating() { new_test_ext().execute_with(|| { - assert_ok!(Assets::create(RuntimeOrigin::signed(ALICE))); + assert_ok!(Assets::create(Origin::signed(ALICE))); let mint_amount = 100; let burn_amount = mint_amount + 1; - assert_ok!(Assets::mint(RuntimeOrigin::signed(ALICE), 0, mint_amount, ALICE)); - assert_ok!(Assets::mint(RuntimeOrigin::signed(ALICE), 0, mint_amount, BOB)); + assert_ok!(Assets::mint(Origin::signed(ALICE), 0, mint_amount, ALICE)); + assert_ok!(Assets::mint(Origin::signed(ALICE), 0, mint_amount, BOB)); let total_supply = Assets::asset(0).unwrap().supply; - assert_ok!(Assets::burn(RuntimeOrigin::signed(BOB), 0, burn_amount)); + assert_ok!(Assets::burn(Origin::signed(BOB), 0, burn_amount)); // Total supply and account have been reduced by mint_amount. assert_eq!(Assets::asset(0).unwrap().supply, total_supply - mint_amount); assert_eq!(Assets::account(0, BOB), 0); @@ -292,7 +292,7 @@ mod burn { // The event was deposited assert_eq!( last_event(), - RuntimeEvent::Assets(crate::Event::Burned { + Event::Assets(crate::Event::Burned { asset_id: 0, owner: BOB, total_supply: total_supply - mint_amount, @@ -304,8 +304,8 @@ mod burn { #[test] fn must_be_signed() { new_test_ext().execute_with(|| { - assert_ok!(Assets::create(RuntimeOrigin::signed(ALICE))); - assert_noop!(Assets::burn(RuntimeOrigin::none(), 0, 100), BadOrigin); + assert_ok!(Assets::create(Origin::signed(ALICE))); + assert_noop!(Assets::burn(Origin::none(), 0, 100), BadOrigin); }) } @@ -313,7 +313,7 @@ mod burn { fn must_exist() { new_test_ext().execute_with(|| { assert_noop!( - Assets::burn(RuntimeOrigin::signed(ALICE), 0, 100), + Assets::burn(Origin::signed(ALICE), 0, 100), Error::::UnknownAssetId ); }) @@ -326,16 +326,16 @@ mod transfer { #[test] fn ok() { new_test_ext().execute_with(|| { - assert_ok!(Assets::create(RuntimeOrigin::signed(ALICE))); + assert_ok!(Assets::create(Origin::signed(ALICE))); let mint_amount = 100; let transfer_amount = 50; - assert_ok!(Assets::mint(RuntimeOrigin::signed(ALICE), 0, mint_amount, BOB)); + assert_ok!(Assets::mint(Origin::signed(ALICE), 0, mint_amount, BOB)); let total_supply = Assets::asset(0).unwrap().supply; assert_ok!(Assets::transfer( - RuntimeOrigin::signed(BOB), + Origin::signed(BOB), 0, transfer_amount, ALICE @@ -350,7 +350,7 @@ mod transfer { // The event was deposited assert_eq!( last_event(), - RuntimeEvent::Assets(crate::Event::Transferred { + Event::Assets(crate::Event::Transferred { asset_id: 0, from: BOB, to: ALICE, @@ -363,14 +363,14 @@ mod transfer { #[test] fn ok_saturating() { new_test_ext().execute_with(|| { - assert_ok!(Assets::create(RuntimeOrigin::signed(ALICE))); + assert_ok!(Assets::create(Origin::signed(ALICE))); let mint_amount = 100; let transfer_amount = mint_amount + 1; - assert_ok!(Assets::mint(RuntimeOrigin::signed(ALICE), 0, mint_amount, BOB)); + assert_ok!(Assets::mint(Origin::signed(ALICE), 0, mint_amount, BOB)); assert_ok!(Assets::transfer( - RuntimeOrigin::signed(BOB), + Origin::signed(BOB), 0, transfer_amount, ALICE @@ -384,8 +384,8 @@ mod transfer { #[test] fn must_be_signed() { new_test_ext().execute_with(|| { - assert_ok!(Assets::create(RuntimeOrigin::signed(ALICE))); - assert_noop!(Assets::transfer(RuntimeOrigin::none(), 0, 100, BOB), BadOrigin); + assert_ok!(Assets::create(Origin::signed(ALICE))); + assert_noop!(Assets::transfer(Origin::none(), 0, 100, BOB), BadOrigin); }) } @@ -393,7 +393,7 @@ mod transfer { fn must_exist() { new_test_ext().execute_with(|| { assert_noop!( - Assets::transfer(RuntimeOrigin::signed(ALICE), 0, 100, BOB), + Assets::transfer(Origin::signed(ALICE), 0, 100, BOB), Error::::UnknownAssetId ); }) diff --git a/exercises/ex01-pallet-easy/assets/src/tests/mock.rs b/exercises/ex01-pallet-easy/assets/src/tests/mock.rs index 0ca1b84..dec9612 100644 --- a/exercises/ex01-pallet-easy/assets/src/tests/mock.rs +++ b/exercises/ex01-pallet-easy/assets/src/tests/mock.rs @@ -1,15 +1,22 @@ use crate as pallet_assets; use frame_support::parameter_types; -use frame_system::GenesisConfig; use sp_core::H256; -use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, BuildStorage, Storage}; +use sp_runtime::{ + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, +}; +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 TestRuntime { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + pub enum TestRuntime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event}, Assets: pallet_assets::{Pallet, Call, Storage, Event}, } ); @@ -25,31 +32,25 @@ impl frame_system::Config for TestRuntime { type BaseCallFilter = frame_support::traits::Everything; type BlockHashCount = BlockHashCount; type BlockLength = (); + type BlockNumber = u64; type BlockWeights = (); + type Call = Call; type DbWeight = (); + type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; + type Header = Header; + type Index = u64; type Lookup = IdentityLookup; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); + type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = SS58Prefix; type SystemWeightInfo = (); type Version = (); - - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type RuntimeTask = (); - type Nonce = u64; - type Block = Block; - type SingleBlockMigrations = (); - type MultiBlockMigrator = (); - type PreInherents = (); - type PostInherents = (); - type PostTransactions = (); } parameter_types! { @@ -57,14 +58,14 @@ parameter_types! { } impl pallet_assets::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; + type Event = Event; type MaxLength = MaxLength; } // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - let storage: Storage = as BuildStorage>::build_storage(&GenesisConfig::default()).unwrap(); - let mut ext = sp_io::TestExternalities::new(storage); + let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut ext = sp_io::TestExternalities::new(t); // In order to emit events the block number must be more than 0 ext.execute_with(|| System::set_block_number(1)); ext diff --git a/exercises/ex01-pallet-easy/assets/src/types.rs b/exercises/ex01-pallet-easy/assets/src/types.rs index f98c4a5..c122657 100644 --- a/exercises/ex01-pallet-easy/assets/src/types.rs +++ b/exercises/ex01-pallet-easy/assets/src/types.rs @@ -2,9 +2,9 @@ use codec::{Decode, Encode}; use frame_support::{ pallet_prelude::{BoundedVec, MaxEncodedLen}, traits::Get, + RuntimeDebug, }; use scale_info::TypeInfo; -use sp_core::RuntimeDebug; pub type AssetId = u128; diff --git a/exercises/ex02-runtime/README.md b/exercises/ex02-runtime/README.md index 93df597..63ba703 100644 --- a/exercises/ex02-runtime/README.md +++ b/exercises/ex02-runtime/README.md @@ -3,27 +3,14 @@ A Substrate based blockchain is made of the sum of the pallets it includes. In this exercise, you are going to learn how to include a pallet in a runtime. -[Substrate SDK](https://github.com/paritytech/polkadot-sdk#-documentation) | -[Templates](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/templates/index.html): -- [Minimal](https://github.com/paritytech/polkadot-sdk-minimal-template) -- [Solo-Chain](https://github.com/paritytech/polkadot-sdk-solochain-template) (ex-"substrate-node-template") -- [Para-Chain](https://github.com/paritytech/polkadot-sdk-parachain-template) -- [OpenZeppelin](https://github.com/OpenZeppelin/polkadot-runtime-templates) - -The most recent version of solo-chain template at the time of this writing is v0.0.2: -``` -## tag: v0.0.2, commit: 8599efc46aee8359692df055cc0818984f27763e -git clone https://github.com/paritytech/polkadot-sdk-solochain-template -cd polkadot-sdk-solochain-template && rm -rf .git/ .github/ -``` - +We added a git submodule to this repository: [substrate-node-template](https://github.com/substrate-developer-hub/substrate-node-template). It's a great unlicenced project that offers a functional, yet empty, Substrate blockchain. You can think about it as a skeleton, ready to receive the flesh and life you chose to infuse in it. We are going to add the asset pallet we wrote in the previous exercise to this runtime, and then run it. ## Step 0: Dry run ```shell -$ cd polkadot-sdk-solochain-template +$ cd substrate-node-template $ cargo build $ cargo run -- --dev ``` @@ -47,7 +34,7 @@ Great. Now go back to your terminal and hit `Ctrl + c` to kill the chain. We are ## Step 1: Import our code To be able to use our code in this project, we have to add it to the manifest. -Open `polkadot-sdk-solochain-template/runtime/Cargo.toml`. +Open `substrate-node-template/runtime/Cargo.toml`. And add `pallet_assets` as a dependency: ```toml [dependencies] @@ -62,7 +49,7 @@ Compile again to make sure the crate is well added to the project. ## Step 1: construct_runtime! -Open `polkadot-sdk-solochain-template/runtime/src/lib.rs`. +Open `substrate-node-template/runtime/src/lib.rs`. Find the `construct_runtime!` macro call. That's where we declare the pallets we want our runtime to use. That's where we have to add our `assets` pallet. First thing first, add the pallet assets to the runtime. diff --git a/exercises/ex03-pallet-intermediate/nft/Cargo.toml b/exercises/ex03-pallet-intermediate/nft/Cargo.toml index 6d1e45a..7cf68d5 100644 --- a/exercises/ex03-pallet-intermediate/nft/Cargo.toml +++ b/exercises/ex03-pallet-intermediate/nft/Cargo.toml @@ -13,14 +13,15 @@ scale-info = { version = "2.0.1", default-features = false, features = [ "derive", ] } -frame-support = "38.0.0" -frame-system = "38.0.0" -sp-std = "14.0.0" -sp-core = "34.0.0" +frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } + [dev-dependencies] -sp-io = "38.0.0" -sp-runtime = "39.0.2" +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } [features] default = ["std"] diff --git a/exercises/ex03-pallet-intermediate/nft/src/lib.rs b/exercises/ex03-pallet-intermediate/nft/src/lib.rs index ae0a3b5..09d140e 100644 --- a/exercises/ex03-pallet-intermediate/nft/src/lib.rs +++ b/exercises/ex03-pallet-intermediate/nft/src/lib.rs @@ -18,18 +18,16 @@ pub mod pallet { use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); - #[pallet::config] pub trait Config: frame_system::Config + scale_info::TypeInfo { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; + type Event: From> + IsType<::Event>; #[pallet::constant] type MaxLength: Get; } #[pallet::pallet] - #[pallet::storage_version(STORAGE_VERSION)] + #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(_); #[pallet::storage] @@ -90,8 +88,7 @@ pub mod pallet { #[pallet::call] impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight({0})] + #[pallet::weight(0)] pub fn mint( origin: OriginFor, metadata: BoundedVec, @@ -100,18 +97,12 @@ pub mod pallet { Ok(()) } - #[pallet::call_index(1)] - #[pallet::weight({0})] - pub fn burn( - origin: OriginFor, - asset_id: UniqueAssetId, - amount: u128, - ) -> DispatchResult { + #[pallet::weight(0)] + pub fn burn(origin: OriginFor, asset_id: UniqueAssetId, amount: u128) -> DispatchResult { Ok(()) } - #[pallet::call_index(2)] - #[pallet::weight({0})] + #[pallet::weight(0)] pub fn transfer( origin: OriginFor, asset_id: UniqueAssetId, diff --git a/exercises/ex03-pallet-intermediate/nft/src/tests/mock.rs b/exercises/ex03-pallet-intermediate/nft/src/tests/mock.rs index c45cb0e..c5cd22a 100644 --- a/exercises/ex03-pallet-intermediate/nft/src/tests/mock.rs +++ b/exercises/ex03-pallet-intermediate/nft/src/tests/mock.rs @@ -1,15 +1,22 @@ use crate as pallet_nft; use frame_support::parameter_types; -use frame_system::GenesisConfig; use sp_core::H256; -use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, BuildStorage, Storage}; +use sp_runtime::{ + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, +}; +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 TestRuntime { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + pub enum TestRuntime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event}, NFTs: pallet_nft::{Pallet, Call, Storage, Event}, } ); @@ -25,31 +32,25 @@ impl frame_system::Config for TestRuntime { type BaseCallFilter = frame_support::traits::Everything; type BlockHashCount = BlockHashCount; type BlockLength = (); + type BlockNumber = u64; type BlockWeights = (); + type Call = Call; type DbWeight = (); + type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; + type Header = Header; + type Index = u64; type Lookup = IdentityLookup; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); + type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = SS58Prefix; type SystemWeightInfo = (); type Version = (); - - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type RuntimeTask = (); - type Nonce = u64; - type Block = Block; - type SingleBlockMigrations = (); - type MultiBlockMigrator = (); - type PreInherents = (); - type PostInherents = (); - type PostTransactions = (); } parameter_types! { @@ -57,14 +58,14 @@ parameter_types! { } impl pallet_nft::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; + type Event = Event; type MaxLength = MaxLength; } // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - let storage: Storage = as BuildStorage>::build_storage(&GenesisConfig::default()).unwrap(); - let mut ext = sp_io::TestExternalities::new(storage); + let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut ext = sp_io::TestExternalities::new(t); // In order to emit events the block number must be more than 0 ext.execute_with(|| System::set_block_number(1)); ext diff --git a/exercises/ex03-pallet-intermediate/nft/src/tests/unique_assets.rs b/exercises/ex03-pallet-intermediate/nft/src/tests/unique_assets.rs index 4196bc5..9f9dd02 100644 --- a/exercises/ex03-pallet-intermediate/nft/src/tests/unique_assets.rs +++ b/exercises/ex03-pallet-intermediate/nft/src/tests/unique_assets.rs @@ -1,7 +1,7 @@ use crate::{tests::mock::*, Error}; use frame_support::{assert_noop, assert_ok, error::BadOrigin, BoundedVec}; -fn last_event() -> RuntimeEvent { +fn last_event() -> Event { frame_system::Pallet::::events() .pop() .expect("Event expected") @@ -16,7 +16,7 @@ mod mint { new_test_ext().execute_with(|| { let metadata: BoundedVec::MaxLength> = "Some metadata".as_bytes().to_vec().try_into().unwrap(); - assert_ok!(NFTs::mint(RuntimeOrigin::signed(ALICE), metadata.clone(), 5)); + assert_ok!(NFTs::mint(Origin::signed(ALICE), metadata.clone(), 5)); assert_eq!(NFTs::nonce(), 1); @@ -27,7 +27,7 @@ mod mint { assert_eq!(NFTs::account(0, ALICE), 5); assert_eq!( last_event(), - RuntimeEvent::NFTs(crate::Event::Created { + Event::NFTs(crate::Event::Created { creator: ALICE, asset_id: 0 }) @@ -40,7 +40,7 @@ mod mint { new_test_ext().execute_with(|| { assert_noop!( NFTs::mint( - RuntimeOrigin::none(), + Origin::none(), "Some metadata".as_bytes().to_vec().try_into().unwrap(), 5 ), @@ -54,7 +54,7 @@ mod mint { new_test_ext().execute_with(|| { assert_noop!( NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), 0 ), @@ -73,12 +73,12 @@ mod transfer { let minted_amount = 5; let transfered_amount = 2; assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), minted_amount )); assert_ok!(NFTs::transfer( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 0, transfered_amount, BOB @@ -89,7 +89,7 @@ mod transfer { assert_eq!( last_event(), - RuntimeEvent::NFTs(crate::Event::Transferred { + Event::NFTs(crate::Event::Transferred { asset_id: 0, from: ALICE, to: BOB, @@ -105,12 +105,12 @@ mod transfer { let minted_amount = 5; let transfered_amount = 10; assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), minted_amount )); assert_ok!(NFTs::transfer( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 0, transfered_amount, BOB @@ -121,7 +121,7 @@ mod transfer { assert_eq!( last_event(), - RuntimeEvent::NFTs(crate::Event::Transferred { + Event::NFTs(crate::Event::Transferred { asset_id: 0, from: ALICE, to: BOB, @@ -136,7 +136,7 @@ mod transfer { new_test_ext().execute_with(|| { assert_noop!( NFTs::mint( - RuntimeOrigin::none(), + Origin::none(), "Some metadata".as_bytes().to_vec().try_into().unwrap(), 5 ), @@ -149,7 +149,7 @@ mod transfer { fn must_exist() { new_test_ext().execute_with(|| { assert_noop!( - NFTs::transfer(RuntimeOrigin::signed(ALICE), 0, 100, BOB), + NFTs::transfer(Origin::signed(ALICE), 0, 100, BOB), Error::::UnknownAssetId ); }) @@ -159,12 +159,12 @@ mod transfer { fn must_own_some() { new_test_ext().execute_with(|| { assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), 5 )); assert_noop!( - NFTs::transfer(RuntimeOrigin::signed(BOB), 0, 2, ALICE), + NFTs::transfer(Origin::signed(BOB), 0, 2, ALICE), Error::::NotOwned ); }) @@ -180,11 +180,11 @@ mod burn { let minted_amount = 5; let burned_amount = 2; assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), minted_amount )); - assert_ok!(NFTs::burn(RuntimeOrigin::signed(ALICE), 0, burned_amount)); + assert_ok!(NFTs::burn(Origin::signed(ALICE), 0, burned_amount)); assert_eq!( NFTs::unique_asset(0).unwrap().supply, @@ -194,7 +194,7 @@ mod burn { assert_eq!( last_event(), - RuntimeEvent::NFTs(crate::Event::Burned { + Event::NFTs(crate::Event::Burned { asset_id: 0, owner: ALICE, total_supply: minted_amount - burned_amount @@ -209,19 +209,19 @@ mod burn { let minted_amount = 5; let burned_amount = 10; assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), minted_amount )); - assert_ok!(NFTs::burn(RuntimeOrigin::signed(ALICE), 0, burned_amount)); + assert_ok!(NFTs::burn(Origin::signed(ALICE), 0, burned_amount)); assert_eq!(NFTs::unique_asset(0).unwrap().supply, 0); assert_eq!(NFTs::account(0, ALICE), 0); assert_eq!( last_event(), - RuntimeEvent::NFTs(crate::Event::Burned { + Event::NFTs(crate::Event::Burned { asset_id: 0, owner: ALICE, total_supply: 0 @@ -233,7 +233,7 @@ mod burn { #[test] fn must_be_signed() { new_test_ext().execute_with(|| { - assert_noop!(NFTs::burn(RuntimeOrigin::none(), 0, 5), BadOrigin); + assert_noop!(NFTs::burn(Origin::none(), 0, 5), BadOrigin); }) } @@ -241,7 +241,7 @@ mod burn { fn must_exist() { new_test_ext().execute_with(|| { assert_noop!( - NFTs::burn(RuntimeOrigin::signed(ALICE), 0, 100), + NFTs::burn(Origin::signed(ALICE), 0, 100), Error::::UnknownAssetId ); }) @@ -251,12 +251,12 @@ mod burn { fn must_own_some() { new_test_ext().execute_with(|| { assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), 5 )); assert_noop!( - NFTs::burn(RuntimeOrigin::signed(BOB), 0, 2), + NFTs::burn(Origin::signed(BOB), 0, 2), Error::::NotOwned ); }) diff --git a/exercises/ex03-pallet-intermediate/nft/src/types.rs b/exercises/ex03-pallet-intermediate/nft/src/types.rs index 4bfe83e..031b17f 100644 --- a/exercises/ex03-pallet-intermediate/nft/src/types.rs +++ b/exercises/ex03-pallet-intermediate/nft/src/types.rs @@ -3,9 +3,9 @@ use codec::{Decode, Encode}; use frame_support::{ pallet_prelude::{BoundedVec, MaxEncodedLen}, traits::Get, + RuntimeDebug, }; use scale_info::TypeInfo; -use sp_core::RuntimeDebug; pub type UniqueAssetId = u128; diff --git a/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/Cargo.toml b/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/Cargo.toml index ea0110d..8a5eb21 100644 --- a/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/Cargo.toml +++ b/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/Cargo.toml @@ -16,18 +16,18 @@ scale-info = { version = "2.0.1", default-features = false, features = [ "derive", ] } -frame-support = "38.0.0" -frame-system = "38.0.0" -sp-std = "14.0.0" -sp-core = "34.0.0" +frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } # Local dependecies pallet-marketplace-nfts = { path = "../marketplace-nfts", default-features = false } [dev-dependencies] -pallet-balances = "39.0.0" -sp-io = "38.0.0" -sp-runtime = "39.0.2" +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.28" } +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } [features] default = ["std"] diff --git a/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/lib.rs b/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/lib.rs index cc6c224..29fde5a 100644 --- a/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/lib.rs +++ b/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/lib.rs @@ -25,11 +25,9 @@ pub mod pallet { use frame_support::pallet_prelude::*; use frame_system::{ensure_signed, pallet_prelude::*}; - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); - #[pallet::config] pub trait Config: frame_system::Config + scale_info::TypeInfo { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; + type Event: From> + IsType<::Event>; type Currency: Currency; // Here are types that allow for the pallet coupling. // Resource must be a type that implements transferable (remember that pallets are types). @@ -42,7 +40,7 @@ pub mod pallet { } #[pallet::pallet] - #[pallet::storage_version(STORAGE_VERSION)] + #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(_); #[pallet::event] diff --git a/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/tests/marketplace.rs b/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/tests/marketplace.rs index 21371b5..7011547 100644 --- a/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/tests/marketplace.rs +++ b/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/tests/marketplace.rs @@ -3,7 +3,7 @@ use frame_support::{assert_noop, assert_ok, error::BadOrigin}; fn create_nft(amount: u128) { let metadata = "Some metadata".as_bytes().to_vec().try_into().unwrap(); - NFTs::mint(RuntimeOrigin::signed(ALICE), metadata, amount).unwrap(); + NFTs::mint(Origin::signed(ALICE), metadata, amount).unwrap(); } fn amount_owned(resource_id: u128, address: u64) -> u128 { @@ -23,7 +23,7 @@ mod set_sale { let amount = 2; assert_ok!(Marketplace::set_sale( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 0, price, amount @@ -39,7 +39,7 @@ mod set_sale { fn nft_does_not_exist() { ExtBuilder::default().balances(vec![]).build().execute_with(|| { assert_noop!( - Marketplace::set_sale(RuntimeOrigin::signed(ALICE), 0, 1000, 2), + Marketplace::set_sale(Origin::signed(ALICE), 0, 1000, 2), Error::::NotEnoughOwned ); }) @@ -50,7 +50,7 @@ mod set_sale { ExtBuilder::default().balances(vec![]).build().execute_with(|| { create_nft(5); assert_noop!( - Marketplace::set_sale(RuntimeOrigin::signed(ALICE), 0, 1000, 0), + Marketplace::set_sale(Origin::signed(ALICE), 0, 1000, 0), Error::::ZeroAmount ); }) @@ -61,7 +61,7 @@ mod set_sale { ExtBuilder::default().balances(vec![]).build().execute_with(|| { create_nft(5); assert_noop!( - Marketplace::set_sale(RuntimeOrigin::signed(ALICE), 0, 1000, 10), + Marketplace::set_sale(Origin::signed(ALICE), 0, 1000, 10), Error::::NotEnoughOwned ); }) @@ -70,7 +70,7 @@ mod set_sale { #[test] fn must_be_signed() { ExtBuilder::default().balances(vec![]).build().execute_with(|| { - assert_noop!(Marketplace::set_sale(RuntimeOrigin::none(), 0, 1000, 2), BadOrigin); + assert_noop!(Marketplace::set_sale(Origin::none(), 0, 1000, 2), BadOrigin); }) } } @@ -84,9 +84,9 @@ mod buy { ExtBuilder::default().balances(vec![(BOB, bob_funds)]).build().execute_with(|| { create_nft(5); let price = 1000; - assert_ok!(Marketplace::set_sale(RuntimeOrigin::signed(ALICE), 0, price, 2)); + assert_ok!(Marketplace::set_sale(Origin::signed(ALICE), 0, price, 2)); - assert_ok!(Marketplace::buy(RuntimeOrigin::signed(BOB), 0, ALICE, 1)); + assert_ok!(Marketplace::buy(Origin::signed(BOB), 0, ALICE, 1)); assert_eq!(bob_funds - price, Balances::free_balance(BOB)); assert_eq!(price, Balances::free_balance(ALICE)); @@ -101,11 +101,11 @@ mod buy { ExtBuilder::default().balances(vec![(BOB, bob_funds)]).build().execute_with(|| { create_nft(5); let price = 1000; - assert_ok!(Marketplace::set_sale(RuntimeOrigin::signed(ALICE), 0, price, 2)); + assert_ok!(Marketplace::set_sale(Origin::signed(ALICE), 0, price, 2)); let amount_buy = 2; let total_price = amount_buy * price; - assert_ok!(Marketplace::buy(RuntimeOrigin::signed(BOB), 0, ALICE, amount_buy)); + assert_ok!(Marketplace::buy(Origin::signed(BOB), 0, ALICE, amount_buy)); assert_eq!(bob_funds - total_price, Balances::free_balance(BOB)); assert_eq!(total_price, Balances::free_balance(ALICE)); @@ -118,10 +118,10 @@ mod buy { fn not_enough_in_sale() { ExtBuilder::default().balances(vec![]).build().execute_with(|| { create_nft(5); - assert_ok!(Marketplace::set_sale(RuntimeOrigin::signed(ALICE), 0, 1000, 2)); + assert_ok!(Marketplace::set_sale(Origin::signed(ALICE), 0, 1000, 2)); assert_noop!( - Marketplace::buy(RuntimeOrigin::signed(BOB), 0, ALICE, 5), + Marketplace::buy(Origin::signed(BOB), 0, ALICE, 5), Error::::NotEnoughInSale ); }) @@ -131,12 +131,12 @@ mod buy { fn not_enough_owned() { ExtBuilder::default().balances(vec![]).build().execute_with(|| { create_nft(5); - assert_ok!(Marketplace::set_sale(RuntimeOrigin::signed(ALICE), 0, 1000, 2)); + assert_ok!(Marketplace::set_sale(Origin::signed(ALICE), 0, 1000, 2)); - assert_ok!(NFTs::transfer(RuntimeOrigin::signed(ALICE), 0, 4, 0)); + assert_ok!(NFTs::transfer(Origin::signed(ALICE), 0, 4, 0)); assert_noop!( - Marketplace::buy(RuntimeOrigin::signed(BOB), 0, ALICE, 2), + Marketplace::buy(Origin::signed(BOB), 0, ALICE, 2), Error::::NotEnoughOwned ); }) @@ -145,7 +145,7 @@ mod buy { #[test] fn must_be_signed() { ExtBuilder::default().balances(vec![]).build().execute_with(|| { - assert_noop!(Marketplace::buy(RuntimeOrigin::none(), 0, ALICE, 1), BadOrigin); + assert_noop!(Marketplace::buy(Origin::none(), 0, ALICE, 1), BadOrigin); }) } } diff --git a/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/tests/mock.rs b/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/tests/mock.rs index bee2e86..60eaadc 100644 --- a/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/tests/mock.rs +++ b/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/tests/mock.rs @@ -1,14 +1,21 @@ use crate as pallet_marketplace; use frame_support::parameter_types; -use frame_system::GenesisConfig; use sp_core::H256; -use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, BuildStorage, Storage}; +use sp_runtime::{ + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, +}; +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 TestRuntime { + pub enum TestRuntime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { System: frame_system, Balances: pallet_balances, @@ -28,31 +35,25 @@ impl frame_system::Config for TestRuntime { type BaseCallFilter = frame_support::traits::Everything; type BlockHashCount = BlockHashCount; type BlockLength = (); + type BlockNumber = u64; type BlockWeights = (); + type Call = Call; type DbWeight = (); + type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; + type Header = Header; + type Index = u64; type Lookup = IdentityLookup; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); + type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = SS58Prefix; type SystemWeightInfo = (); type Version = (); - - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type RuntimeTask = (); - type Nonce = u64; - type Block = Block; - type SingleBlockMigrations = (); - type MultiBlockMigrator = (); - type PreInherents = (); - type PostInherents = (); - type PostTransactions = (); } parameter_types! { @@ -65,17 +66,12 @@ impl pallet_balances::Config for TestRuntime { type AccountStore = System; type Balance = u128; type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; + type Event = Event; type ExistentialDeposit = ExistentialDeposit; type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; type WeightInfo = (); - - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); - type FreezeIdentifier = (); - type MaxFreezes = (); } parameter_types! { @@ -83,14 +79,14 @@ parameter_types! { } impl pallet_marketplace_nfts::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; + type Event = Event; type MaxLength = MaxLength; type NFTId = u128; } impl pallet_marketplace::Config for TestRuntime { type Currency = Balances; - type RuntimeEvent = RuntimeEvent; + type Event = Event; type Resource = NFTs; type ResourceId = u128; } @@ -113,14 +109,15 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { - let mut storage: Storage = as BuildStorage>::build_storage(&GenesisConfig::default()).unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + pallet_balances::GenesisConfig:: { balances: self.caps_endowed_accounts, } - .assimilate_storage(&mut storage) + .assimilate_storage(&mut t) .unwrap(); - let mut ext = sp_io::TestExternalities::new(storage); + let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext } diff --git a/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/types.rs b/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/types.rs index b1f92ca..c745527 100644 --- a/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/types.rs +++ b/exercises/ex04-pallet-coupling/loosely-coupled-marketplace/src/types.rs @@ -1,7 +1,7 @@ use crate::{BalanceOf, Config}; use codec::{Decode, Encode, MaxEncodedLen}; +use frame_support::RuntimeDebug; use scale_info::TypeInfo; -use sp_core::RuntimeDebug; #[derive(Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] #[codec(mel_bound())] diff --git a/exercises/ex04-pallet-coupling/marketplace-nfts/Cargo.toml b/exercises/ex04-pallet-coupling/marketplace-nfts/Cargo.toml index 9a5a289..06de4e9 100644 --- a/exercises/ex04-pallet-coupling/marketplace-nfts/Cargo.toml +++ b/exercises/ex04-pallet-coupling/marketplace-nfts/Cargo.toml @@ -13,14 +13,15 @@ scale-info = { version = "2.0.1", default-features = false, features = [ "derive", ] } -frame-support = "38.0.0" -frame-system = "38.0.0" -sp-std = "14.0.0" -sp-core = "34.0.0" -sp-runtime = "39.0.2" +frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } + [dev-dependencies] -sp-io = "38.0.0" +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } [features] default = ["std"] diff --git a/exercises/ex04-pallet-coupling/marketplace-nfts/src/lib.rs b/exercises/ex04-pallet-coupling/marketplace-nfts/src/lib.rs index aae6a9b..a8d9e78 100644 --- a/exercises/ex04-pallet-coupling/marketplace-nfts/src/lib.rs +++ b/exercises/ex04-pallet-coupling/marketplace-nfts/src/lib.rs @@ -13,18 +13,15 @@ use frame_support::ensure; use sp_runtime::traits::{AtLeast32BitUnsigned, One, Saturating}; use types::*; -#[allow(unexpected_cfgs)] // skip warning "unexpected `cfg` condition value: `try-runtime`" #[frame_support::pallet] pub mod pallet { use super::*; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); - #[pallet::config] pub trait Config: frame_system::Config + scale_info::TypeInfo { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; + type Event: From> + IsType<::Event>; type NFTId: Parameter + AtLeast32BitUnsigned + Default + Copy + MaxEncodedLen; @@ -33,7 +30,7 @@ pub mod pallet { } #[pallet::pallet] - #[pallet::storage_version(STORAGE_VERSION)] + #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(_); #[pallet::storage] @@ -94,8 +91,7 @@ pub mod pallet { #[pallet::call] impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight({0})] + #[pallet::weight(0)] pub fn mint( origin: OriginFor, metadata: BoundedVec, @@ -119,8 +115,7 @@ pub mod pallet { Ok(()) } - #[pallet::call_index(1)] - #[pallet::weight({0})] + #[pallet::weight(0)] pub fn burn(origin: OriginFor, asset_id: T::NFTId, amount: u128) -> DispatchResult { let origin = ensure_signed(origin)?; @@ -154,8 +149,7 @@ pub mod pallet { Ok(()) } - #[pallet::call_index(2)] - #[pallet::weight({0})] + #[pallet::weight(0)] pub fn transfer( origin: OriginFor, asset_id: T::NFTId, diff --git a/exercises/ex04-pallet-coupling/marketplace-nfts/src/tests/mock.rs b/exercises/ex04-pallet-coupling/marketplace-nfts/src/tests/mock.rs index f3bfe62..26aacec 100644 --- a/exercises/ex04-pallet-coupling/marketplace-nfts/src/tests/mock.rs +++ b/exercises/ex04-pallet-coupling/marketplace-nfts/src/tests/mock.rs @@ -1,15 +1,22 @@ use crate as pallet_nft; use frame_support::parameter_types; -use frame_system::GenesisConfig; use sp_core::H256; -use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, BuildStorage, Storage}; +use sp_runtime::{ + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, +}; +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 TestRuntime { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + pub enum TestRuntime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event}, NFTs: pallet_nft::{Pallet, Call, Storage, Event}, } ); @@ -25,31 +32,25 @@ impl frame_system::Config for TestRuntime { type BaseCallFilter = frame_support::traits::Everything; type BlockHashCount = BlockHashCount; type BlockLength = (); + type BlockNumber = u64; type BlockWeights = (); + type Call = Call; type DbWeight = (); + type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; + type Header = Header; + type Index = u64; type Lookup = IdentityLookup; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); + type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = SS58Prefix; type SystemWeightInfo = (); type Version = (); - - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type RuntimeTask = (); - type Nonce = u64; - type Block = Block; - type SingleBlockMigrations = (); - type MultiBlockMigrator = (); - type PreInherents = (); - type PostInherents = (); - type PostTransactions = (); } parameter_types! { @@ -57,15 +58,15 @@ parameter_types! { } impl pallet_nft::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; + type Event = Event; type MaxLength = MaxLength; type NFTId = u128; } // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - let storage: Storage = as BuildStorage>::build_storage(&GenesisConfig::default()).unwrap(); - let mut ext = sp_io::TestExternalities::new(storage); + let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut ext = sp_io::TestExternalities::new(t); // In order to emit events the block number must be more than 0 ext.execute_with(|| System::set_block_number(1)); ext diff --git a/exercises/ex04-pallet-coupling/marketplace-nfts/src/tests/unique_assets.rs b/exercises/ex04-pallet-coupling/marketplace-nfts/src/tests/unique_assets.rs index 7d1113b..9d419b2 100644 --- a/exercises/ex04-pallet-coupling/marketplace-nfts/src/tests/unique_assets.rs +++ b/exercises/ex04-pallet-coupling/marketplace-nfts/src/tests/unique_assets.rs @@ -8,7 +8,7 @@ mod mint { new_test_ext().execute_with(|| { let metadata = "Some metadata".as_bytes().to_vec(); assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), metadata.clone().try_into().unwrap(), 5 )); @@ -27,7 +27,7 @@ mod mint { new_test_ext().execute_with(|| { assert_noop!( NFTs::mint( - RuntimeOrigin::none(), + Origin::none(), "".as_bytes().to_vec().try_into().unwrap(), 5 ), @@ -41,7 +41,7 @@ mod mint { new_test_ext().execute_with(|| { assert_noop!( NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "".as_bytes().to_vec().try_into().unwrap(), 0 ), @@ -60,12 +60,12 @@ mod transfer { let minted_amount = 5; let transfered_amount = 2; assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), minted_amount )); assert_ok!(NFTs::transfer( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 0, transfered_amount, BOB @@ -82,12 +82,12 @@ mod transfer { let minted_amount = 5; let transfered_amount = 10; assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), minted_amount )); assert_ok!(NFTs::transfer( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 0, transfered_amount, BOB @@ -103,7 +103,7 @@ mod transfer { new_test_ext().execute_with(|| { assert_noop!( NFTs::mint( - RuntimeOrigin::none(), + Origin::none(), "".as_bytes().to_vec().try_into().unwrap(), 5 ), @@ -116,7 +116,7 @@ mod transfer { fn must_exist() { new_test_ext().execute_with(|| { assert_noop!( - NFTs::transfer(RuntimeOrigin::signed(ALICE), 0, 100, BOB), + NFTs::transfer(Origin::signed(ALICE), 0, 100, BOB), Error::::Unknown ); }) @@ -126,12 +126,12 @@ mod transfer { fn must_own_some() { new_test_ext().execute_with(|| { assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), 5 )); assert_noop!( - NFTs::transfer(RuntimeOrigin::signed(BOB), 0, 2, ALICE), + NFTs::transfer(Origin::signed(BOB), 0, 2, ALICE), Error::::NotOwned ); }) @@ -147,11 +147,11 @@ mod burn { let minted_amount = 5; let burned_amount = 2; assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), minted_amount )); - assert_ok!(NFTs::burn(RuntimeOrigin::signed(ALICE), 0, burned_amount)); + assert_ok!(NFTs::burn(Origin::signed(ALICE), 0, burned_amount)); assert_eq!( NFTs::unique_asset(0).unwrap().supply, @@ -168,17 +168,17 @@ mod burn { let transfered_amount = 2; let burned_amount = 10; assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), minted_amount )); assert_ok!(NFTs::transfer( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 0, transfered_amount, BOB )); - assert_ok!(NFTs::burn(RuntimeOrigin::signed(BOB), 0, burned_amount)); + assert_ok!(NFTs::burn(Origin::signed(BOB), 0, burned_amount)); assert_eq!( NFTs::unique_asset(0).unwrap().supply, @@ -193,7 +193,7 @@ mod burn { new_test_ext().execute_with(|| { assert_noop!( NFTs::mint( - RuntimeOrigin::none(), + Origin::none(), "".as_bytes().to_vec().try_into().unwrap(), 5 ), @@ -206,7 +206,7 @@ mod burn { fn must_exist() { new_test_ext().execute_with(|| { assert_noop!( - NFTs::transfer(RuntimeOrigin::signed(ALICE), 0, 100, BOB), + NFTs::transfer(Origin::signed(ALICE), 0, 100, BOB), Error::::Unknown ); }) @@ -216,12 +216,12 @@ mod burn { fn must_own_some() { new_test_ext().execute_with(|| { assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), 5 )); assert_noop!( - NFTs::burn(RuntimeOrigin::signed(BOB), 0, 2), + NFTs::burn(Origin::signed(BOB), 0, 2), Error::::NotOwned ); }) diff --git a/exercises/ex04-pallet-coupling/marketplace-nfts/src/types.rs b/exercises/ex04-pallet-coupling/marketplace-nfts/src/types.rs index 493dec1..2cb0594 100644 --- a/exercises/ex04-pallet-coupling/marketplace-nfts/src/types.rs +++ b/exercises/ex04-pallet-coupling/marketplace-nfts/src/types.rs @@ -3,9 +3,9 @@ use codec::{Decode, Encode}; use frame_support::{ pallet_prelude::{BoundedVec, MaxEncodedLen}, traits::Get, + RuntimeDebug, }; use scale_info::TypeInfo; -use sp_core::RuntimeDebug; pub trait Sellable { /// return the amount of `id` possessed by `account` diff --git a/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/Cargo.toml b/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/Cargo.toml index 97d0d6f..b9450ea 100644 --- a/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/Cargo.toml +++ b/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/Cargo.toml @@ -13,18 +13,18 @@ scale-info = { version = "2.0.1", default-features = false, features = [ "derive", ] } -frame-support = "38.0.0" -frame-system = "38.0.0" -sp-std = "14.0.0" -sp-core = "34.0.0" +frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } # Local dependecies pallet-marketplace-nfts = { path = "../marketplace-nfts", default-features = false } [dev-dependencies] -pallet-balances = "39.0.0" -sp-io = "38.0.0" -sp-runtime = "39.0.2" +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.28" } +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } [features] default = ["std"] diff --git a/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/lib.rs b/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/lib.rs index 952edaf..c1c9590 100644 --- a/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/lib.rs +++ b/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/lib.rs @@ -25,16 +25,15 @@ pub mod pallet { use frame_support::pallet_prelude::*; use frame_system::{ensure_signed, pallet_prelude::*}; - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); #[pallet::config] // TODO: add a dependency on pallet_marketplace_nft on the previous line pub trait Config: frame_system::Config + scale_info::TypeInfo { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; + type Event: From> + IsType<::Event>; type Currency: Currency; } #[pallet::pallet] - #[pallet::storage_version(STORAGE_VERSION)] + #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(_); #[pallet::event] @@ -69,8 +68,7 @@ pub mod pallet { #[pallet::call] impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight({0})] + #[pallet::weight(0)] pub fn set_sale( origin: OriginFor, nft_id: NFTId, @@ -91,8 +89,7 @@ pub mod pallet { Ok(()) } - #[pallet::call_index(1)] - #[pallet::weight({0})] + #[pallet::weight(0)] pub fn buy( origin: OriginFor, nft_id: NFTId, diff --git a/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/tests/marketplace.rs b/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/tests/marketplace.rs index f8262c1..bef54b3 100644 --- a/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/tests/marketplace.rs +++ b/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/tests/marketplace.rs @@ -3,7 +3,7 @@ use frame_support::{assert_noop, assert_ok, error::BadOrigin}; fn create_nft(amount: u128) { let metadata = "Some metadata".as_bytes().to_vec().try_into().unwrap(); - NFTs::mint(RuntimeOrigin::signed(ALICE), metadata, amount).unwrap(); + NFTs::mint(Origin::signed(ALICE), metadata, amount).unwrap(); } fn amount_owned(resource_id: u128, address: u64) -> u128 { @@ -21,7 +21,7 @@ mod set_sale { let amount = 2; assert_ok!(Marketplace::set_sale( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 0, price, amount @@ -37,7 +37,7 @@ mod set_sale { fn nft_does_not_exist() { ExtBuilder::default().balances(vec![]).build().execute_with(|| { assert_noop!( - Marketplace::set_sale(RuntimeOrigin::signed(ALICE), 0, 1000, 2), + Marketplace::set_sale(Origin::signed(ALICE), 0, 1000, 2), Error::::NotEnoughOwned ); }) @@ -48,7 +48,7 @@ mod set_sale { ExtBuilder::default().balances(vec![]).build().execute_with(|| { create_nft(5); assert_noop!( - Marketplace::set_sale(RuntimeOrigin::signed(ALICE), 0, 1000, 0), + Marketplace::set_sale(Origin::signed(ALICE), 0, 1000, 0), Error::::ZeroAmount ); }) @@ -59,7 +59,7 @@ mod set_sale { ExtBuilder::default().balances(vec![]).build().execute_with(|| { create_nft(5); assert_noop!( - Marketplace::set_sale(RuntimeOrigin::signed(ALICE), 0, 1000, 10), + Marketplace::set_sale(Origin::signed(ALICE), 0, 1000, 10), Error::::NotEnoughOwned ); }) @@ -68,7 +68,7 @@ mod set_sale { #[test] fn must_be_signed() { ExtBuilder::default().balances(vec![]).build().execute_with(|| { - assert_noop!(Marketplace::set_sale(RuntimeOrigin::none(), 0, 1000, 2), BadOrigin); + assert_noop!(Marketplace::set_sale(Origin::none(), 0, 1000, 2), BadOrigin); }) } } @@ -82,9 +82,9 @@ mod buy { ExtBuilder::default().balances(vec![(BOB, bob_funds)]).build().execute_with(|| { create_nft(5); let price = 1000; - assert_ok!(Marketplace::set_sale(RuntimeOrigin::signed(ALICE), 0, price, 2)); + assert_ok!(Marketplace::set_sale(Origin::signed(ALICE), 0, price, 2)); - assert_ok!(Marketplace::buy(RuntimeOrigin::signed(BOB), 0, ALICE, 1)); + assert_ok!(Marketplace::buy(Origin::signed(BOB), 0, ALICE, 1)); assert_eq!(bob_funds - price, Balances::free_balance(BOB)); assert_eq!(price, Balances::free_balance(ALICE)); @@ -99,11 +99,11 @@ mod buy { ExtBuilder::default().balances(vec![(BOB, bob_funds)]).build().execute_with(|| { create_nft(5); let price = 1000; - assert_ok!(Marketplace::set_sale(RuntimeOrigin::signed(ALICE), 0, price, 2)); + assert_ok!(Marketplace::set_sale(Origin::signed(ALICE), 0, price, 2)); let amount_buy = 2; let total_price = amount_buy * price; - assert_ok!(Marketplace::buy(RuntimeOrigin::signed(BOB), 0, ALICE, amount_buy)); + assert_ok!(Marketplace::buy(Origin::signed(BOB), 0, ALICE, amount_buy)); assert_eq!(bob_funds - total_price, Balances::free_balance(BOB)); assert_eq!(total_price, Balances::free_balance(ALICE)); @@ -116,10 +116,10 @@ mod buy { fn not_enough_in_sale() { ExtBuilder::default().balances(vec![]).build().execute_with(|| { create_nft(5); - assert_ok!(Marketplace::set_sale(RuntimeOrigin::signed(ALICE), 0, 1000, 2)); + assert_ok!(Marketplace::set_sale(Origin::signed(ALICE), 0, 1000, 2)); assert_noop!( - Marketplace::buy(RuntimeOrigin::signed(BOB), 0, ALICE, 5), + Marketplace::buy(Origin::signed(BOB), 0, ALICE, 5), Error::::NotEnoughInSale ); }) @@ -129,12 +129,12 @@ mod buy { fn not_enough_owned() { ExtBuilder::default().balances(vec![]).build().execute_with(|| { create_nft(5); - assert_ok!(Marketplace::set_sale(RuntimeOrigin::signed(ALICE), 0, 1000, 2)); + assert_ok!(Marketplace::set_sale(Origin::signed(ALICE), 0, 1000, 2)); - assert_ok!(NFTs::transfer(RuntimeOrigin::signed(ALICE), 0, 4, 0)); + assert_ok!(NFTs::transfer(Origin::signed(ALICE), 0, 4, 0)); assert_noop!( - Marketplace::buy(RuntimeOrigin::signed(BOB), 0, ALICE, 2), + Marketplace::buy(Origin::signed(BOB), 0, ALICE, 2), Error::::NotEnoughOwned ); }) @@ -143,7 +143,7 @@ mod buy { #[test] fn must_be_signed() { ExtBuilder::default().balances(vec![]).build().execute_with(|| { - assert_noop!(Marketplace::buy(RuntimeOrigin::none(), 0, ALICE, 1), BadOrigin); + assert_noop!(Marketplace::buy(Origin::none(), 0, ALICE, 1), BadOrigin); }) } } diff --git a/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/tests/mock.rs b/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/tests/mock.rs index 3d32e22..3b2fe19 100644 --- a/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/tests/mock.rs +++ b/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/tests/mock.rs @@ -1,15 +1,21 @@ use crate as pallet_marketplace; use frame_support::parameter_types; -use frame_system::GenesisConfig; use sp_core::H256; -use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, BuildStorage}; +use sp_runtime::{ + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, +}; 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 TestRuntime { + pub enum TestRuntime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { System: frame_system, Balances: pallet_balances, @@ -29,32 +35,25 @@ impl frame_system::Config for TestRuntime { type BaseCallFilter = frame_support::traits::Everything; type BlockHashCount = BlockHashCount; type BlockLength = (); + type BlockNumber = u64; type BlockWeights = (); + type Call = Call; type DbWeight = (); + type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; + type Header = Header; + type Index = u64; type Lookup = IdentityLookup; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); + type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = SS58Prefix; type SystemWeightInfo = (); type Version = (); - - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type RuntimeTask = (); - type Nonce = u64; - type Block = Block; - type SingleBlockMigrations = (); - type MultiBlockMigrator = (); - type PreInherents = (); - type PostInherents = (); - type PostTransactions = (); - } parameter_types! { @@ -67,17 +66,12 @@ impl pallet_balances::Config for TestRuntime { type AccountStore = System; type Balance = u128; type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; + type Event = Event; type ExistentialDeposit = ExistentialDeposit; type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; type WeightInfo = (); - - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); - type FreezeIdentifier = (); - type MaxFreezes = (); } parameter_types! { @@ -85,14 +79,14 @@ parameter_types! { } impl pallet_marketplace_nfts::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; + type Event = Event; type MaxLength = MaxLength; type NFTId = u128; } impl pallet_marketplace::Config for TestRuntime { type Currency = Balances; - type RuntimeEvent = RuntimeEvent; + type Event = Event; } // Mock users AccountId @@ -113,15 +107,15 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { - let mut storage = as BuildStorage>::build_storage(&GenesisConfig::default()).unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); pallet_balances::GenesisConfig:: { balances: self.caps_endowed_accounts, } - .assimilate_storage(&mut storage) + .assimilate_storage(&mut t) .unwrap(); - let mut ext = sp_io::TestExternalities::new(storage); + let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext } diff --git a/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/types.rs b/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/types.rs index b1f92ca..c745527 100644 --- a/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/types.rs +++ b/exercises/ex04-pallet-coupling/tightly-coupled-marketplace/src/types.rs @@ -1,7 +1,7 @@ use crate::{BalanceOf, Config}; use codec::{Decode, Encode, MaxEncodedLen}; +use frame_support::RuntimeDebug; use scale_info::TypeInfo; -use sp_core::RuntimeDebug; #[derive(Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] #[codec(mel_bound())] diff --git a/exercises/ex05-hooks/reminder/Cargo.toml b/exercises/ex05-hooks/reminder/Cargo.toml index 4071af8..eb195e3 100644 --- a/exercises/ex05-hooks/reminder/Cargo.toml +++ b/exercises/ex05-hooks/reminder/Cargo.toml @@ -13,14 +13,14 @@ scale-info = { version = "2.0.1", default-features = false, features = [ "derive", ] } -frame-support = "38.0.0" -frame-system = "38.0.0" -sp-std = "14.0.0" +frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } [dev-dependencies] -sp-io = "38.0.0" -sp-core = "34.0.0" -sp-runtime = "39.0.2" +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } [features] default = ["std"] diff --git a/exercises/ex05-hooks/reminder/src/lib.rs b/exercises/ex05-hooks/reminder/src/lib.rs index 74efad4..478b94d 100644 --- a/exercises/ex05-hooks/reminder/src/lib.rs +++ b/exercises/ex05-hooks/reminder/src/lib.rs @@ -10,22 +10,19 @@ mod tests; use sp_std::vec::Vec; -#[allow(unexpected_cfgs)] #[frame_support::pallet] pub mod pallet { use super::*; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); - #[pallet::pallet] - #[pallet::storage_version(STORAGE_VERSION)] + #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(_); #[pallet::config] pub trait Config: frame_system::Config { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; + type Event: From> + IsType<::Event>; } #[pallet::storage] @@ -36,12 +33,12 @@ pub mod pallet { #[pallet::unbounded] #[pallet::getter(fn reminders)] pub type Reminders = - StorageMap<_, Blake2_256, BlockNumberFor, Vec>, ValueQuery>; + StorageMap<_, Blake2_256, T::BlockNumber, Vec>, ValueQuery>; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - ReminderSet(BlockNumberFor, Vec), + ReminderSet(T::BlockNumber, Vec), Reminder(Vec), RemindersExecuteds(u32), } @@ -52,8 +49,8 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { // on_initialize() will be called at the beginning of each new block, before anything - fn on_initialize(n: BlockNumberFor) -> Weight { - let mut used_weight = Weight::zero(); + fn on_initialize(n: T::BlockNumber) -> Weight { + let mut used_weight = 0; // TODO: get the reminders for the block `n` let reminders: Vec> = Vec::new(); // this is an example of how do we get system weights for read and writes. @@ -71,20 +68,20 @@ pub mod pallet { } // TODO: clean the storage, a.k remove the events, after emitting them - used_weight.into() + used_weight } - fn on_finalize(_: BlockNumberFor) { + fn on_finalize(_: T::BlockNumber) { // TODO: emit a `RemindersExecutes` event, with the right value } } #[pallet::call] impl Pallet { - #[pallet::weight(T::DbWeight::get().reads(1) + 10_000.into())] + #[pallet::weight(10_000 + T::DbWeight::get().reads(1))] pub fn schedule_reminder( origin: OriginFor, - at: BlockNumberFor, + at: T::BlockNumber, message: Vec, ) -> DispatchResult { let _ = ensure_signed(origin)?; diff --git a/exercises/ex05-hooks/reminder/src/mock.rs b/exercises/ex05-hooks/reminder/src/mock.rs index 6c82d84..a3562c7 100644 --- a/exercises/ex05-hooks/reminder/src/mock.rs +++ b/exercises/ex05-hooks/reminder/src/mock.rs @@ -4,15 +4,22 @@ use frame_support::{ traits::{ConstU16, ConstU64}, weights::RuntimeDbWeight, }; -use frame_system::GenesisConfig; use sp_core::H256; -use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, BuildStorage}; +use sp_runtime::{ + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, +}; +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 TestRuntime { + pub enum TestRuntime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { System: frame_system, Reminder: pallet_reminder, } @@ -28,40 +35,34 @@ impl frame_system::Config for TestRuntime { type BaseCallFilter = frame_support::traits::Everything; type BlockHashCount = ConstU64<250>; type BlockLength = (); + type BlockNumber = u64; type BlockWeights = (); + type Call = Call; type DbWeight = DbWeight; + type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; + type Header = Header; + type Index = u64; type Lookup = IdentityLookup; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); + type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = ConstU16<42>; type SystemWeightInfo = (); type Version = (); - - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type RuntimeTask = (); - type Nonce = u64; - type Block = Block; - type SingleBlockMigrations = (); - type MultiBlockMigrator = (); - type PreInherents = (); - type PostInherents = (); - type PostTransactions = (); } impl pallet_reminder::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; + type Event = Event; } pub fn new_test_ext() -> sp_io::TestExternalities { - let storage = as BuildStorage>::build_storage(&GenesisConfig::default()).unwrap(); - let mut ext = sp_io::TestExternalities::new(storage); + 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/exercises/ex05-hooks/reminder/src/tests.rs b/exercises/ex05-hooks/reminder/src/tests.rs index 7717520..6020734 100644 --- a/exercises/ex05-hooks/reminder/src/tests.rs +++ b/exercises/ex05-hooks/reminder/src/tests.rs @@ -13,7 +13,7 @@ mod mint { fn schedule() { new_test_ext().execute_with(|| { assert_ok!(Reminder::schedule_reminder( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 1, "test".as_bytes().to_vec(), )); @@ -30,12 +30,12 @@ mod mint { fn execution_and_cleanup() { new_test_ext().execute_with(|| { assert_ok!(Reminder::schedule_reminder( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 2, "test".as_bytes().to_vec(), )); assert_ok!(Reminder::schedule_reminder( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 2, "test2".as_bytes().to_vec(), )); @@ -52,19 +52,19 @@ mod mint { fn counting_events() { new_test_ext().execute_with(|| { assert_ok!(Reminder::schedule_reminder( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 2, "test".as_bytes().to_vec(), )); assert_ok!(Reminder::schedule_reminder( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 2, "test2".as_bytes().to_vec(), )); >::on_initialize(2); assert_eq!(Reminder::event_counter(), 2); >::on_finalize(2); - System::assert_last_event(RuntimeEvent::Reminder(crate::Event::RemindersExecuteds(2))); + System::assert_last_event(Event::Reminder(crate::Event::RemindersExecuteds(2))); }) } @@ -72,12 +72,12 @@ mod mint { fn reset_counter() { new_test_ext().execute_with(|| { assert_ok!(Reminder::schedule_reminder( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 2, "test".as_bytes().to_vec(), )); assert_ok!(Reminder::schedule_reminder( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 2, "test2".as_bytes().to_vec(), )); @@ -96,12 +96,12 @@ mod mint { ::DbWeight::get(); assert_ok!(Reminder::schedule_reminder( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 2, "test".as_bytes().to_vec(), )); assert_ok!(Reminder::schedule_reminder( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 2, "test2".as_bytes().to_vec(), )); diff --git a/exercises/ex06-weights/weights/Cargo.toml b/exercises/ex06-weights/weights/Cargo.toml index d1d76cf..735e108 100644 --- a/exercises/ex06-weights/weights/Cargo.toml +++ b/exercises/ex06-weights/weights/Cargo.toml @@ -13,17 +13,18 @@ scale-info = { version = "2.0.1", default-features = false, features = [ "derive", ] } -frame-benchmarking = "38.0.0" +frame-benchmarking = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", optional = true } -frame-support = "38.0.0" -frame-system = "38.0.0" -sp-io = "38.0.0" -sp-std = "14.0.0" -sp-core = "34.0.0" +frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } [dev-dependencies] -pallet-balances = "39.0.0" -sp-runtime = "39.0.2" +pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } [features] # TODO: replace ["std"] with ["std", "runtime-benchmarks"] to activate the benchmark feature diff --git a/exercises/ex06-weights/weights/src/lib.rs b/exercises/ex06-weights/weights/src/lib.rs index c822cc3..c74bcea 100644 --- a/exercises/ex06-weights/weights/src/lib.rs +++ b/exercises/ex06-weights/weights/src/lib.rs @@ -24,16 +24,14 @@ pub mod pallet { use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); - #[pallet::config] pub trait Config: frame_system::Config { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; + type Event: From> + IsType<::Event>; type WeightInfo; } #[pallet::pallet] - #[pallet::storage_version(STORAGE_VERSION)] + #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(_); #[pallet::storage] diff --git a/exercises/ex06-weights/weights/src/mock.rs b/exercises/ex06-weights/weights/src/mock.rs index 6568af1..6e798f3 100644 --- a/exercises/ex06-weights/weights/src/mock.rs +++ b/exercises/ex06-weights/weights/src/mock.rs @@ -4,18 +4,24 @@ use frame_support::{ traits::{ConstU16, ConstU64}, weights::RuntimeDbWeight, }; -use frame_system::GenesisConfig; +use frame_system as system; use sp_core::H256; use sp_runtime::{ - traits::{BlakeTwo256, IdentityLookup}, BuildStorage, + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, }; +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 { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + pub enum Test where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event}, Weight: pallet_weights::{Pallet, Call, Storage, Event}, Balances: pallet_balances, @@ -32,31 +38,25 @@ impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockHashCount = ConstU64<250>; type BlockLength = (); + type BlockNumber = u64; type BlockWeights = (); + type Call = Call; type DbWeight = DbWeight; + type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; + type Header = Header; + type Index = u64; type Lookup = IdentityLookup; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); + type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = ConstU16<42>; type SystemWeightInfo = (); type Version = (); - - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type RuntimeTask = (); - type Nonce = u64; - type Block = Block; - type SingleBlockMigrations = (); - type MultiBlockMigrator = (); - type PreInherents = (); - type PostInherents = (); - type PostTransactions = (); } parameter_types! { @@ -69,26 +69,20 @@ impl pallet_balances::Config for Test { type AccountStore = System; type Balance = u64; type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; + type Event = Event; type ExistentialDeposit = ExistentialDeposit; type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; type WeightInfo = (); - - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); - type FreezeIdentifier = (); - type MaxFreezes = (); } impl pallet_weights::Config for Test { - type RuntimeEvent = RuntimeEvent; + type Event = Event; type WeightInfo = (); } // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - let storage = as BuildStorage>::build_storage(&GenesisConfig::default()).unwrap(); - storage.into() + system::GenesisConfig::default().build_storage::().unwrap().into() } diff --git a/exercises/ex06-weights/weights/src/tests.rs b/exercises/ex06-weights/weights/src/tests.rs index d9e2720..6600a0e 100644 --- a/exercises/ex06-weights/weights/src/tests.rs +++ b/exercises/ex06-weights/weights/src/tests.rs @@ -1,14 +1,13 @@ use crate as pallet_weights; use crate::mock::*; -use frame_support::dispatch::GetDispatchInfo; -use frame_support::weights::RuntimeDbWeight; +use frame_support::weights::{GetDispatchInfo, RuntimeDbWeight}; #[test] fn verify_address_test() { new_test_ext().execute_with(|| { let db_weights: RuntimeDbWeight = ::DbWeight::get(); let weight = pallet_weights::Call::::verify_address {}.get_dispatch_info().weight; - assert_eq!(weight, db_weights.reads(1) + 10_000.into()); + assert_eq!(weight, 10_000 + db_weights.reads(1)); }); } @@ -26,8 +25,8 @@ fn duplicate_test() { .get_dispatch_info() .weight; - assert!(weight1.all_lt(weight2)); - assert!(weight1.all_gt(db_weights.writes(1))); + assert!(weight1 < weight2); + assert!(weight1 > db_weights.writes(1)); }); } @@ -47,8 +46,8 @@ fn store_maybe_hashed_test() { .get_dispatch_info() .weight; - assert_eq!(weight1, 100_000.into()); - assert_eq!(weight2, 10_000.into()); + assert_eq!(weight1, 100_000); + assert_eq!(weight2, 10_000); }); } @@ -69,6 +68,6 @@ fn benchmarked_store_maybe_hashed_test() { .get_dispatch_info() .weight; - assert!(weight1.all_gt(weight2)); + assert!(weight1 > weight2); }); } diff --git a/exercises/ex07-imbalances/imbalances/Cargo.toml b/exercises/ex07-imbalances/imbalances/Cargo.toml index 8f8524e..596f1d0 100644 --- a/exercises/ex07-imbalances/imbalances/Cargo.toml +++ b/exercises/ex07-imbalances/imbalances/Cargo.toml @@ -14,15 +14,16 @@ scale-info = { version = "2.0.1", default-features = false, features = [ "derive", ] } -frame-support = "38.0.0" -frame-system = "38.0.0" -sp-std = "14.0.0" +frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } + [dev-dependencies] -pallet-balances = "39.0.0" -sp-io = "38.0.0" -sp-core = "34.0.0" -sp-runtime = "39.0.2" +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.28" } +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } [features] default = ["std"] diff --git a/exercises/ex07-imbalances/imbalances/src/lib.rs b/exercises/ex07-imbalances/imbalances/src/lib.rs index d8df236..f0aee1e 100644 --- a/exercises/ex07-imbalances/imbalances/src/lib.rs +++ b/exercises/ex07-imbalances/imbalances/src/lib.rs @@ -28,11 +28,9 @@ pub mod pallet { }; use frame_system::pallet_prelude::*; - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); - #[pallet::config] pub trait Config: frame_system::Config + scale_info::TypeInfo { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; + type Event: From> + IsType<::Event>; type Currency: Currency; #[pallet::constant] @@ -42,7 +40,7 @@ pub mod pallet { } #[pallet::pallet] - #[pallet::storage_version(STORAGE_VERSION)] + #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(_); #[pallet::event] diff --git a/exercises/ex07-imbalances/imbalances/src/tests/mint.rs b/exercises/ex07-imbalances/imbalances/src/tests/mint.rs index 96f3525..02cfea1 100644 --- a/exercises/ex07-imbalances/imbalances/src/tests/mint.rs +++ b/exercises/ex07-imbalances/imbalances/src/tests/mint.rs @@ -9,7 +9,7 @@ fn ok() { let amount_to_mint = 500; - Imbalances::mint_to(RuntimeOrigin::root(), amount_to_mint, ALICE).unwrap(); + Imbalances::mint_to(Origin::root(), amount_to_mint, ALICE).unwrap(); assert_eq!(Balances::total_issuance(), total_issuance + amount_to_mint); assert_eq!( @@ -22,7 +22,7 @@ fn ok() { #[test] fn must_be_signed() { ExtBuilder::default().balances(vec![(ALICE, 100)]).build().execute_with(|| { - assert_noop!(Imbalances::mint_to(RuntimeOrigin::none(), 500, ALICE), BadOrigin); + assert_noop!(Imbalances::mint_to(Origin::none(), 500, ALICE), BadOrigin); }) } @@ -30,7 +30,7 @@ fn must_be_signed() { fn must_be_root() { ExtBuilder::default().balances(vec![(ALICE, 100)]).build().execute_with(|| { assert_noop!( - Imbalances::mint_to(RuntimeOrigin::signed(ALICE), 500, ALICE), + Imbalances::mint_to(Origin::signed(ALICE), 500, ALICE), BadOrigin ); }) @@ -40,7 +40,7 @@ fn must_be_root() { fn recipent_must_exist() { ExtBuilder::default().build().execute_with(|| { assert_noop!( - Imbalances::mint_to(RuntimeOrigin::root(), 500, ALICE), + Imbalances::mint_to(Origin::root(), 500, ALICE), Error::::AccountDoesNotExist ); }) diff --git a/exercises/ex07-imbalances/imbalances/src/tests/mock.rs b/exercises/ex07-imbalances/imbalances/src/tests/mock.rs index d35a2f6..a187dce 100644 --- a/exercises/ex07-imbalances/imbalances/src/tests/mock.rs +++ b/exercises/ex07-imbalances/imbalances/src/tests/mock.rs @@ -1,17 +1,21 @@ use crate as pallet_imbalance; use frame_support::parameter_types; -use frame_system::GenesisConfig; use sp_core::H256; use sp_runtime::{ - traits::{BlakeTwo256, IdentityLookup}, - BuildStorage, + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, }; +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 TestRuntime { + pub enum TestRuntime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { System: frame_system, Balances: pallet_balances, @@ -30,31 +34,25 @@ impl frame_system::Config for TestRuntime { type BaseCallFilter = frame_support::traits::Everything; type BlockHashCount = BlockHashCount; type BlockLength = (); + type BlockNumber = u64; type BlockWeights = (); + type Call = Call; type DbWeight = (); + type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; + type Header = Header; + type Index = u64; type Lookup = IdentityLookup; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); + type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = SS58Prefix; type SystemWeightInfo = (); type Version = (); - - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type RuntimeTask = (); - type Nonce = u64; - type Block = Block; - type SingleBlockMigrations = (); - type MultiBlockMigrator = (); - type PreInherents = (); - type PostInherents = (); - type PostTransactions = (); } pub const EXISTENTIAL_DEPOSIT: u128 = 10; @@ -69,17 +67,12 @@ impl pallet_balances::Config for TestRuntime { type AccountStore = System; type Balance = u128; type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; + type Event = Event; type ExistentialDeposit = ExistentialDeposit; type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; type WeightInfo = (); - - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); - type FreezeIdentifier = (); - type MaxFreezes = (); } pub const TREASURY_FLAT_CUT: u128 = 50; @@ -91,7 +84,7 @@ parameter_types! { impl pallet_imbalance::Config for TestRuntime { type Currency = Balances; - type RuntimeEvent = RuntimeEvent; + type Event = Event; type TreasuryAccount = TreasuryAccount; type TreasuryFlatCut = TreasuryFlatCut; } @@ -116,15 +109,15 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { - let mut storage = as BuildStorage>::build_storage(&GenesisConfig::default()).unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); pallet_balances::GenesisConfig:: { balances: self.caps_endowed_accounts, } - .assimilate_storage(&mut storage) + .assimilate_storage(&mut t) .unwrap(); - let mut ext = sp_io::TestExternalities::new(storage); + let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext } diff --git a/exercises/ex07-imbalances/imbalances/src/tests/sack.rs b/exercises/ex07-imbalances/imbalances/src/tests/sack.rs index 91b76bf..178923d 100644 --- a/exercises/ex07-imbalances/imbalances/src/tests/sack.rs +++ b/exercises/ex07-imbalances/imbalances/src/tests/sack.rs @@ -12,7 +12,7 @@ fn ok() { let bob_balance = Balances::free_balance(BOB); let charly_balance = Balances::free_balance(CHARLY); - Imbalances::sack(RuntimeOrigin::root(), vec![ALICE, BOB], CHARLY).unwrap(); + Imbalances::sack(Origin::root(), vec![ALICE, BOB], CHARLY).unwrap(); assert_eq!(Balances::total_issuance(), total_issuance); assert_eq!(Balances::free_balance(ALICE), EXISTENTIAL_DEPOSIT); @@ -30,7 +30,7 @@ fn ok() { #[test] fn must_be_signed() { ExtBuilder::default().balances(vec![]).build().execute_with(|| { - assert_noop!(Imbalances::sack(RuntimeOrigin::none(), vec![], ALICE), BadOrigin); + assert_noop!(Imbalances::sack(Origin::none(), vec![], ALICE), BadOrigin); }) } @@ -38,7 +38,7 @@ fn must_be_signed() { fn must_be_root() { ExtBuilder::default().balances(vec![]).build().execute_with(|| { assert_noop!( - Imbalances::sack(RuntimeOrigin::signed(ALICE), vec![], ALICE), + Imbalances::sack(Origin::signed(ALICE), vec![], ALICE), BadOrigin ); }) @@ -51,7 +51,7 @@ fn recipient_must_exist() { .build() .execute_with(|| { assert_noop!( - Imbalances::sack(RuntimeOrigin::root(), vec![ALICE, BOB], CHARLY), + Imbalances::sack(Origin::root(), vec![ALICE, BOB], CHARLY), Error::::AccountDoesNotExist ); }) diff --git a/exercises/ex07-imbalances/imbalances/src/tests/slash.rs b/exercises/ex07-imbalances/imbalances/src/tests/slash.rs index 89976c9..d3dcb45 100644 --- a/exercises/ex07-imbalances/imbalances/src/tests/slash.rs +++ b/exercises/ex07-imbalances/imbalances/src/tests/slash.rs @@ -9,7 +9,7 @@ fn ok() { let amount_to_slash = 500; - Imbalances::slash(RuntimeOrigin::root(), amount_to_slash, ALICE).unwrap(); + Imbalances::slash(Origin::root(), amount_to_slash, ALICE).unwrap(); let treasury_part = amount_to_slash / 3; let burned_part = amount_to_slash - treasury_part; @@ -31,7 +31,7 @@ fn ok_not_enough_funds() { let amount_to_slash = 5000; - Imbalances::slash(RuntimeOrigin::root(), amount_to_slash, ALICE).unwrap(); + Imbalances::slash(Origin::root(), amount_to_slash, ALICE).unwrap(); let treasury_part = alice_balance / 3; let burned_part = alice_balance - treasury_part; @@ -45,7 +45,7 @@ fn ok_not_enough_funds() { #[test] fn must_be_signed() { ExtBuilder::default().balances(vec![(ALICE, 100)]).build().execute_with(|| { - assert_noop!(Imbalances::slash(RuntimeOrigin::none(), 500, ALICE), BadOrigin); + assert_noop!(Imbalances::slash(Origin::none(), 500, ALICE), BadOrigin); }) } @@ -53,7 +53,7 @@ fn must_be_signed() { fn must_be_root() { ExtBuilder::default().balances(vec![(ALICE, 100)]).build().execute_with(|| { assert_noop!( - Imbalances::slash(RuntimeOrigin::signed(ALICE), 500, ALICE), + Imbalances::slash(Origin::signed(ALICE), 500, ALICE), BadOrigin ); }) diff --git a/exercises/ex08-genesis-config/nft-with-genesis-config/Cargo.toml b/exercises/ex08-genesis-config/nft-with-genesis-config/Cargo.toml index 5fc8fc7..c6b01b9 100644 --- a/exercises/ex08-genesis-config/nft-with-genesis-config/Cargo.toml +++ b/exercises/ex08-genesis-config/nft-with-genesis-config/Cargo.toml @@ -13,14 +13,15 @@ scale-info = { version = "2.0.1", default-features = false, features = [ "derive", ] } -frame-support = "38.0.0" -frame-system = "38.0.0" -sp-std = "14.0.0" -sp-core = "34.0.0" +frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } + [dev-dependencies] -sp-io = "38.0.0" -sp-runtime = "39.0.2" +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } [features] default = ["std"] diff --git a/exercises/ex08-genesis-config/nft-with-genesis-config/src/lib.rs b/exercises/ex08-genesis-config/nft-with-genesis-config/src/lib.rs index 0df1690..883bbd4 100644 --- a/exercises/ex08-genesis-config/nft-with-genesis-config/src/lib.rs +++ b/exercises/ex08-genesis-config/nft-with-genesis-config/src/lib.rs @@ -10,7 +10,6 @@ mod tests; pub mod types; use frame_support::{ensure, BoundedVec}; -use frame_support::traits::GenesisBuild; use types::*; type GenesisAssetList = Vec<( @@ -26,11 +25,9 @@ pub mod pallet { use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); - #[pallet::config] pub trait Config: frame_system::Config + scale_info::TypeInfo { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; + type Event: From> + IsType<::Event>; #[pallet::constant] type MaxLength: Get; @@ -60,7 +57,7 @@ pub mod pallet { } #[pallet::pallet] - #[pallet::storage_version(STORAGE_VERSION)] + #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(_); #[pallet::storage] diff --git a/exercises/ex08-genesis-config/nft-with-genesis-config/src/tests/mock.rs b/exercises/ex08-genesis-config/nft-with-genesis-config/src/tests/mock.rs index 23fc84d..d11343c 100644 --- a/exercises/ex08-genesis-config/nft-with-genesis-config/src/tests/mock.rs +++ b/exercises/ex08-genesis-config/nft-with-genesis-config/src/tests/mock.rs @@ -1,16 +1,22 @@ -use crate::{self as pallet_nft, GenesisConfig}; +use crate as pallet_nft; use frame_support::{parameter_types, traits::GenesisBuild}; use sp_core::H256; use sp_runtime::{ - traits::{BlakeTwo256, IdentityLookup}, BuildStorage, + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, }; +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 TestRuntime { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + pub enum TestRuntime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event}, NFTs: pallet_nft::{Pallet, Call, Storage, Event}, } ); @@ -26,31 +32,25 @@ impl frame_system::Config for TestRuntime { type BaseCallFilter = frame_support::traits::Everything; type BlockHashCount = BlockHashCount; type BlockLength = (); + type BlockNumber = u64; type BlockWeights = (); + type Call = Call; type DbWeight = (); + type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; + type Header = Header; + type Index = u64; type Lookup = IdentityLookup; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); + type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = SS58Prefix; type SystemWeightInfo = (); type Version = (); - - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type RuntimeTask = (); - type Nonce = u64; - type Block = Block; - type SingleBlockMigrations = (); - type MultiBlockMigrator = (); - type PreInherents = (); - type PostInherents = (); - type PostTransactions = (); } parameter_types! { @@ -58,13 +58,13 @@ parameter_types! { } impl pallet_nft::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; + type Event = Event; type MaxLength = MaxLength; } pub fn new_test_ext() -> sp_io::TestExternalities { - let storage = as BuildStorage>::build_storage(&GenesisConfig::default()).unwrap(); - let mut ext = sp_io::TestExternalities::new(storage); + let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut ext = sp_io::TestExternalities::new(t); // In order to emit events the block number must be more than 0 ext.execute_with(|| System::set_block_number(1)); ext @@ -73,11 +73,11 @@ pub fn new_test_ext() -> sp_io::TestExternalities { pub fn new_test_ext_with_genesis_config( genesis_config: pallet_nft::GenesisConfig, ) -> sp_io::TestExternalities { - let mut storage = as GenesisBuild>::build_storage(&genesis_config).unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - BuildStorage::assimilate_storage(&genesis_config, &mut storage).unwrap(); + genesis_config.assimilate_storage(&mut t).unwrap(); - let mut ext = sp_io::TestExternalities::new(storage); + let mut ext = sp_io::TestExternalities::new(t); // In order to emit events the block number must be more than 0 ext.execute_with(|| System::set_block_number(1)); ext diff --git a/exercises/ex08-genesis-config/nft-with-genesis-config/src/tests/unique_assets.rs b/exercises/ex08-genesis-config/nft-with-genesis-config/src/tests/unique_assets.rs index 4196bc5..9f9dd02 100644 --- a/exercises/ex08-genesis-config/nft-with-genesis-config/src/tests/unique_assets.rs +++ b/exercises/ex08-genesis-config/nft-with-genesis-config/src/tests/unique_assets.rs @@ -1,7 +1,7 @@ use crate::{tests::mock::*, Error}; use frame_support::{assert_noop, assert_ok, error::BadOrigin, BoundedVec}; -fn last_event() -> RuntimeEvent { +fn last_event() -> Event { frame_system::Pallet::::events() .pop() .expect("Event expected") @@ -16,7 +16,7 @@ mod mint { new_test_ext().execute_with(|| { let metadata: BoundedVec::MaxLength> = "Some metadata".as_bytes().to_vec().try_into().unwrap(); - assert_ok!(NFTs::mint(RuntimeOrigin::signed(ALICE), metadata.clone(), 5)); + assert_ok!(NFTs::mint(Origin::signed(ALICE), metadata.clone(), 5)); assert_eq!(NFTs::nonce(), 1); @@ -27,7 +27,7 @@ mod mint { assert_eq!(NFTs::account(0, ALICE), 5); assert_eq!( last_event(), - RuntimeEvent::NFTs(crate::Event::Created { + Event::NFTs(crate::Event::Created { creator: ALICE, asset_id: 0 }) @@ -40,7 +40,7 @@ mod mint { new_test_ext().execute_with(|| { assert_noop!( NFTs::mint( - RuntimeOrigin::none(), + Origin::none(), "Some metadata".as_bytes().to_vec().try_into().unwrap(), 5 ), @@ -54,7 +54,7 @@ mod mint { new_test_ext().execute_with(|| { assert_noop!( NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), 0 ), @@ -73,12 +73,12 @@ mod transfer { let minted_amount = 5; let transfered_amount = 2; assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), minted_amount )); assert_ok!(NFTs::transfer( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 0, transfered_amount, BOB @@ -89,7 +89,7 @@ mod transfer { assert_eq!( last_event(), - RuntimeEvent::NFTs(crate::Event::Transferred { + Event::NFTs(crate::Event::Transferred { asset_id: 0, from: ALICE, to: BOB, @@ -105,12 +105,12 @@ mod transfer { let minted_amount = 5; let transfered_amount = 10; assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), minted_amount )); assert_ok!(NFTs::transfer( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), 0, transfered_amount, BOB @@ -121,7 +121,7 @@ mod transfer { assert_eq!( last_event(), - RuntimeEvent::NFTs(crate::Event::Transferred { + Event::NFTs(crate::Event::Transferred { asset_id: 0, from: ALICE, to: BOB, @@ -136,7 +136,7 @@ mod transfer { new_test_ext().execute_with(|| { assert_noop!( NFTs::mint( - RuntimeOrigin::none(), + Origin::none(), "Some metadata".as_bytes().to_vec().try_into().unwrap(), 5 ), @@ -149,7 +149,7 @@ mod transfer { fn must_exist() { new_test_ext().execute_with(|| { assert_noop!( - NFTs::transfer(RuntimeOrigin::signed(ALICE), 0, 100, BOB), + NFTs::transfer(Origin::signed(ALICE), 0, 100, BOB), Error::::UnknownAssetId ); }) @@ -159,12 +159,12 @@ mod transfer { fn must_own_some() { new_test_ext().execute_with(|| { assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), 5 )); assert_noop!( - NFTs::transfer(RuntimeOrigin::signed(BOB), 0, 2, ALICE), + NFTs::transfer(Origin::signed(BOB), 0, 2, ALICE), Error::::NotOwned ); }) @@ -180,11 +180,11 @@ mod burn { let minted_amount = 5; let burned_amount = 2; assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), minted_amount )); - assert_ok!(NFTs::burn(RuntimeOrigin::signed(ALICE), 0, burned_amount)); + assert_ok!(NFTs::burn(Origin::signed(ALICE), 0, burned_amount)); assert_eq!( NFTs::unique_asset(0).unwrap().supply, @@ -194,7 +194,7 @@ mod burn { assert_eq!( last_event(), - RuntimeEvent::NFTs(crate::Event::Burned { + Event::NFTs(crate::Event::Burned { asset_id: 0, owner: ALICE, total_supply: minted_amount - burned_amount @@ -209,19 +209,19 @@ mod burn { let minted_amount = 5; let burned_amount = 10; assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), minted_amount )); - assert_ok!(NFTs::burn(RuntimeOrigin::signed(ALICE), 0, burned_amount)); + assert_ok!(NFTs::burn(Origin::signed(ALICE), 0, burned_amount)); assert_eq!(NFTs::unique_asset(0).unwrap().supply, 0); assert_eq!(NFTs::account(0, ALICE), 0); assert_eq!( last_event(), - RuntimeEvent::NFTs(crate::Event::Burned { + Event::NFTs(crate::Event::Burned { asset_id: 0, owner: ALICE, total_supply: 0 @@ -233,7 +233,7 @@ mod burn { #[test] fn must_be_signed() { new_test_ext().execute_with(|| { - assert_noop!(NFTs::burn(RuntimeOrigin::none(), 0, 5), BadOrigin); + assert_noop!(NFTs::burn(Origin::none(), 0, 5), BadOrigin); }) } @@ -241,7 +241,7 @@ mod burn { fn must_exist() { new_test_ext().execute_with(|| { assert_noop!( - NFTs::burn(RuntimeOrigin::signed(ALICE), 0, 100), + NFTs::burn(Origin::signed(ALICE), 0, 100), Error::::UnknownAssetId ); }) @@ -251,12 +251,12 @@ mod burn { fn must_own_some() { new_test_ext().execute_with(|| { assert_ok!(NFTs::mint( - RuntimeOrigin::signed(ALICE), + Origin::signed(ALICE), "Some metadata".as_bytes().to_vec().try_into().unwrap(), 5 )); assert_noop!( - NFTs::burn(RuntimeOrigin::signed(BOB), 0, 2), + NFTs::burn(Origin::signed(BOB), 0, 2), Error::::NotOwned ); }) diff --git a/exercises/ex08-genesis-config/nft-with-genesis-config/src/types.rs b/exercises/ex08-genesis-config/nft-with-genesis-config/src/types.rs index 4bfe83e..031b17f 100644 --- a/exercises/ex08-genesis-config/nft-with-genesis-config/src/types.rs +++ b/exercises/ex08-genesis-config/nft-with-genesis-config/src/types.rs @@ -3,9 +3,9 @@ use codec::{Decode, Encode}; use frame_support::{ pallet_prelude::{BoundedVec, MaxEncodedLen}, traits::Get, + RuntimeDebug, }; use scale_info::TypeInfo; -use sp_core::RuntimeDebug; pub type UniqueAssetId = u128; diff --git a/exercises/ex09-mock/pallet-to-mock/Cargo.toml b/exercises/ex09-mock/pallet-to-mock/Cargo.toml index ed768ac..1f24187 100644 --- a/exercises/ex09-mock/pallet-to-mock/Cargo.toml +++ b/exercises/ex09-mock/pallet-to-mock/Cargo.toml @@ -13,16 +13,17 @@ scale-info = { version = "2.0.1", default-features = false, features = [ "derive", ] } -frame-support = "38.0.0" -frame-system = "38.0.0" -pallet-balances = "39.0.0" -sp-std = "14.0.0" +frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } + [dev-dependencies] -#frame-support-test = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } -sp-io = "38.0.0" -sp-core = "34.0.0" -sp-runtime = "39.0.2" +frame-support-test = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } [features] default = ["std"] diff --git a/exercises/ex09-mock/pallet-to-mock/src/lib.rs b/exercises/ex09-mock/pallet-to-mock/src/lib.rs index 04756f0..2904ffd 100644 --- a/exercises/ex09-mock/pallet-to-mock/src/lib.rs +++ b/exercises/ex09-mock/pallet-to-mock/src/lib.rs @@ -21,11 +21,9 @@ pub mod pallet { use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); - #[pallet::config] pub trait Config: frame_system::Config { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; + type Event: From> + IsType<::Event>; type Currency: Currency; @@ -36,7 +34,7 @@ pub mod pallet { } #[pallet::pallet] - #[pallet::storage_version(STORAGE_VERSION)] + #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(_); #[pallet::event] diff --git a/exercises/ex10-offchain-worker/pallet-price-oracle/Cargo.toml b/exercises/ex10-offchain-worker/pallet-price-oracle/Cargo.toml index 6685ace..b565a8d 100644 --- a/exercises/ex10-offchain-worker/pallet-price-oracle/Cargo.toml +++ b/exercises/ex10-offchain-worker/pallet-price-oracle/Cargo.toml @@ -10,28 +10,26 @@ version = "0.1.0" codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ "derive", ] } +frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } scale-info = { version = "2.0.1", default-features = false, features = [ "derive", ] } - -frame-support = "38.0.0" -frame-system = "38.0.0" - -serde = { version = "1.0.214", default-features = false, features = [ +serde = { version = "1.0.160", default-features = false, features = [ "alloc", "derive", ] } -serde_json = { version = "1.0.132", default-features = false, features = [ +serde_json = { version = "1.0.96", default-features = false, features = [ "alloc", ] } -sp-arithmetic = "26.0.0" -sp-std = "14.0.0" +sp-arithmetic = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } [dev-dependencies] -sp-io = "38.0.0" -sp-core = "34.0.0" -sp-runtime = "39.0.2" -sp-keystore = "0.40.0" +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-keystore = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } [features] default = ["std"] diff --git a/exercises/ex10-offchain-worker/pallet-price-oracle/src/lib.rs b/exercises/ex10-offchain-worker/pallet-price-oracle/src/lib.rs index 2eecea3..63a8d9a 100644 --- a/exercises/ex10-offchain-worker/pallet-price-oracle/src/lib.rs +++ b/exercises/ex10-offchain-worker/pallet-price-oracle/src/lib.rs @@ -6,6 +6,7 @@ mod offchain_worker; pub use pallet::*; +use frame_support::log; use sp_std::vec::Vec; extern crate alloc; @@ -25,11 +26,12 @@ pub mod pallet { pub trait Config: frame_system::Config + frame_system::offchain::SendTransactionTypes> { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; - type RuntimeCall: IsType<::RuntimeCall> + From>; + type Event: From> + IsType<::Event>; + type Call: From>; } #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(_); #[pallet::storage] @@ -54,7 +56,6 @@ pub mod pallet { #[pallet::call] impl Pallet { - #[pallet::call_index(0)] #[pallet::weight(0)] pub fn set_btc_price(origin: OriginFor, btc_price: FixedI64) -> DispatchResult { // TODO: diff --git a/exercises/ex10-offchain-worker/pallet-price-oracle/src/tests/mock.rs b/exercises/ex10-offchain-worker/pallet-price-oracle/src/tests/mock.rs index 00e4c5a..a3c8045 100644 --- a/exercises/ex10-offchain-worker/pallet-price-oracle/src/tests/mock.rs +++ b/exercises/ex10-offchain-worker/pallet-price-oracle/src/tests/mock.rs @@ -8,14 +8,17 @@ use sp_runtime::{ type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; -pub type Extrinsic = TestXt; +pub type Extrinsic = TestXt; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum TestRuntime + pub enum TestRuntime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system, - PriceOracle: pallet_price_oracle, + System: frame_system::{Pallet, Call, Config, Storage, Event}, + PriceOracle: pallet_price_oracle::{Pallet, Call, Storage, Event}, } ); @@ -30,26 +33,21 @@ impl frame_system::Config for TestRuntime { type BaseCallFilter = frame_support::traits::Everything; type BlockHashCount = ConstU64<250>; type BlockLength = (); + type BlockNumber = u64; type BlockWeights = (); + type Call = Call; type DbWeight = (); - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type RuntimeTask = (); - type Nonce = u64; - type Block = Block; - type SingleBlockMigrations = (); - type MultiBlockMigrator = (); - type PreInherents = (); - type PostInherents = (); - type PostTransactions = (); + type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; + type Header = Header; + type Index = u64; type Lookup = IdentityLookup; type MaxConsumers = ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); + type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = (); type SystemWeightInfo = (); @@ -57,14 +55,14 @@ impl frame_system::Config for TestRuntime { } impl pallet_price_oracle::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; - type RuntimeCall = RuntimeCall; + type Call = Call; + type Event = Event; } impl frame_system::offchain::SendTransactionTypes for TestRuntime where - RuntimeCall: From, + Call: From, { type Extrinsic = Extrinsic; - type OverarchingCall = RuntimeCall; + type OverarchingCall = Call; } diff --git a/exercises/ex10-offchain-worker/pallet-price-oracle/src/tests/offchain_worker.rs b/exercises/ex10-offchain-worker/pallet-price-oracle/src/tests/offchain_worker.rs index c3d5e62..d81d524 100644 --- a/exercises/ex10-offchain-worker/pallet-price-oracle/src/tests/offchain_worker.rs +++ b/exercises/ex10-offchain-worker/pallet-price-oracle/src/tests/offchain_worker.rs @@ -8,7 +8,7 @@ use sp_core::offchain::{ use super::mock::*; use crate::offchain_worker::fetch_btc_price; -use super::mock::PriceOracle; +use super::mock::{Call, PriceOracle}; fn price_oracle_response(state: &mut OffchainState) { state.expect_request(PendingRequest { @@ -59,7 +59,7 @@ fn offchain_worker_submit_unsigned_transaction_ok() { assert_eq!( tx.call, - RuntimeCall::PriceOracle(crate::Call::set_btc_price { + Call::PriceOracle(crate::Call::set_btc_price { btc_price: FixedI64::from_float(29021.47) }) ); diff --git a/polkadot-sdk-solochain-template/.gitignore b/polkadot-sdk-solochain-template/.gitignore deleted file mode 100644 index 2f7896d..0000000 --- a/polkadot-sdk-solochain-template/.gitignore +++ /dev/null @@ -1 +0,0 @@ -target/ diff --git a/polkadot-sdk-solochain-template/Cargo.toml b/polkadot-sdk-solochain-template/Cargo.toml deleted file mode 100644 index 203202e..0000000 --- a/polkadot-sdk-solochain-template/Cargo.toml +++ /dev/null @@ -1,74 +0,0 @@ -[workspace.package] -license = "MIT-0" -authors = ["Parity Technologies "] -homepage = "https://paritytech.github.io/polkadot-sdk/" -repository = "https://github.com/paritytech/polkadot-sdk-solochain-template.git" -edition = "2021" - -[workspace] -members = [ - "node", - "pallets/template", - "runtime", -] -resolver = "2" - -[workspace.dependencies] -solochain-template-runtime = { path = "./runtime", default-features = false } -pallet-template = { path = "./pallets/template", default-features = false } -clap = { version = "4.5.3" } -frame-benchmarking-cli = { version = "42.0.0", default-features = false } -frame-system = { version = "37.0.0", default-features = false } -futures = { version = "0.3.30" } -jsonrpsee = { version = "0.23.2" } -pallet-transaction-payment = { version = "37.0.0", default-features = false } -pallet-transaction-payment-rpc = { version = "40.0.0", default-features = false } -sc-basic-authorship = { version = "0.44.0", default-features = false } -sc-cli = { version = "0.46.0", default-features = false } -sc-client-api = { version = "37.0.0", default-features = false } -sc-consensus = { version = "0.43.0", default-features = false } -sc-consensus-aura = { version = "0.44.0", default-features = false } -sc-consensus-grandpa = { version = "0.29.0", default-features = false } -sc-executor = { version = "0.40.0", default-features = false } -sc-network = { version = "0.44.0", default-features = false } -sc-offchain = { version = "39.0.0", default-features = false } -sc-rpc-api = { version = "0.43.0", default-features = false } -sc-service = { version = "0.45.0", default-features = false } -sc-telemetry = { version = "24.0.0", default-features = false } -sc-transaction-pool = { version = "37.0.0", default-features = false } -sc-transaction-pool-api = { version = "37.0.0", default-features = false } -serde_json = { version = "1.0.114", default-features = false } -sp-api = { version = "34.0.0", default-features = false } -sp-block-builder = { version = "34.0.0", default-features = false } -sp-blockchain = { version = "37.0.0", default-features = false } -sp-consensus-aura = { version = "0.40.0", default-features = false } -sp-consensus-grandpa = { version = "21.0.0", default-features = false } -sp-core = { version = "34.0.0", default-features = false } -sp-inherents = { version = "34.0.0", default-features = false } -sp-io = { version = "38.0.0", default-features = false } -sp-keyring = { version = "39.0.0", default-features = false } -sp-runtime = { version = "39.0.0", default-features = false } -sp-timestamp = { version = "34.0.0", default-features = false } -substrate-frame-rpc-system = { version = "38.0.0", default-features = false } -substrate-build-script-utils = { version = "11.0.0", default-features = false } -codec = { version = "3.6.12", default-features = false, package = "parity-scale-codec" } -frame-benchmarking = { version = "37.0.0", default-features = false } -frame-executive = { version = "37.0.0", default-features = false } -frame-support = { version = "37.0.0", default-features = false } -frame-system-benchmarking = { version = "37.0.0", default-features = false } -frame-system-rpc-runtime-api = { version = "34.0.0", default-features = false } -frame-try-runtime = { version = "0.43.0", default-features = false } -pallet-aura = { version = "36.0.0", default-features = false } -pallet-balances = { version = "38.0.0", default-features = false } -pallet-grandpa = { version = "37.0.0", default-features = false } -pallet-sudo = { version = "37.0.0", default-features = false } -pallet-timestamp = { version = "36.0.0", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { version = "37.0.0", default-features = false } -scale-info = { version = "2.11.1", default-features = false } -sp-genesis-builder = { version = "0.15.0", default-features = false } -sp-offchain = { version = "34.0.0", default-features = false } -sp-session = { version = "35.0.0", default-features = false } -sp-storage = { version = "21.0.0", default-features = false } -sp-transaction-pool = { version = "34.0.0", default-features = false } -sp-version = { version = "37.0.0", default-features = false } -substrate-wasm-builder = { version = "24.0.0", default-features = false } diff --git a/polkadot-sdk-solochain-template/Dockerfile b/polkadot-sdk-solochain-template/Dockerfile deleted file mode 100644 index 97e6dd2..0000000 --- a/polkadot-sdk-solochain-template/Dockerfile +++ /dev/null @@ -1,28 +0,0 @@ -FROM docker.io/paritytech/ci-unified:latest as builder - -WORKDIR /polkadot -COPY . /polkadot - -RUN cargo fetch -RUN cargo build --locked --release - -FROM docker.io/parity/base-bin:latest - -COPY --from=builder /polkadot/target/release/solochain-template-node /usr/local/bin - -USER root -RUN useradd -m -u 1001 -U -s /bin/sh -d /polkadot polkadot && \ - mkdir -p /data /polkadot/.local/share && \ - chown -R polkadot:polkadot /data && \ - ln -s /data /polkadot/.local/share/polkadot && \ -# unclutter and minimize the attack surface - rm -rf /usr/bin /usr/sbin && \ -# check if executable works in this container - /usr/local/bin/solochain-template-node --version - -USER polkadot - -EXPOSE 30333 9933 9944 9615 -VOLUME ["/data"] - -ENTRYPOINT ["/usr/local/bin/solochain-template-node"] diff --git a/polkadot-sdk-solochain-template/LICENSE b/polkadot-sdk-solochain-template/LICENSE deleted file mode 100644 index cf1ab25..0000000 --- a/polkadot-sdk-solochain-template/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. - -For more information, please refer to diff --git a/polkadot-sdk-solochain-template/README.md b/polkadot-sdk-solochain-template/README.md deleted file mode 100644 index c5dc5db..0000000 --- a/polkadot-sdk-solochain-template/README.md +++ /dev/null @@ -1,224 +0,0 @@ -# Substrate Node Template - -A fresh [Substrate](https://substrate.io/) node, ready for hacking :rocket: - -A standalone version of this template is available for each release of Polkadot -in the [Substrate Developer Hub Parachain -Template](https://github.com/substrate-developer-hub/substrate-node-template/) -repository. The parachain template is generated directly at each Polkadot -release branch from the [Solochain Template in -Substrate](https://github.com/paritytech/polkadot-sdk/tree/master/templates/solochain) -upstream - -It is usually best to use the stand-alone version to start a new project. All -bugs, suggestions, and feature requests should be made upstream in the -[Substrate](https://github.com/paritytech/polkadot-sdk/tree/master/substrate) -repository. - -## Getting Started - -Depending on your operating system and Rust version, there might be additional -packages required to compile this template. Check the -[Install](https://docs.substrate.io/install/) instructions for your platform for -the most common dependencies. Alternatively, you can use one of the [alternative -installation](#alternatives-installations) options. - -### Build - -Use the following command to build the node without launching it: - -```sh -cargo build --package solochain-template-node --release -``` - -### Embedded Docs - -After you build the project, you can use the following command to explore its -parameters and subcommands: - -```sh -./target/release/solochain-template-node -h -``` - -You can generate and view the [Rust -Docs](https://doc.rust-lang.org/cargo/commands/cargo-doc.html) for this template -with this command: - -```sh -cargo +nightly doc --open -``` - -### Single-Node Development Chain - -The following command starts a single-node development chain that doesn't -persist state: - -```sh -./target/release/solochain-template-node --dev -``` - -To purge the development chain's state, run the following command: - -```sh -./target/release/solochain-template-node purge-chain --dev -``` - -To start the development chain with detailed logging, run the following command: - -```sh -RUST_BACKTRACE=1 ./target/release/solochain-template-node -ldebug --dev -``` - -Development chains: - -- Maintain state in a `tmp` folder while the node is running. -- Use the **Alice** and **Bob** accounts as default validator authorities. -- Use the **Alice** account as the default `sudo` account. -- Are preconfigured with a genesis state (`/node/src/chain_spec.rs`) that - includes several pre-funded development accounts. - - -To persist chain state between runs, specify a base path by running a command -similar to the following: - -```sh -// Create a folder to use as the db base path -$ mkdir my-chain-state - -// Use of that folder to store the chain state -$ ./target/release/solochain-template-node --dev --base-path ./my-chain-state/ - -// Check the folder structure created inside the base path after running the chain -$ ls ./my-chain-state -chains -$ ls ./my-chain-state/chains/ -dev -$ ls ./my-chain-state/chains/dev -db keystore network -``` - -### Connect with Polkadot-JS Apps Front-End - -After you start the node template locally, you can interact with it using the -hosted version of the [Polkadot/Substrate -Portal](https://polkadot.js.org/apps/#/explorer?rpc=ws://localhost:9944) -front-end by connecting to the local node endpoint. A hosted version is also -available on [IPFS](https://dotapps.io/). You can -also find the source code and instructions for hosting your own instance in the -[`polkadot-js/apps`](https://github.com/polkadot-js/apps) repository. - -### Multi-Node Local Testnet - -If you want to see the multi-node consensus algorithm in action, see [Simulate a -network](https://docs.substrate.io/tutorials/build-a-blockchain/simulate-network/). - -## Template Structure - -A Substrate project such as this consists of a number of components that are -spread across a few directories. - -### Node - -A blockchain node is an application that allows users to participate in a -blockchain network. Substrate-based blockchain nodes expose a number of -capabilities: - -- Networking: Substrate nodes use the [`libp2p`](https://libp2p.io/) networking - stack to allow the nodes in the network to communicate with one another. -- Consensus: Blockchains must have a way to come to - [consensus](https://docs.substrate.io/fundamentals/consensus/) on the state of - the network. Substrate makes it possible to supply custom consensus engines - and also ships with several consensus mechanisms that have been built on top - of [Web3 Foundation - research](https://research.web3.foundation/Polkadot/protocols/NPoS). -- RPC Server: A remote procedure call (RPC) server is used to interact with - Substrate nodes. - -There are several files in the `node` directory. Take special note of the -following: - -- [`chain_spec.rs`](./node/src/chain_spec.rs): A [chain - specification](https://docs.substrate.io/build/chain-spec/) is a source code - file that defines a Substrate chain's initial (genesis) state. Chain - specifications are useful for development and testing, and critical when - architecting the launch of a production chain. Take note of the - `development_config` and `testnet_genesis` functions. These functions are - used to define the genesis state for the local development chain - configuration. These functions identify some [well-known - accounts](https://docs.substrate.io/reference/command-line-tools/subkey/) and - use them to configure the blockchain's initial state. -- [`service.rs`](./node/src/service.rs): This file defines the node - implementation. Take note of the libraries that this file imports and the - names of the functions it invokes. In particular, there are references to - consensus-related topics, such as the [block finalization and - forks](https://docs.substrate.io/fundamentals/consensus/#finalization-and-forks) - and other [consensus - mechanisms](https://docs.substrate.io/fundamentals/consensus/#default-consensus-models) - such as Aura for block authoring and GRANDPA for finality. - - -### Runtime - -In Substrate, the terms "runtime" and "state transition function" are analogous. -Both terms refer to the core logic of the blockchain that is responsible for -validating blocks and executing the state changes they define. The Substrate -project in this repository uses -[FRAME](https://docs.substrate.io/learn/runtime-development/#frame) to construct -a blockchain runtime. FRAME allows runtime developers to declare domain-specific -logic in modules called "pallets". At the heart of FRAME is a helpful [macro -language](https://docs.substrate.io/reference/frame-macros/) that makes it easy -to create pallets and flexibly compose them to create blockchains that can -address [a variety of needs](https://substrate.io/ecosystem/projects/). - -Review the [FRAME runtime implementation](./runtime/src/lib.rs) included in this -template and note the following: - -- This file configures several pallets to include in the runtime. Each pallet - configuration is defined by a code block that begins with `impl - $PALLET_NAME::Config for Runtime`. -- The pallets are composed into a single runtime by way of the - [`construct_runtime!`](https://paritytech.github.io/substrate/master/frame_support/macro.construct_runtime.html) - macro, which is part of the [core FRAME pallet - library](https://docs.substrate.io/reference/frame-pallets/#system-pallets). - -### Pallets - -The runtime in this project is constructed using many FRAME pallets that ship -with [the Substrate -repository](https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame) and a -template pallet that is [defined in the -`pallets`](./pallets/template/src/lib.rs) directory. - -A FRAME pallet is comprised of a number of blockchain primitives, including: - -- Storage: FRAME defines a rich set of powerful [storage - abstractions](https://docs.substrate.io/build/runtime-storage/) that makes it - easy to use Substrate's efficient key-value database to manage the evolving - state of a blockchain. -- Dispatchables: FRAME pallets define special types of functions that can be - invoked (dispatched) from outside of the runtime in order to update its state. -- Events: Substrate uses - [events](https://docs.substrate.io/build/events-and-errors/) to notify users - of significant state changes. -- Errors: When a dispatchable fails, it returns an error. - -Each pallet has its own `Config` trait which serves as a configuration interface -to generically define the types and parameters it depends on. - -## Alternatives Installations - -Instead of installing dependencies and building this source directly, consider -the following alternatives. - -### Nix - -Install [nix](https://nixos.org/) and -[nix-direnv](https://github.com/nix-community/nix-direnv) for a fully -plug-and-play experience for setting up the development environment. To get all -the correct dependencies, activate direnv `direnv allow`. - -### Docker - -Please follow the [Substrate Docker instructions -here](https://github.com/paritytech/polkadot-sdk/blob/master/substrate/docker/README.md) to -build the Docker container with the Substrate Node Template binary. diff --git a/polkadot-sdk-solochain-template/docs/rust-setup.md b/polkadot-sdk-solochain-template/docs/rust-setup.md deleted file mode 100644 index 00089ab..0000000 --- a/polkadot-sdk-solochain-template/docs/rust-setup.md +++ /dev/null @@ -1,218 +0,0 @@ -# Installation - -This guide is for reference only, please check the latest information on getting started with Substrate [here](https://docs.substrate.io/main-docs/install/). - -This page will guide you through the **2 steps** needed to prepare a computer for **Substrate** development. Since -Substrate is built with [the Rust programming language](https://www.rust-lang.org/), the first thing you will need to do -is prepare the computer for Rust development - these steps will vary based on the computer's operating system. Once Rust -is configured, you will use its toolchains to interact with Rust projects; the commands for Rust's toolchains will be -the same for all supported, Unix-based operating systems. - -## Build dependencies - -Substrate development is easiest on Unix-based operating systems like macOS or Linux. The examples in the [Substrate -Docs](https://docs.substrate.io) use Unix-style terminals to demonstrate how to interact with Substrate from the command -line. - -### Ubuntu/Debian - -Use a terminal shell to execute the following commands: - -```bash -sudo apt update -# May prompt for location information -sudo apt install -y git clang curl libssl-dev llvm libudev-dev -``` - -### Arch Linux - -Run these commands from a terminal: - -```bash -pacman -Syu --needed --noconfirm curl git clang -``` - -### Fedora - -Run these commands from a terminal: - -```bash -sudo dnf update -sudo dnf install clang curl git openssl-devel -``` - -### OpenSUSE - -Run these commands from a terminal: - -```bash -sudo zypper install clang curl git openssl-devel llvm-devel libudev-devel -``` - -### macOS - -> **Apple M1 ARM** If you have an Apple M1 ARM system on a chip, make sure that you have Apple Rosetta 2 installed -> through `softwareupdate --install-rosetta`. This is only needed to run the `protoc` tool during the build. The build -> itself and the target binaries would remain native. - -Open the Terminal application and execute the following commands: - -```bash -# Install Homebrew if necessary https://brew.sh/ -/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" - -# Make sure Homebrew is up-to-date, install openssl -brew update -brew install openssl -``` - -### Windows - -**_PLEASE NOTE:_** Native Windows development of Substrate is _not_ very well supported! It is _highly_ -recommended to use [Windows Subsystem Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) -(WSL) and follow the instructions for [Ubuntu/Debian](#ubuntudebian). -Please refer to the separate -[guide for native Windows development](https://docs.substrate.io/main-docs/install/windows/). - -## Rust developer environment - -This guide uses installer and the `rustup` tool to manage the Rust toolchain. First install and -configure `rustup`: - -```bash -# Install -curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -# Configure -source ~/.cargo/env -``` - -Configure the Rust toolchain to default to the latest stable version, add nightly and the nightly wasm target: - -```bash -rustup default stable -rustup update -rustup update nightly -rustup target add wasm32-unknown-unknown --toolchain nightly -``` - -## Test your set-up - -Now the best way to ensure that you have successfully prepared a computer for Substrate development is to follow the -steps in [our first Substrate tutorial](https://docs.substrate.io/tutorials/v3/create-your-first-substrate-chain/). - -## Troubleshooting Substrate builds - -Sometimes you can't get the Substrate node template to compile out of the box. Here are some tips to help you work -through that. - -### Rust configuration check - -To see what Rust toolchain you are presently using, run: - -```bash -rustup show -``` - -This will show something like this (Ubuntu example) output: - -```text -Default host: x86_64-unknown-linux-gnu -rustup home: /home/user/.rustup - -installed toolchains --------------------- - -stable-x86_64-unknown-linux-gnu (default) -nightly-2020-10-06-x86_64-unknown-linux-gnu -nightly-x86_64-unknown-linux-gnu - -installed targets for active toolchain --------------------------------------- - -wasm32-unknown-unknown -x86_64-unknown-linux-gnu - -active toolchain ----------------- - -stable-x86_64-unknown-linux-gnu (default) -rustc 1.50.0 (cb75ad5db 2021-02-10) -``` - -As you can see above, the default toolchain is stable, and the `nightly-x86_64-unknown-linux-gnu` toolchain as well as -its `wasm32-unknown-unknown` target is installed. You also see that `nightly-2020-10-06-x86_64-unknown-linux-gnu` is -installed, but is not used unless explicitly defined as illustrated in the [specify your nightly -version](#specifying-nightly-version) section. - -### WebAssembly compilation - -Substrate uses [WebAssembly](https://webassembly.org) (Wasm) to produce portable blockchain runtimes. You will need to -configure your Rust compiler to use [`nightly` builds](https://doc.rust-lang.org/book/appendix-07-nightly-rust.html) to -allow you to compile Substrate runtime code to the Wasm target. - -> There are upstream issues in Rust that need to be resolved before all of Substrate can use the stable Rust toolchain. -> [This is our tracking issue](https://github.com/paritytech/substrate/issues/1252) if you're curious as to why and how -> this will be resolved. - -#### Latest nightly for Substrate `master` - -Developers who are building Substrate _itself_ should always use the latest bug-free versions of Rust stable and -nightly. This is because the Substrate codebase follows the tip of Rust nightly, which means that changes in Substrate -often depend on upstream changes in the Rust nightly compiler. To ensure your Rust compiler is always up to date, you -should run: - -```bash -rustup update -rustup update nightly -rustup target add wasm32-unknown-unknown --toolchain nightly -``` - -> NOTE: It may be necessary to occasionally rerun `rustup update` if a change in the upstream Substrate codebase depends -> on a new feature of the Rust compiler. When you do this, both your nightly and stable toolchains will be pulled to the -> most recent release, and for nightly, it is generally _not_ expected to compile WASM without error (although it very -> often does). Be sure to [specify your nightly version](#specifying-nightly-version) if you get WASM build errors from -> `rustup` and [downgrade nightly as needed](#downgrading-rust-nightly). - -#### Rust nightly toolchain - -If you want to guarantee that your build works on your computer as you update Rust and other dependencies, you should -use a specific Rust nightly version that is known to be compatible with the version of Substrate they are using; this -version will vary from project to project and different projects may use different mechanisms to communicate this -version to developers. For instance, the Polkadot client specifies this information in its [release -notes](https://github.com/paritytech/polkadot-sdk/releases). - -```bash -# Specify the specific nightly toolchain in the date below: -rustup install nightly- -``` - -#### Wasm toolchain - -Now, configure the nightly version to work with the Wasm compilation target: - -```bash -rustup target add wasm32-unknown-unknown --toolchain nightly- -``` - -### Specifying nightly version - -Use the `WASM_BUILD_TOOLCHAIN` environment variable to specify the Rust nightly version a Substrate project should use -for Wasm compilation: - -```bash -WASM_BUILD_TOOLCHAIN=nightly- cargo build --release -``` - -> Note that this only builds _the runtime_ with the specified nightly. The rest of project will be compiled with **your -> default toolchain**, i.e. the latest installed stable toolchain. - -### Downgrading Rust nightly - -If your computer is configured to use the latest Rust nightly and you would like to downgrade to a specific nightly -version, follow these steps: - -```bash -rustup uninstall nightly -rustup install nightly- -rustup target add wasm32-unknown-unknown --toolchain nightly- -``` diff --git a/polkadot-sdk-solochain-template/env-setup/README.md b/polkadot-sdk-solochain-template/env-setup/README.md deleted file mode 100644 index a795587..0000000 --- a/polkadot-sdk-solochain-template/env-setup/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# Env setup - -Special files for setting up an environment to work with the template: - -- `rust-toolchain.toml` when working with `rustup`. -- `flake.nix` when working with `nix`. - -These files will be copied by the installer script to the main directory. They are -put into this special directory to not interfere with the normal CI. diff --git a/polkadot-sdk-solochain-template/env-setup/flake.lock b/polkadot-sdk-solochain-template/env-setup/flake.lock deleted file mode 100644 index 60819f6..0000000 --- a/polkadot-sdk-solochain-template/env-setup/flake.lock +++ /dev/null @@ -1,43 +0,0 @@ -{ - "nodes": { - "flake-utils": { - "locked": { - "lastModified": 1678901627, - "narHash": "sha256-U02riOqrKKzwjsxc/400XnElV+UtPUQWpANPlyazjH0=", - "owner": "numtide", - "repo": "flake-utils", - "rev": "93a2b84fc4b70d9e089d029deacc3583435c2ed6", - "type": "github" - }, - "original": { - "owner": "numtide", - "repo": "flake-utils", - "type": "github" - } - }, - "nixpkgs": { - "locked": { - "lastModified": 1679262748, - "narHash": "sha256-DQCrrAFrkxijC6haUzOC5ZoFqpcv/tg2WxnyW3np1Cc=", - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "60c1d71f2ba4c80178ec84523c2ca0801522e0a6", - "type": "github" - }, - "original": { - "owner": "NixOS", - "ref": "nixos-unstable", - "repo": "nixpkgs", - "type": "github" - } - }, - "root": { - "inputs": { - "flake-utils": "flake-utils", - "nixpkgs": "nixpkgs" - } - } - }, - "root": "root", - "version": 7 -} diff --git a/polkadot-sdk-solochain-template/env-setup/flake.nix b/polkadot-sdk-solochain-template/env-setup/flake.nix deleted file mode 100644 index 428efd0..0000000 --- a/polkadot-sdk-solochain-template/env-setup/flake.nix +++ /dev/null @@ -1,22 +0,0 @@ -{ - inputs = { - nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; - flake-utils.url = "github:numtide/flake-utils"; - }; - - outputs = { self, nixpkgs, flake-utils, ... }: flake-utils.lib.eachDefaultSystem (system: - let - pkgs = import nixpkgs { inherit system; }; - in - { - devShells.default = pkgs.mkShell { - packages = with pkgs; [ - rustup - clang - protobuf - ]; - - LIBCLANG_PATH = "${pkgs.libclang.lib}/lib"; - }; - }); -} diff --git a/polkadot-sdk-solochain-template/env-setup/rust-toolchain.toml b/polkadot-sdk-solochain-template/env-setup/rust-toolchain.toml deleted file mode 100644 index f81199a..0000000 --- a/polkadot-sdk-solochain-template/env-setup/rust-toolchain.toml +++ /dev/null @@ -1,14 +0,0 @@ -[toolchain] -channel = "stable" -components = [ - "cargo", - "clippy", - "rust-analyzer", - "rust-src", - "rust-std", - "rustc", - "rustc-dev", - "rustfmt", -] -targets = ["wasm32-unknown-unknown"] -profile = "minimal" diff --git a/polkadot-sdk-solochain-template/node/Cargo.toml b/polkadot-sdk-solochain-template/node/Cargo.toml deleted file mode 100644 index 8fa4175..0000000 --- a/polkadot-sdk-solochain-template/node/Cargo.toml +++ /dev/null @@ -1,107 +0,0 @@ -[package] -name = "solochain-template-node" -description = "A solochain node template built with Substrate, part of Polkadot Sdk. (polkadot v1.15.0)" -version = "0.1.0" -license = "Unlicense" -authors.workspace = true -homepage.workspace = true -repository.workspace = true -edition.workspace = true -publish = false - -build = "build.rs" - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -clap = { features = ["derive"], workspace = true } -futures = { features = ["thread-pool"], workspace = true } -serde_json = { workspace = true, default-features = true } -jsonrpsee = { features = ["server"], workspace = true } -sc-cli.workspace = true -sc-cli.default-features = true -sp-core.workspace = true -sp-core.default-features = true -sc-executor.workspace = true -sc-executor.default-features = true -sc-network.workspace = true -sc-network.default-features = true -sc-service.workspace = true -sc-service.default-features = true -sc-telemetry.workspace = true -sc-telemetry.default-features = true -sc-transaction-pool.workspace = true -sc-transaction-pool.default-features = true -sc-transaction-pool-api.workspace = true -sc-transaction-pool-api.default-features = true -sc-offchain.workspace = true -sc-offchain.default-features = true -sc-consensus-aura.workspace = true -sc-consensus-aura.default-features = true -sp-consensus-aura.workspace = true -sp-consensus-aura.default-features = true -sc-consensus.workspace = true -sc-consensus.default-features = true -sc-consensus-grandpa.workspace = true -sc-consensus-grandpa.default-features = true -sp-consensus-grandpa.workspace = true -sp-consensus-grandpa.default-features = true -sc-client-api.workspace = true -sc-client-api.default-features = true -sc-rpc-api.workspace = true -sc-rpc-api.default-features = true -sc-basic-authorship.workspace = true -sc-basic-authorship.default-features = true -sp-runtime.workspace = true -sp-runtime.default-features = true -sp-io.workspace = true -sp-io.default-features = true -sp-timestamp.workspace = true -sp-timestamp.default-features = true -sp-inherents.workspace = true -sp-inherents.default-features = true -sp-keyring.workspace = true -sp-keyring.default-features = true -sp-api.workspace = true -sp-api.default-features = true -sp-blockchain.workspace = true -sp-blockchain.default-features = true -sp-block-builder.workspace = true -sp-block-builder.default-features = true -frame-system.workspace = true -frame-system.default-features = true -pallet-transaction-payment.workspace = true -pallet-transaction-payment-rpc.workspace = true -pallet-transaction-payment-rpc.default-features = true -substrate-frame-rpc-system.workspace = true -substrate-frame-rpc-system.default-features = true -frame-benchmarking-cli.workspace = true -frame-benchmarking-cli.default-features = true -solochain-template-runtime.workspace = true - -[build-dependencies] -substrate-build-script-utils.workspace = true -substrate-build-script-utils.default-features = true - -[features] -default = ["std"] -std = [ - "solochain-template-runtime/std", -] -# Dependencies that are only required if runtime benchmarking should be build. -runtime-benchmarks = [ - "frame-benchmarking-cli/runtime-benchmarks", - "frame-system/runtime-benchmarks", - "sc-service/runtime-benchmarks", - "solochain-template-runtime/runtime-benchmarks", - "sp-runtime/runtime-benchmarks", -] -# Enable features that allow the runtime to be tried and debugged. Name might be subject to change -# in the near future. -try-runtime = [ - "frame-system/try-runtime", - "pallet-transaction-payment/try-runtime", - "solochain-template-runtime/try-runtime", - "sp-runtime/try-runtime", -] diff --git a/polkadot-sdk-solochain-template/node/build.rs b/polkadot-sdk-solochain-template/node/build.rs deleted file mode 100644 index e3bfe31..0000000 --- a/polkadot-sdk-solochain-template/node/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; - -fn main() { - generate_cargo_keys(); - - rerun_if_git_head_changed(); -} diff --git a/polkadot-sdk-solochain-template/node/src/benchmarking.rs b/polkadot-sdk-solochain-template/node/src/benchmarking.rs deleted file mode 100644 index d1d8c2c..0000000 --- a/polkadot-sdk-solochain-template/node/src/benchmarking.rs +++ /dev/null @@ -1,161 +0,0 @@ -//! Setup code for [`super::command`] which would otherwise bloat that module. -//! -//! Should only be used for benchmarking as it may break in other contexts. - -use crate::service::FullClient; - -use runtime::{AccountId, Balance, BalancesCall, SystemCall}; -use sc_cli::Result; -use sc_client_api::BlockBackend; -use solochain_template_runtime as runtime; -use sp_core::{Encode, Pair}; -use sp_inherents::{InherentData, InherentDataProvider}; -use sp_keyring::Sr25519Keyring; -use sp_runtime::{OpaqueExtrinsic, SaturatedConversion}; - -use std::{sync::Arc, time::Duration}; - -/// Generates extrinsics for the `benchmark overhead` command. -/// -/// Note: Should only be used for benchmarking. -pub struct RemarkBuilder { - client: Arc, -} - -impl RemarkBuilder { - /// Creates a new [`Self`] from the given client. - pub fn new(client: Arc) -> Self { - Self { client } - } -} - -impl frame_benchmarking_cli::ExtrinsicBuilder for RemarkBuilder { - fn pallet(&self) -> &str { - "system" - } - - fn extrinsic(&self) -> &str { - "remark" - } - - fn build(&self, nonce: u32) -> std::result::Result { - let acc = Sr25519Keyring::Bob.pair(); - let extrinsic: OpaqueExtrinsic = create_benchmark_extrinsic( - self.client.as_ref(), - acc, - SystemCall::remark { remark: vec![] }.into(), - nonce, - ) - .into(); - - Ok(extrinsic) - } -} - -/// Generates `Balances::TransferKeepAlive` extrinsics for the benchmarks. -/// -/// Note: Should only be used for benchmarking. -pub struct TransferKeepAliveBuilder { - client: Arc, - dest: AccountId, - value: Balance, -} - -impl TransferKeepAliveBuilder { - /// Creates a new [`Self`] from the given client. - pub fn new(client: Arc, dest: AccountId, value: Balance) -> Self { - Self { client, dest, value } - } -} - -impl frame_benchmarking_cli::ExtrinsicBuilder for TransferKeepAliveBuilder { - fn pallet(&self) -> &str { - "balances" - } - - fn extrinsic(&self) -> &str { - "transfer_keep_alive" - } - - fn build(&self, nonce: u32) -> std::result::Result { - let acc = Sr25519Keyring::Bob.pair(); - let extrinsic: OpaqueExtrinsic = create_benchmark_extrinsic( - self.client.as_ref(), - acc, - BalancesCall::transfer_keep_alive { dest: self.dest.clone().into(), value: self.value } - .into(), - nonce, - ) - .into(); - - Ok(extrinsic) - } -} - -/// Create a transaction using the given `call`. -/// -/// Note: Should only be used for benchmarking. -pub fn create_benchmark_extrinsic( - client: &FullClient, - sender: sp_core::sr25519::Pair, - call: runtime::RuntimeCall, - nonce: u32, -) -> runtime::UncheckedExtrinsic { - let genesis_hash = client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"); - let best_hash = client.chain_info().best_hash; - let best_block = client.chain_info().best_number; - - let period = runtime::BlockHashCount::get() - .checked_next_power_of_two() - .map(|c| c / 2) - .unwrap_or(2) as u64; - let extra: runtime::SignedExtra = ( - frame_system::CheckNonZeroSender::::new(), - frame_system::CheckSpecVersion::::new(), - frame_system::CheckTxVersion::::new(), - frame_system::CheckGenesis::::new(), - frame_system::CheckEra::::from(sp_runtime::generic::Era::mortal( - period, - best_block.saturated_into(), - )), - frame_system::CheckNonce::::from(nonce), - frame_system::CheckWeight::::new(), - pallet_transaction_payment::ChargeTransactionPayment::::from(0), - ); - - let raw_payload = runtime::SignedPayload::from_raw( - call.clone(), - extra.clone(), - ( - (), - runtime::VERSION.spec_version, - runtime::VERSION.transaction_version, - genesis_hash, - best_hash, - (), - (), - (), - ), - ); - let signature = raw_payload.using_encoded(|e| sender.sign(e)); - - runtime::UncheckedExtrinsic::new_signed( - call, - sp_runtime::AccountId32::from(sender.public()).into(), - runtime::Signature::Sr25519(signature), - extra, - ) -} - -/// Generates inherent data for the `benchmark overhead` command. -/// -/// Note: Should only be used for benchmarking. -pub fn inherent_benchmark_data() -> Result { - let mut inherent_data = InherentData::new(); - let d = Duration::from_millis(0); - let timestamp = sp_timestamp::InherentDataProvider::new(d.into()); - - futures::executor::block_on(timestamp.provide_inherent_data(&mut inherent_data)) - .map_err(|e| format!("creating inherent data: {:?}", e))?; - Ok(inherent_data) -} diff --git a/polkadot-sdk-solochain-template/node/src/chain_spec.rs b/polkadot-sdk-solochain-template/node/src/chain_spec.rs deleted file mode 100644 index 651025e..0000000 --- a/polkadot-sdk-solochain-template/node/src/chain_spec.rs +++ /dev/null @@ -1,117 +0,0 @@ -use sc_service::ChainType; -use solochain_template_runtime::{AccountId, Signature, WASM_BINARY}; -use sp_consensus_aura::sr25519::AuthorityId as AuraId; -use sp_consensus_grandpa::AuthorityId as GrandpaId; -use sp_core::{sr25519, Pair, Public}; -use sp_runtime::traits::{IdentifyAccount, Verify}; - -// The URL for the telemetry server. -// const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; - -/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type. -pub type ChainSpec = sc_service::GenericChainSpec; - -/// Generate a crypto pair from seed. -pub fn get_from_seed(seed: &str) -> ::Public { - TPublic::Pair::from_string(&format!("//{}", seed), None) - .expect("static values are valid; qed") - .public() -} - -type AccountPublic = ::Signer; - -/// Generate an account ID from seed. -pub fn get_account_id_from_seed(seed: &str) -> AccountId -where - AccountPublic: From<::Public>, -{ - AccountPublic::from(get_from_seed::(seed)).into_account() -} - -/// Generate an Aura authority key. -pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) { - (get_from_seed::(s), get_from_seed::(s)) -} - -pub fn development_config() -> Result { - Ok(ChainSpec::builder( - WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?, - None, - ) - .with_name("Development") - .with_id("dev") - .with_chain_type(ChainType::Development) - .with_genesis_config_patch(testnet_genesis( - // Initial PoA authorities - vec![authority_keys_from_seed("Alice")], - // Sudo account - get_account_id_from_seed::("Alice"), - // Pre-funded accounts - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - ], - true, - )) - .build()) -} - -pub fn local_testnet_config() -> Result { - Ok(ChainSpec::builder( - WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?, - None, - ) - .with_name("Local Testnet") - .with_id("local_testnet") - .with_chain_type(ChainType::Local) - .with_genesis_config_patch(testnet_genesis( - // Initial PoA authorities - vec![authority_keys_from_seed("Alice"), authority_keys_from_seed("Bob")], - // Sudo account - get_account_id_from_seed::("Alice"), - // Pre-funded accounts - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Ferdie"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - get_account_id_from_seed::("Charlie//stash"), - get_account_id_from_seed::("Dave//stash"), - get_account_id_from_seed::("Eve//stash"), - get_account_id_from_seed::("Ferdie//stash"), - ], - true, - )) - .build()) -} - -/// Configure initial storage state for FRAME modules. -fn testnet_genesis( - initial_authorities: Vec<(AuraId, GrandpaId)>, - root_key: AccountId, - endowed_accounts: Vec, - _enable_println: bool, -) -> serde_json::Value { - serde_json::json!({ - "balances": { - // Configure endowed accounts with initial balance of 1 << 60. - "balances": endowed_accounts.iter().cloned().map(|k| (k, 1u64 << 60)).collect::>(), - }, - "aura": { - "authorities": initial_authorities.iter().map(|x| (x.0.clone())).collect::>(), - }, - "grandpa": { - "authorities": initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect::>(), - }, - "sudo": { - // Assign network admin rights. - "key": Some(root_key), - }, - }) -} diff --git a/polkadot-sdk-solochain-template/node/src/cli.rs b/polkadot-sdk-solochain-template/node/src/cli.rs deleted file mode 100644 index b2c53aa..0000000 --- a/polkadot-sdk-solochain-template/node/src/cli.rs +++ /dev/null @@ -1,46 +0,0 @@ -use sc_cli::RunCmd; - -#[derive(Debug, clap::Parser)] -pub struct Cli { - #[command(subcommand)] - pub subcommand: Option, - - #[clap(flatten)] - pub run: RunCmd, -} - -#[derive(Debug, clap::Subcommand)] -#[allow(clippy::large_enum_variant)] -pub enum Subcommand { - /// Key management cli utilities - #[command(subcommand)] - Key(sc_cli::KeySubcommand), - - /// Build a chain specification. - BuildSpec(sc_cli::BuildSpecCmd), - - /// Validate blocks. - CheckBlock(sc_cli::CheckBlockCmd), - - /// Export blocks. - ExportBlocks(sc_cli::ExportBlocksCmd), - - /// Export the state of a given block into a chain spec. - ExportState(sc_cli::ExportStateCmd), - - /// Import blocks. - ImportBlocks(sc_cli::ImportBlocksCmd), - - /// Remove the whole chain. - PurgeChain(sc_cli::PurgeChainCmd), - - /// Revert the chain to a previous state. - Revert(sc_cli::RevertCmd), - - /// Sub-commands concerned with benchmarking. - #[command(subcommand)] - Benchmark(frame_benchmarking_cli::BenchmarkCmd), - - /// Db meta columns information. - ChainInfo(sc_cli::ChainInfoCmd), -} diff --git a/polkadot-sdk-solochain-template/node/src/command.rs b/polkadot-sdk-solochain-template/node/src/command.rs deleted file mode 100644 index 624ace1..0000000 --- a/polkadot-sdk-solochain-template/node/src/command.rs +++ /dev/null @@ -1,195 +0,0 @@ -use crate::{ - benchmarking::{inherent_benchmark_data, RemarkBuilder, TransferKeepAliveBuilder}, - chain_spec, - cli::{Cli, Subcommand}, - service, -}; -use frame_benchmarking_cli::{BenchmarkCmd, ExtrinsicFactory, SUBSTRATE_REFERENCE_HARDWARE}; -use sc_cli::SubstrateCli; -use sc_service::PartialComponents; -use solochain_template_runtime::{Block, EXISTENTIAL_DEPOSIT}; -use sp_keyring::Sr25519Keyring; - -impl SubstrateCli for Cli { - fn impl_name() -> String { - "Substrate Node".into() - } - - fn impl_version() -> String { - env!("SUBSTRATE_CLI_IMPL_VERSION").into() - } - - fn description() -> String { - env!("CARGO_PKG_DESCRIPTION").into() - } - - fn author() -> String { - env!("CARGO_PKG_AUTHORS").into() - } - - fn support_url() -> String { - "support.anonymous.an".into() - } - - fn copyright_start_year() -> i32 { - 2017 - } - - fn load_spec(&self, id: &str) -> Result, String> { - Ok(match id { - "dev" => Box::new(chain_spec::development_config()?), - "" | "local" => Box::new(chain_spec::local_testnet_config()?), - path => - Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?), - }) - } -} - -/// Parse and run command line arguments -pub fn run() -> sc_cli::Result<()> { - let cli = Cli::from_args(); - - match &cli.subcommand { - Some(Subcommand::Key(cmd)) => cmd.run(&cli), - Some(Subcommand::BuildSpec(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) - }, - Some(Subcommand::CheckBlock(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.async_run(|config| { - let PartialComponents { client, task_manager, import_queue, .. } = - service::new_partial(&config)?; - Ok((cmd.run(client, import_queue), task_manager)) - }) - }, - Some(Subcommand::ExportBlocks(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.async_run(|config| { - let PartialComponents { client, task_manager, .. } = service::new_partial(&config)?; - Ok((cmd.run(client, config.database), task_manager)) - }) - }, - Some(Subcommand::ExportState(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.async_run(|config| { - let PartialComponents { client, task_manager, .. } = service::new_partial(&config)?; - Ok((cmd.run(client, config.chain_spec), task_manager)) - }) - }, - Some(Subcommand::ImportBlocks(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.async_run(|config| { - let PartialComponents { client, task_manager, import_queue, .. } = - service::new_partial(&config)?; - Ok((cmd.run(client, import_queue), task_manager)) - }) - }, - Some(Subcommand::PurgeChain(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run(config.database)) - }, - Some(Subcommand::Revert(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.async_run(|config| { - let PartialComponents { client, task_manager, backend, .. } = - service::new_partial(&config)?; - let aux_revert = Box::new(|client, _, blocks| { - sc_consensus_grandpa::revert(client, blocks)?; - Ok(()) - }); - Ok((cmd.run(client, backend, Some(aux_revert)), task_manager)) - }) - }, - Some(Subcommand::Benchmark(cmd)) => { - let runner = cli.create_runner(cmd)?; - - runner.sync_run(|config| { - // This switch needs to be in the client, since the client decides - // which sub-commands it wants to support. - match cmd { - BenchmarkCmd::Pallet(cmd) => { - if !cfg!(feature = "runtime-benchmarks") { - return Err( - "Runtime benchmarking wasn't enabled when building the node. \ - You can enable it with `--features runtime-benchmarks`." - .into(), - ); - } - - cmd.run_with_spec::, ()>(Some( - config.chain_spec, - )) - }, - BenchmarkCmd::Block(cmd) => { - let PartialComponents { client, .. } = service::new_partial(&config)?; - cmd.run(client) - }, - #[cfg(not(feature = "runtime-benchmarks"))] - BenchmarkCmd::Storage(_) => Err( - "Storage benchmarking can be enabled with `--features runtime-benchmarks`." - .into(), - ), - #[cfg(feature = "runtime-benchmarks")] - BenchmarkCmd::Storage(cmd) => { - let PartialComponents { client, backend, .. } = - service::new_partial(&config)?; - let db = backend.expose_db(); - let storage = backend.expose_storage(); - - cmd.run(config, client, db, storage) - }, - BenchmarkCmd::Overhead(cmd) => { - let PartialComponents { client, .. } = service::new_partial(&config)?; - let ext_builder = RemarkBuilder::new(client.clone()); - - cmd.run( - config, - client, - inherent_benchmark_data()?, - Vec::new(), - &ext_builder, - ) - }, - BenchmarkCmd::Extrinsic(cmd) => { - let PartialComponents { client, .. } = service::new_partial(&config)?; - // Register the *Remark* and *TKA* builders. - let ext_factory = ExtrinsicFactory(vec![ - Box::new(RemarkBuilder::new(client.clone())), - Box::new(TransferKeepAliveBuilder::new( - client.clone(), - Sr25519Keyring::Alice.to_account_id(), - EXISTENTIAL_DEPOSIT, - )), - ]); - - cmd.run(client, inherent_benchmark_data()?, Vec::new(), &ext_factory) - }, - BenchmarkCmd::Machine(cmd) => - cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()), - } - }) - }, - Some(Subcommand::ChainInfo(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run::(&config)) - }, - None => { - let runner = cli.create_runner(&cli.run)?; - runner.run_node_until_exit(|config| async move { - match config.network.network_backend { - sc_network::config::NetworkBackendType::Libp2p => service::new_full::< - sc_network::NetworkWorker< - solochain_template_runtime::opaque::Block, - ::Hash, - >, - >(config) - .map_err(sc_cli::Error::Service), - sc_network::config::NetworkBackendType::Litep2p => - service::new_full::(config) - .map_err(sc_cli::Error::Service), - } - }) - }, - } -} diff --git a/polkadot-sdk-solochain-template/node/src/main.rs b/polkadot-sdk-solochain-template/node/src/main.rs deleted file mode 100644 index 8918dd4..0000000 --- a/polkadot-sdk-solochain-template/node/src/main.rs +++ /dev/null @@ -1,13 +0,0 @@ -//! Substrate Node Template CLI library. -#![warn(missing_docs)] - -mod benchmarking; -mod chain_spec; -mod cli; -mod command; -mod rpc; -mod service; - -fn main() -> sc_cli::Result<()> { - command::run() -} diff --git a/polkadot-sdk-solochain-template/node/src/rpc.rs b/polkadot-sdk-solochain-template/node/src/rpc.rs deleted file mode 100644 index fe2b6ca..0000000 --- a/polkadot-sdk-solochain-template/node/src/rpc.rs +++ /dev/null @@ -1,64 +0,0 @@ -//! A collection of node-specific RPC methods. -//! Substrate provides the `sc-rpc` crate, which defines the core RPC layer -//! used by Substrate nodes. This file extends those RPC definitions with -//! capabilities that are specific to this project's runtime configuration. - -#![warn(missing_docs)] - -use std::sync::Arc; - -use jsonrpsee::RpcModule; -use sc_transaction_pool_api::TransactionPool; -use solochain_template_runtime::{opaque::Block, AccountId, Balance, Nonce}; -use sp_api::ProvideRuntimeApi; -use sp_block_builder::BlockBuilder; -use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; - -pub use sc_rpc_api::DenyUnsafe; - -/// Full client dependencies. -pub struct FullDeps { - /// The client instance to use. - pub client: Arc, - /// Transaction pool instance. - pub pool: Arc

, - /// Whether to deny unsafe calls - pub deny_unsafe: DenyUnsafe, -} - -/// Instantiate all full RPC extensions. -pub fn create_full( - deps: FullDeps, -) -> Result, Box> -where - C: ProvideRuntimeApi, - C: HeaderBackend + HeaderMetadata + 'static, - C: Send + Sync + 'static, - C::Api: substrate_frame_rpc_system::AccountNonceApi, - C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, - C::Api: BlockBuilder, - P: TransactionPool + 'static, -{ - use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; - use substrate_frame_rpc_system::{System, SystemApiServer}; - - let mut module = RpcModule::new(()); - let FullDeps { client, pool, deny_unsafe } = deps; - - module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?; - module.merge(TransactionPayment::new(client).into_rpc())?; - - // Extend this RPC with a custom API by using the following syntax. - // `YourRpcStruct` should have a reference to a client, which is needed - // to call into the runtime. - // `module.merge(YourRpcTrait::into_rpc(YourRpcStruct::new(ReferenceToClient, ...)))?;` - - // You probably want to enable the `rpc v2 chainSpec` API as well - // - // let chain_name = chain_spec.name().to_string(); - // let genesis_hash = client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"); - // let properties = chain_spec.properties(); - // module.merge(ChainSpec::new(chain_name, genesis_hash, properties).into_rpc())?; - - Ok(module) -} diff --git a/polkadot-sdk-solochain-template/node/src/service.rs b/polkadot-sdk-solochain-template/node/src/service.rs deleted file mode 100644 index 06d4b8a..0000000 --- a/polkadot-sdk-solochain-template/node/src/service.rs +++ /dev/null @@ -1,332 +0,0 @@ -//! Service and ServiceFactory implementation. Specialized wrapper over substrate service. - -use futures::FutureExt; -use sc_client_api::{Backend, BlockBackend}; -use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams}; -use sc_consensus_grandpa::SharedVoterState; -use sc_service::{error::Error as ServiceError, Configuration, TaskManager, WarpSyncParams}; -use sc_telemetry::{Telemetry, TelemetryWorker}; -use sc_transaction_pool_api::OffchainTransactionPoolFactory; -use solochain_template_runtime::{self, opaque::Block, RuntimeApi}; -use sp_consensus_aura::sr25519::AuthorityPair as AuraPair; -use std::{sync::Arc, time::Duration}; - -pub(crate) type FullClient = sc_service::TFullClient< - Block, - RuntimeApi, - sc_executor::WasmExecutor, ->; -type FullBackend = sc_service::TFullBackend; -type FullSelectChain = sc_consensus::LongestChain; - -/// The minimum period of blocks on which justifications will be -/// imported and generated. -const GRANDPA_JUSTIFICATION_PERIOD: u32 = 512; - -pub type Service = sc_service::PartialComponents< - FullClient, - FullBackend, - FullSelectChain, - sc_consensus::DefaultImportQueue, - sc_transaction_pool::FullPool, - ( - sc_consensus_grandpa::GrandpaBlockImport, - sc_consensus_grandpa::LinkHalf, - Option, - ), ->; - -pub fn new_partial(config: &Configuration) -> Result { - let telemetry = config - .telemetry_endpoints - .clone() - .filter(|x| !x.is_empty()) - .map(|endpoints| -> Result<_, sc_telemetry::Error> { - let worker = TelemetryWorker::new(16)?; - let telemetry = worker.handle().new_telemetry(endpoints); - Ok((worker, telemetry)) - }) - .transpose()?; - - let executor = sc_service::new_wasm_executor::(config); - let (client, backend, keystore_container, task_manager) = - sc_service::new_full_parts::( - config, - telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), - executor, - )?; - let client = Arc::new(client); - - let telemetry = telemetry.map(|(worker, telemetry)| { - task_manager.spawn_handle().spawn("telemetry", None, worker.run()); - telemetry - }); - - let select_chain = sc_consensus::LongestChain::new(backend.clone()); - - let transaction_pool = sc_transaction_pool::BasicPool::new_full( - config.transaction_pool.clone(), - config.role.is_authority().into(), - config.prometheus_registry(), - task_manager.spawn_essential_handle(), - client.clone(), - ); - - let (grandpa_block_import, grandpa_link) = sc_consensus_grandpa::block_import( - client.clone(), - GRANDPA_JUSTIFICATION_PERIOD, - &client, - select_chain.clone(), - telemetry.as_ref().map(|x| x.handle()), - )?; - - let cidp_client = client.clone(); - let import_queue = - sc_consensus_aura::import_queue::(ImportQueueParams { - block_import: grandpa_block_import.clone(), - justification_import: Some(Box::new(grandpa_block_import.clone())), - client: client.clone(), - create_inherent_data_providers: move |parent_hash, _| { - let cidp_client = cidp_client.clone(); - async move { - let slot_duration = sc_consensus_aura::standalone::slot_duration_at( - &*cidp_client, - parent_hash, - )?; - let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); - - let slot = - sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration( - *timestamp, - slot_duration, - ); - - Ok((slot, timestamp)) - } - }, - spawner: &task_manager.spawn_essential_handle(), - registry: config.prometheus_registry(), - check_for_equivocation: Default::default(), - telemetry: telemetry.as_ref().map(|x| x.handle()), - compatibility_mode: Default::default(), - })?; - - Ok(sc_service::PartialComponents { - client, - backend, - task_manager, - import_queue, - keystore_container, - select_chain, - transaction_pool, - other: (grandpa_block_import, grandpa_link, telemetry), - }) -} - -/// Builds a new service for a full client. -pub fn new_full< - N: sc_network::NetworkBackend::Hash>, ->( - config: Configuration, -) -> Result { - let sc_service::PartialComponents { - client, - backend, - mut task_manager, - import_queue, - keystore_container, - select_chain, - transaction_pool, - other: (block_import, grandpa_link, mut telemetry), - } = new_partial(&config)?; - - let mut net_config = sc_network::config::FullNetworkConfiguration::< - Block, - ::Hash, - N, - >::new(&config.network); - let metrics = N::register_notification_metrics(config.prometheus_registry()); - - let peer_store_handle = net_config.peer_store_handle(); - let grandpa_protocol_name = sc_consensus_grandpa::protocol_standard_name( - &client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"), - &config.chain_spec, - ); - let (grandpa_protocol_config, grandpa_notification_service) = - sc_consensus_grandpa::grandpa_peers_set_config::<_, N>( - grandpa_protocol_name.clone(), - metrics.clone(), - peer_store_handle, - ); - net_config.add_notification_protocol(grandpa_protocol_config); - - let warp_sync = Arc::new(sc_consensus_grandpa::warp_proof::NetworkProvider::new( - backend.clone(), - grandpa_link.shared_authority_set().clone(), - Vec::default(), - )); - - let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) = - sc_service::build_network(sc_service::BuildNetworkParams { - config: &config, - net_config, - client: client.clone(), - transaction_pool: transaction_pool.clone(), - spawn_handle: task_manager.spawn_handle(), - import_queue, - block_announce_validator_builder: None, - warp_sync_params: Some(WarpSyncParams::WithProvider(warp_sync)), - block_relay: None, - metrics, - })?; - - if config.offchain_worker.enabled { - 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: Arc::new(network.clone()), - enable_http_requests: true, - custom_extensions: |_| vec![], - }) - .run(client.clone(), task_manager.spawn_handle()) - .boxed(), - ); - } - - let role = config.role.clone(); - let force_authoring = config.force_authoring; - let backoff_authoring_blocks: Option<()> = None; - let name = config.network.node_name.clone(); - let enable_grandpa = !config.disable_grandpa; - let prometheus_registry = config.prometheus_registry().cloned(); - - let rpc_extensions_builder = { - let client = client.clone(); - let pool = transaction_pool.clone(); - - Box::new(move |deny_unsafe, _| { - let deps = - crate::rpc::FullDeps { client: client.clone(), pool: pool.clone(), deny_unsafe }; - crate::rpc::create_full(deps).map_err(Into::into) - }) - }; - - let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams { - network: Arc::new(network.clone()), - client: client.clone(), - keystore: keystore_container.keystore(), - task_manager: &mut task_manager, - transaction_pool: transaction_pool.clone(), - rpc_builder: rpc_extensions_builder, - backend, - system_rpc_tx, - tx_handler_controller, - sync_service: sync_service.clone(), - config, - telemetry: telemetry.as_mut(), - })?; - - if role.is_authority() { - let proposer_factory = sc_basic_authorship::ProposerFactory::new( - task_manager.spawn_handle(), - client.clone(), - transaction_pool.clone(), - prometheus_registry.as_ref(), - telemetry.as_ref().map(|x| x.handle()), - ); - - let slot_duration = sc_consensus_aura::slot_duration(&*client)?; - - let aura = sc_consensus_aura::start_aura::( - StartAuraParams { - slot_duration, - client, - select_chain, - block_import, - proposer_factory, - create_inherent_data_providers: move |_, ()| async move { - let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); - - let slot = - sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration( - *timestamp, - slot_duration, - ); - - Ok((slot, timestamp)) - }, - force_authoring, - backoff_authoring_blocks, - keystore: keystore_container.keystore(), - sync_oracle: sync_service.clone(), - justification_sync_link: sync_service.clone(), - block_proposal_slot_portion: SlotProportion::new(2f32 / 3f32), - max_block_proposal_slot_portion: None, - telemetry: telemetry.as_ref().map(|x| x.handle()), - compatibility_mode: Default::default(), - }, - )?; - - // the AURA authoring task is considered essential, i.e. if it - // fails we take down the service with it. - task_manager - .spawn_essential_handle() - .spawn_blocking("aura", Some("block-authoring"), aura); - } - - if enable_grandpa { - // if the node isn't actively participating in consensus then it doesn't - // need a keystore, regardless of which protocol we use below. - let keystore = if role.is_authority() { Some(keystore_container.keystore()) } else { None }; - - let grandpa_config = sc_consensus_grandpa::Config { - // FIXME #1578 make this available through chainspec - gossip_duration: Duration::from_millis(333), - justification_generation_period: GRANDPA_JUSTIFICATION_PERIOD, - name: Some(name), - observer_enabled: false, - keystore, - local_role: role, - telemetry: telemetry.as_ref().map(|x| x.handle()), - protocol_name: grandpa_protocol_name, - }; - - // start the full GRANDPA voter - // NOTE: non-authorities could run the GRANDPA observer protocol, but at - // this point the full voter should provide better guarantees of block - // and vote data availability than the observer. The observer has not - // been tested extensively yet and having most nodes in a network run it - // could lead to finality stalls. - let grandpa_config = sc_consensus_grandpa::GrandpaParams { - config: grandpa_config, - link: grandpa_link, - network, - sync: Arc::new(sync_service), - notification_service: grandpa_notification_service, - voting_rule: sc_consensus_grandpa::VotingRulesBuilder::default().build(), - prometheus_registry, - shared_voter_state: SharedVoterState::empty(), - telemetry: telemetry.as_ref().map(|x| x.handle()), - offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(transaction_pool), - }; - - // the GRANDPA voter task is considered infallible, i.e. - // if it fails we take down the service with it. - task_manager.spawn_essential_handle().spawn_blocking( - "grandpa-voter", - None, - sc_consensus_grandpa::run_grandpa_voter(grandpa_config)?, - ); - } - - network_starter.start_network(); - Ok(task_manager) -} diff --git a/polkadot-sdk-solochain-template/pallets/template/Cargo.toml b/polkadot-sdk-solochain-template/pallets/template/Cargo.toml deleted file mode 100644 index cf5bee0..0000000 --- a/polkadot-sdk-solochain-template/pallets/template/Cargo.toml +++ /dev/null @@ -1,48 +0,0 @@ -[package] -name = "pallet-template" -description = "FRAME pallet template for defining custom runtime logic. (polkadot v1.15.0)" -version = "0.1.0" -license = "Unlicense" -authors.workspace = true -homepage.workspace = true -repository.workspace = true -edition.workspace = true -publish = false - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -codec = { features = [ - "derive", -], workspace = true } -scale-info = { features = [ - "derive", -], workspace = true } -frame-benchmarking = { optional = true, workspace = true } -frame-support.workspace = true -frame-system.workspace = true - -[dev-dependencies] -sp-core = { default-features = true, workspace = true } -sp-io = { default-features = true, workspace = true } -sp-runtime = { default-features = true, workspace = true } - -[features] -default = ["std"] -std = [ - "codec/std", - "frame-benchmarking?/std", - "frame-support/std", - "frame-system/std", - "scale-info/std", -] -runtime-benchmarks = [ - "frame-benchmarking/runtime-benchmarks", - "frame-support/runtime-benchmarks", - "frame-system/runtime-benchmarks", -] -try-runtime = [ - "frame-support/try-runtime", - "frame-system/try-runtime", -] diff --git a/polkadot-sdk-solochain-template/pallets/template/README.md b/polkadot-sdk-solochain-template/pallets/template/README.md deleted file mode 100644 index 9e4dc55..0000000 --- a/polkadot-sdk-solochain-template/pallets/template/README.md +++ /dev/null @@ -1 +0,0 @@ -License: MIT-0 diff --git a/polkadot-sdk-solochain-template/pallets/template/src/benchmarking.rs b/polkadot-sdk-solochain-template/pallets/template/src/benchmarking.rs deleted file mode 100644 index d1a9554..0000000 --- a/polkadot-sdk-solochain-template/pallets/template/src/benchmarking.rs +++ /dev/null @@ -1,35 +0,0 @@ -//! Benchmarking setup for pallet-template -#![cfg(feature = "runtime-benchmarks")] -use super::*; - -#[allow(unused)] -use crate::Pallet as Template; -use frame_benchmarking::v2::*; -use frame_system::RawOrigin; - -#[benchmarks] -mod benchmarks { - use super::*; - - #[benchmark] - fn do_something() { - let value = 100u32; - let caller: T::AccountId = whitelisted_caller(); - #[extrinsic_call] - do_something(RawOrigin::Signed(caller), value); - - assert_eq!(Something::::get(), Some(value)); - } - - #[benchmark] - fn cause_error() { - Something::::put(100u32); - let caller: T::AccountId = whitelisted_caller(); - #[extrinsic_call] - cause_error(RawOrigin::Signed(caller)); - - assert_eq!(Something::::get(), Some(101u32)); - } - - impl_benchmark_test_suite!(Template, crate::mock::new_test_ext(), crate::mock::Test); -} diff --git a/polkadot-sdk-solochain-template/pallets/template/src/lib.rs b/polkadot-sdk-solochain-template/pallets/template/src/lib.rs deleted file mode 100644 index 90dfe37..0000000 --- a/polkadot-sdk-solochain-template/pallets/template/src/lib.rs +++ /dev/null @@ -1,202 +0,0 @@ -//! # Template Pallet -//! -//! A pallet with minimal functionality to help developers understand the essential components of -//! writing a FRAME pallet. It is typically used in beginner tutorials or in Substrate template -//! nodes as a starting point for creating a new pallet and **not meant to be used in production**. -//! -//! ## Overview -//! -//! This template pallet contains basic examples of: -//! - declaring a storage item that stores a single `u32` value -//! - declaring and using events -//! - declaring and using errors -//! - a dispatchable function that allows a user to set a new value to storage and emits an event -//! upon success -//! - another dispatchable function that causes a custom error to be thrown -//! -//! Each pallet section is annotated with an attribute using the `#[pallet::...]` procedural macro. -//! This macro generates the necessary code for a pallet to be aggregated into a FRAME runtime. -//! -//! Learn more about FRAME macros [here](https://docs.substrate.io/reference/frame-macros/). -//! -//! ### Pallet Sections -//! -//! The pallet sections in this template are: -//! -//! - A **configuration trait** that defines the types and parameters which the pallet depends on -//! (denoted by the `#[pallet::config]` attribute). See: [`Config`]. -//! - A **means to store pallet-specific data** (denoted by the `#[pallet::storage]` attribute). -//! See: [`storage_types`]. -//! - A **declaration of the events** this pallet emits (denoted by the `#[pallet::event]` -//! attribute). See: [`Event`]. -//! - A **declaration of the errors** that this pallet can throw (denoted by the `#[pallet::error]` -//! attribute). See: [`Error`]. -//! - A **set of dispatchable functions** that define the pallet's functionality (denoted by the -//! `#[pallet::call]` attribute). See: [`dispatchables`]. -//! -//! Run `cargo doc --package pallet-template --open` to view this pallet's documentation. - -// We make sure this pallet uses `no_std` for compiling to Wasm. -#![cfg_attr(not(feature = "std"), no_std)] - -// Re-export pallet items so that they can be accessed from the crate namespace. -pub use pallet::*; - -// FRAME pallets require their own "mock runtimes" to be able to run unit tests. This module -// contains a mock runtime specific for testing this pallet's functionality. -#[cfg(test)] -mod mock; - -// This module contains the unit tests for this pallet. -// Learn about pallet unit testing here: https://docs.substrate.io/test/unit-testing/ -#[cfg(test)] -mod tests; - -// Every callable function or "dispatchable" a pallet exposes must have weight values that correctly -// estimate a dispatchable's execution time. The benchmarking module is used to calculate weights -// for each dispatchable and generates this pallet's weight.rs file. Learn more about benchmarking here: https://docs.substrate.io/test/benchmark/ -#[cfg(feature = "runtime-benchmarks")] -mod benchmarking; -pub mod weights; -pub use weights::*; - -// All pallet logic is defined in its own module and must be annotated by the `pallet` attribute. -#[frame_support::pallet] -pub mod pallet { - // Import various useful types required by all FRAME pallets. - use super::*; - use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; - - // The `Pallet` struct serves as a placeholder to implement traits, methods and dispatchables - // (`Call`s) in this pallet. - #[pallet::pallet] - pub struct Pallet(_); - - /// The pallet's configuration trait. - /// - /// All our types and constants a pallet depends on must be declared here. - /// These types are defined generically and made concrete when the pallet is declared in the - /// `runtime/src/lib.rs` file of your chain. - #[pallet::config] - pub trait Config: frame_system::Config { - /// The overarching runtime event type. - type RuntimeEvent: From> + IsType<::RuntimeEvent>; - /// A type representing the weights required by the dispatchables of this pallet. - type WeightInfo: WeightInfo; - } - - /// A storage item for this pallet. - /// - /// In this template, we are declaring a storage item called `Something` that stores a single - /// `u32` value. Learn more about runtime storage here: - #[pallet::storage] - pub type Something = StorageValue<_, u32>; - - /// Events that functions in this pallet can emit. - /// - /// Events are a simple means of indicating to the outside world (such as dApps, chain explorers - /// or other users) that some notable update in the runtime has occurred. In a FRAME pallet, the - /// documentation for each event field and its parameters is added to a node's metadata so it - /// can be used by external interfaces or tools. - /// - /// The `generate_deposit` macro generates a function on `Pallet` called `deposit_event` which - /// will convert the event type of your pallet into `RuntimeEvent` (declared in the pallet's - /// [`Config`] trait) and deposit it using [`frame_system::Pallet::deposit_event`]. - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { - /// A user has successfully set a new value. - SomethingStored { - /// The new value set. - something: u32, - /// The account who set the new value. - who: T::AccountId, - }, - } - - /// Errors that can be returned by this pallet. - /// - /// Errors tell users that something went wrong so it's important that their naming is - /// informative. Similar to events, error documentation is added to a node's metadata so it's - /// equally important that they have helpful documentation associated with them. - /// - /// This type of runtime error can be up to 4 bytes in size should you want to return additional - /// information. - #[pallet::error] - pub enum Error { - /// The value retrieved was `None` as no value was previously set. - NoneValue, - /// There was an attempt to increment the value in storage over `u32::MAX`. - StorageOverflow, - } - - /// The pallet's dispatchable functions ([`Call`]s). - /// - /// Dispatchable functions allows users to interact with the pallet and invoke state changes. - /// These functions materialize as "extrinsics", which are often compared to transactions. - /// They must always return a `DispatchResult` and be annotated with a weight and call index. - /// - /// The [`call_index`] macro is used to explicitly - /// define an index for calls in the [`Call`] enum. This is useful for pallets that may - /// introduce new dispatchables over time. If the order of a dispatchable changes, its index - /// will also change which will break backwards compatibility. - /// - /// The [`weight`] macro is used to assign a weight to each call. - #[pallet::call] - impl Pallet { - /// An example dispatchable that takes a single u32 value as a parameter, writes the value - /// to storage and emits an event. - /// - /// It checks that the _origin_ for this call is _Signed_ and returns a dispatch - /// error if it isn't. Learn more about origins here: - #[pallet::call_index(0)] - #[pallet::weight(T::WeightInfo::do_something())] - pub fn do_something(origin: OriginFor, something: u32) -> DispatchResult { - // Check that the extrinsic was signed and get the signer. - let who = ensure_signed(origin)?; - - // Update storage. - Something::::put(something); - - // Emit an event. - Self::deposit_event(Event::SomethingStored { something, who }); - - // Return a successful `DispatchResult` - Ok(()) - } - - /// An example dispatchable that may throw a custom error. - /// - /// It checks that the caller is a signed origin and reads the current value from the - /// `Something` storage item. If a current value exists, it is incremented by 1 and then - /// written back to storage. - /// - /// ## Errors - /// - /// The function will return an error under the following conditions: - /// - /// - If no value has been set ([`Error::NoneValue`]) - /// - If incrementing the value in storage causes an arithmetic overflow - /// ([`Error::StorageOverflow`]) - #[pallet::call_index(1)] - #[pallet::weight(T::WeightInfo::cause_error())] - pub fn cause_error(origin: OriginFor) -> DispatchResult { - let _who = ensure_signed(origin)?; - - // Read a value from storage. - match Something::::get() { - // Return an error if the value has not been set. - None => Err(Error::::NoneValue.into()), - Some(old) => { - // Increment the value read from storage. This will cause an error in the event - // of overflow. - let new = old.checked_add(1).ok_or(Error::::StorageOverflow)?; - // Update the value in storage with the incremented result. - Something::::put(new); - Ok(()) - }, - } - } - } -} diff --git a/polkadot-sdk-solochain-template/pallets/template/src/mock.rs b/polkadot-sdk-solochain-template/pallets/template/src/mock.rs deleted file mode 100644 index 0c2a247..0000000 --- a/polkadot-sdk-solochain-template/pallets/template/src/mock.rs +++ /dev/null @@ -1,29 +0,0 @@ -use crate as pallet_template; -use frame_support::derive_impl; -use sp_runtime::BuildStorage; - -type Block = frame_system::mocking::MockBlock; - -// Configure a mock runtime to test the pallet. -frame_support::construct_runtime!( - pub enum Test - { - System: frame_system, - TemplateModule: pallet_template, - } -); - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] -impl frame_system::Config for Test { - type Block = Block; -} - -impl pallet_template::Config for Test { - type RuntimeEvent = RuntimeEvent; - type WeightInfo = (); -} - -// Build genesis storage according to the mock runtime. -pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::::default().build_storage().unwrap().into() -} diff --git a/polkadot-sdk-solochain-template/pallets/template/src/tests.rs b/polkadot-sdk-solochain-template/pallets/template/src/tests.rs deleted file mode 100644 index 83e4bea..0000000 --- a/polkadot-sdk-solochain-template/pallets/template/src/tests.rs +++ /dev/null @@ -1,27 +0,0 @@ -use crate::{mock::*, Error, Event, Something}; -use frame_support::{assert_noop, assert_ok}; - -#[test] -fn it_works_for_default_value() { - new_test_ext().execute_with(|| { - // Go past genesis block so events get deposited - System::set_block_number(1); - // Dispatch a signed extrinsic. - assert_ok!(TemplateModule::do_something(RuntimeOrigin::signed(1), 42)); - // Read pallet storage and assert an expected result. - assert_eq!(Something::::get(), Some(42)); - // Assert that the correct event was deposited - System::assert_last_event(Event::SomethingStored { something: 42, who: 1 }.into()); - }); -} - -#[test] -fn correct_error_for_none_value() { - new_test_ext().execute_with(|| { - // Ensure the expected error is thrown when no value is present. - assert_noop!( - TemplateModule::cause_error(RuntimeOrigin::signed(1)), - Error::::NoneValue - ); - }); -} diff --git a/polkadot-sdk-solochain-template/pallets/template/src/weights.rs b/polkadot-sdk-solochain-template/pallets/template/src/weights.rs deleted file mode 100644 index 7c42936..0000000 --- a/polkadot-sdk-solochain-template/pallets/template/src/weights.rs +++ /dev/null @@ -1,90 +0,0 @@ - -//! Autogenerated weights for pallet_template -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-04-06, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `Alexs-MacBook-Pro-2.local`, CPU: `` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 - -// Executed Command: -// ../../target/release/node-template -// benchmark -// pallet -// --chain -// dev -// --pallet -// pallet_template -// --extrinsic -// * -// --steps=50 -// --repeat=20 -// --wasm-execution=compiled -// --output -// pallets/template/src/weights.rs -// --template -// ../../.maintain/frame-weight-template.hbs - -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] - -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; -use core::marker::PhantomData; - -/// Weight functions needed for pallet_template. -pub trait WeightInfo { - fn do_something() -> Weight; - fn cause_error() -> Weight; -} - -/// Weights for pallet_template using the Substrate node and recommended hardware. -pub struct SubstrateWeight(PhantomData); -impl WeightInfo for SubstrateWeight { - /// Storage: TemplateModule Something (r:0 w:1) - /// Proof: TemplateModule Something (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - fn do_something() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 8_000_000 picoseconds. - Weight::from_parts(9_000_000, 0) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } - /// Storage: TemplateModule Something (r:1 w:1) - /// Proof: TemplateModule Something (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - fn cause_error() -> Weight { - // Proof Size summary in bytes: - // Measured: `32` - // Estimated: `1489` - // Minimum execution time: 6_000_000 picoseconds. - Weight::from_parts(6_000_000, 1489) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } -} - -// For backwards compatibility and tests -impl WeightInfo for () { - /// Storage: TemplateModule Something (r:0 w:1) - /// Proof: TemplateModule Something (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - fn do_something() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 8_000_000 picoseconds. - Weight::from_parts(9_000_000, 0) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } - /// Storage: TemplateModule Something (r:1 w:1) - /// Proof: TemplateModule Something (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - fn cause_error() -> Weight { - // Proof Size summary in bytes: - // Measured: `32` - // Estimated: `1489` - // Minimum execution time: 6_000_000 picoseconds. - Weight::from_parts(6_000_000, 1489) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } -} diff --git a/polkadot-sdk-solochain-template/runtime/Cargo.toml b/polkadot-sdk-solochain-template/runtime/Cargo.toml deleted file mode 100644 index ec9490a..0000000 --- a/polkadot-sdk-solochain-template/runtime/Cargo.toml +++ /dev/null @@ -1,122 +0,0 @@ -[package] -name = "solochain-template-runtime" -description = "A solochain runtime template built with Substrate, part of Polkadot Sdk. (polkadot v1.15.0)" -version = "0.1.0" -license = "Unlicense" -authors.workspace = true -homepage.workspace = true -repository.workspace = true -edition.workspace = true -publish = false - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -codec = { features = [ - "derive", -], workspace = true } -scale-info = { features = [ - "derive", - "serde", -], workspace = true } -frame-support = { features = ["experimental"], workspace = true } -frame-system.workspace = true -frame-try-runtime = { optional = true, workspace = true } -frame-executive.workspace = true -pallet-aura.workspace = true -pallet-balances.workspace = true -pallet-grandpa.workspace = true -pallet-sudo.workspace = true -pallet-timestamp.workspace = true -pallet-transaction-payment.workspace = true -sp-api.workspace = true -sp-block-builder.workspace = true -sp-consensus-aura = { features = ["serde"], workspace = true } -sp-consensus-grandpa = { features = ["serde"], workspace = true } -sp-core = { features = ["serde"], workspace = true } -sp-inherents.workspace = true -sp-offchain.workspace = true -sp-runtime = { features = ["serde"], workspace = true } -sp-session.workspace = true -sp-storage.workspace = true -sp-transaction-pool.workspace = true -sp-version = { features = ["serde"], workspace = true } -sp-genesis-builder.workspace = true -frame-system-rpc-runtime-api.workspace = true -pallet-transaction-payment-rpc-runtime-api.workspace = true -frame-benchmarking = { optional = true, workspace = true } -frame-system-benchmarking = { optional = true, workspace = true } -pallet-template.workspace = true - -[build-dependencies] -substrate-wasm-builder = { optional = true, workspace = true, default-features = true } - -[features] -default = ["std"] -std = [ - "codec/std", - "scale-info/std", - - "frame-executive/std", - "frame-support/std", - "frame-system-benchmarking?/std", - "frame-system-rpc-runtime-api/std", - "frame-system/std", - - "frame-benchmarking?/std", - "frame-try-runtime?/std", - - "pallet-aura/std", - "pallet-balances/std", - "pallet-grandpa/std", - "pallet-sudo/std", - "pallet-template/std", - "pallet-timestamp/std", - "pallet-transaction-payment-rpc-runtime-api/std", - "pallet-transaction-payment/std", - - "sp-api/std", - "sp-block-builder/std", - "sp-consensus-aura/std", - "sp-consensus-grandpa/std", - "sp-core/std", - "sp-genesis-builder/std", - "sp-inherents/std", - "sp-offchain/std", - "sp-runtime/std", - "sp-session/std", - "sp-storage/std", - "sp-transaction-pool/std", - "sp-version/std", - - "substrate-wasm-builder", -] - -runtime-benchmarks = [ - "frame-benchmarking/runtime-benchmarks", - "frame-support/runtime-benchmarks", - "frame-system-benchmarking/runtime-benchmarks", - "frame-system/runtime-benchmarks", - "pallet-balances/runtime-benchmarks", - "pallet-grandpa/runtime-benchmarks", - "pallet-sudo/runtime-benchmarks", - "pallet-template/runtime-benchmarks", - "pallet-timestamp/runtime-benchmarks", - "sp-runtime/runtime-benchmarks", -] - -try-runtime = [ - "frame-executive/try-runtime", - "frame-support/try-runtime", - "frame-system/try-runtime", - "frame-try-runtime/try-runtime", - "pallet-aura/try-runtime", - "pallet-balances/try-runtime", - "pallet-grandpa/try-runtime", - "pallet-sudo/try-runtime", - "pallet-template/try-runtime", - "pallet-timestamp/try-runtime", - "pallet-transaction-payment/try-runtime", - "sp-runtime/try-runtime", -] diff --git a/polkadot-sdk-solochain-template/runtime/build.rs b/polkadot-sdk-solochain-template/runtime/build.rs deleted file mode 100644 index f262c32..0000000 --- a/polkadot-sdk-solochain-template/runtime/build.rs +++ /dev/null @@ -1,6 +0,0 @@ -fn main() { - #[cfg(feature = "std")] - { - substrate_wasm_builder::WasmBuilder::build_using_defaults(); - } -} diff --git a/polkadot-sdk-solochain-template/runtime/src/lib.rs b/polkadot-sdk-solochain-template/runtime/src/lib.rs deleted file mode 100644 index 9de95ac..0000000 --- a/polkadot-sdk-solochain-template/runtime/src/lib.rs +++ /dev/null @@ -1,594 +0,0 @@ -#![cfg_attr(not(feature = "std"), no_std)] - -#[cfg(feature = "std")] -include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); - -extern crate alloc; -use alloc::{vec, vec::Vec}; -use pallet_grandpa::AuthorityId as GrandpaId; -use sp_api::impl_runtime_apis; -use sp_consensus_aura::sr25519::AuthorityId as AuraId; -use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; -use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, - traits::{BlakeTwo256, Block as BlockT, IdentifyAccount, NumberFor, One, Verify}, - transaction_validity::{TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, MultiSignature, -}; -#[cfg(feature = "std")] -use sp_version::NativeVersion; -use sp_version::RuntimeVersion; - -pub use frame_support::{ - construct_runtime, derive_impl, parameter_types, - traits::{ - ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, KeyOwnerProofSystem, Randomness, - StorageInfo, - }, - weights::{ - constants::{ - BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND, - }, - IdentityFee, Weight, - }, - StorageValue, -}; -use frame_support::{ - genesis_builder_helper::{build_state, get_preset}, - traits::VariantCountOf, -}; -pub use frame_system::Call as SystemCall; -pub use pallet_balances::Call as BalancesCall; -pub use pallet_timestamp::Call as TimestampCall; -use pallet_transaction_payment::{ConstFeeMultiplier, FungibleAdapter, Multiplier}; -#[cfg(any(feature = "std", test))] -pub use sp_runtime::BuildStorage; -pub use sp_runtime::{Perbill, Permill}; - -/// Import the template pallet. -pub use pallet_template; - -/// An index to a block. -pub type BlockNumber = u32; - -/// Alias to 512-bit hash when used in the context of a transaction signature on the chain. -pub type Signature = MultiSignature; - -/// Some way of identifying an account on the chain. We intentionally make it equivalent -/// to the public key of our transaction signing scheme. -pub type AccountId = <::Signer as IdentifyAccount>::AccountId; - -/// Balance of an account. -pub type Balance = u128; - -/// Index of a transaction in the chain. -pub type Nonce = u32; - -/// A hash of some data used by the chain. -pub type Hash = sp_core::H256; - -/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know -/// the specifics of the runtime. They can then be made to be agnostic over specific formats -/// of data like extrinsics, allowing for them to continue syncing the network through upgrades -/// to even the core data structures. -pub mod opaque { - use super::*; - - pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; - - /// Opaque block header type. - pub type Header = generic::Header; - /// Opaque block type. - pub type Block = generic::Block; - /// Opaque block identifier type. - pub type BlockId = generic::BlockId; - - impl_opaque_keys! { - pub struct SessionKeys { - pub aura: Aura, - pub grandpa: Grandpa, - } - } -} - -// To learn more about runtime versioning, see: -// https://docs.substrate.io/main-docs/build/upgrade#runtime-versioning -#[sp_version::runtime_version] -pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("solochain-template-runtime"), - impl_name: create_runtime_str!("solochain-template-runtime"), - authoring_version: 1, - // The version of the runtime specification. A full node will not attempt to use its native - // runtime in substitute for the on-chain Wasm runtime unless all of `spec_name`, - // `spec_version`, and `authoring_version` are the same between Wasm and native. - // This value is set to 100 to notify Polkadot-JS App (https://polkadot.js.org/apps) to use - // the compatible custom types. - spec_version: 100, - impl_version: 1, - apis: RUNTIME_API_VERSIONS, - transaction_version: 1, - state_version: 1, -}; - -/// This determines the average expected block time that we are targeting. -/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`. -/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked -/// up by `pallet_aura` to implement `fn slot_duration()`. -/// -/// Change this to adjust the block time. -pub const MILLISECS_PER_BLOCK: u64 = 6000; - -// NOTE: Currently it is not possible to change the slot duration after the chain has started. -// Attempting to do so will brick block production. -pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK; - -// Time is measured by number of blocks. -pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber); -pub const HOURS: BlockNumber = MINUTES * 60; -pub const DAYS: BlockNumber = HOURS * 24; - -/// The version information used to identify this runtime when compiled natively. -#[cfg(feature = "std")] -pub fn native_version() -> NativeVersion { - NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } -} - -const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); - -parameter_types! { - pub const BlockHashCount: BlockNumber = 2400; - pub const Version: RuntimeVersion = VERSION; - /// We allow for 2 seconds of compute with a 6 second average block time. - pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::with_sensible_defaults( - Weight::from_parts(2u64 * WEIGHT_REF_TIME_PER_SECOND, u64::MAX), - NORMAL_DISPATCH_RATIO, - ); - pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength - ::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); - pub const SS58Prefix: u8 = 42; -} - -/// The default types are being injected by [`derive_impl`](`frame_support::derive_impl`) from -/// [`SoloChainDefaultConfig`](`struct@frame_system::config_preludes::SolochainDefaultConfig`), -/// but overridden as needed. -#[derive_impl(frame_system::config_preludes::SolochainDefaultConfig)] -impl frame_system::Config for Runtime { - /// 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). - type BlockLength = BlockLength; - /// The identifier used to distinguish between accounts. - type AccountId = AccountId; - /// The type for storing how many extrinsics an account has signed. - type Nonce = Nonce; - /// The type for hashing blocks and tries. - type Hash = Hash; - /// Maximum number of block number to block hash mappings to keep (oldest pruned first). - type BlockHashCount = BlockHashCount; - /// The weight of database operations that the runtime can invoke. - type DbWeight = RocksDbWeight; - /// Version of the runtime. - type Version = Version; - /// The data to be stored in an account. - type AccountData = pallet_balances::AccountData; - /// This is used as an identifier of the chain. 42 is the generic substrate prefix. - type SS58Prefix = SS58Prefix; - type MaxConsumers = frame_support::traits::ConstU32<16>; -} - -impl pallet_aura::Config for Runtime { - type AuthorityId = AuraId; - type DisabledValidators = (); - type MaxAuthorities = ConstU32<32>; - type AllowMultipleBlocksPerSlot = ConstBool; - type SlotDuration = pallet_aura::MinimumPeriodTimesTwo; -} - -impl pallet_grandpa::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - - type WeightInfo = (); - type MaxAuthorities = ConstU32<32>; - type MaxNominators = ConstU32<0>; - type MaxSetIdSessionEntries = ConstU64<0>; - - type KeyOwnerProof = sp_core::Void; - type EquivocationReportSystem = (); -} - -impl pallet_timestamp::Config for Runtime { - /// A timestamp: milliseconds since the unix epoch. - type Moment = u64; - type OnTimestampSet = Aura; - type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>; - type WeightInfo = (); -} - -/// Existential deposit. -pub const EXISTENTIAL_DEPOSIT: u128 = 500; - -impl pallet_balances::Config for Runtime { - type MaxLocks = ConstU32<50>; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - /// The type for recording an account's balance. - type Balance = Balance; - /// The ubiquitous event type. - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU128; - type AccountStore = System; - type WeightInfo = pallet_balances::weights::SubstrateWeight; - type FreezeIdentifier = RuntimeFreezeReason; - type MaxFreezes = VariantCountOf; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeHoldReason; -} - -parameter_types! { - pub FeeMultiplier: Multiplier = Multiplier::one(); -} - -impl pallet_transaction_payment::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type OnChargeTransaction = FungibleAdapter; - type OperationalFeeMultiplier = ConstU8<5>; - type WeightToFee = IdentityFee; - type LengthToFee = IdentityFee; - type FeeMultiplierUpdate = ConstFeeMultiplier; -} - -impl pallet_sudo::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type RuntimeCall = RuntimeCall; - type WeightInfo = pallet_sudo::weights::SubstrateWeight; -} - -/// Configure the pallet-template in pallets/template. -impl pallet_template::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type WeightInfo = pallet_template::weights::SubstrateWeight; -} - -// Create the runtime by composing the FRAME pallets that were previously configured. -#[frame_support::runtime] -mod runtime { - #[runtime::runtime] - #[runtime::derive( - RuntimeCall, - RuntimeEvent, - RuntimeError, - RuntimeOrigin, - RuntimeFreezeReason, - RuntimeHoldReason, - RuntimeSlashReason, - RuntimeLockId, - RuntimeTask - )] - pub struct Runtime; - - #[runtime::pallet_index(0)] - pub type System = frame_system; - - #[runtime::pallet_index(1)] - pub type Timestamp = pallet_timestamp; - - #[runtime::pallet_index(2)] - pub type Aura = pallet_aura; - - #[runtime::pallet_index(3)] - pub type Grandpa = pallet_grandpa; - - #[runtime::pallet_index(4)] - pub type Balances = pallet_balances; - - #[runtime::pallet_index(5)] - pub type TransactionPayment = pallet_transaction_payment; - - #[runtime::pallet_index(6)] - pub type Sudo = pallet_sudo; - - // Include the custom logic from the pallet-template in the runtime. - #[runtime::pallet_index(7)] - pub type TemplateModule = pallet_template; -} - -/// The address format for describing accounts. -pub type Address = sp_runtime::MultiAddress; -/// Block header type as expected by this runtime. -pub type Header = generic::Header; -/// Block type as expected by this runtime. -pub type Block = generic::Block; -/// The SignedExtension to the basic transaction logic. -pub type SignedExtra = ( - frame_system::CheckNonZeroSender, - frame_system::CheckSpecVersion, - frame_system::CheckTxVersion, - frame_system::CheckGenesis, - frame_system::CheckEra, - frame_system::CheckNonce, - frame_system::CheckWeight, - pallet_transaction_payment::ChargeTransactionPayment, -); - -/// All migrations of the runtime, aside from the ones declared in the pallets. -/// -/// This can be a tuple of types, each implementing `OnRuntimeUpgrade`. -#[allow(unused_parens)] -type Migrations = (); - -/// Unchecked extrinsic type as expected by this runtime. -pub type UncheckedExtrinsic = - generic::UncheckedExtrinsic; -/// The payload being signed in transactions. -pub type SignedPayload = generic::SignedPayload; -/// Executive: handles dispatch to the various modules. -pub type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext, - Runtime, - AllPalletsWithSystem, - Migrations, ->; - -#[cfg(feature = "runtime-benchmarks")] -mod benches { - frame_benchmarking::define_benchmarks!( - [frame_benchmarking, BaselineBench::] - [frame_system, SystemBench::] - [pallet_balances, Balances] - [pallet_timestamp, Timestamp] - [pallet_sudo, Sudo] - [pallet_template, TemplateModule] - ); -} - -impl_runtime_apis! { - impl sp_api::Core for Runtime { - fn version() -> RuntimeVersion { - VERSION - } - - fn execute_block(block: Block) { - Executive::execute_block(block); - } - - fn initialize_block(header: &::Header) -> sp_runtime::ExtrinsicInclusionMode { - Executive::initialize_block(header) - } - } - - impl sp_api::Metadata for Runtime { - fn metadata() -> OpaqueMetadata { - OpaqueMetadata::new(Runtime::metadata().into()) - } - - fn metadata_at_version(version: u32) -> Option { - Runtime::metadata_at_version(version) - } - - fn metadata_versions() -> Vec { - Runtime::metadata_versions() - } - } - - impl sp_block_builder::BlockBuilder for Runtime { - fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { - Executive::apply_extrinsic(extrinsic) - } - - fn finalize_block() -> ::Header { - Executive::finalize_block() - } - - fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { - data.create_extrinsics() - } - - fn check_inherents( - block: Block, - data: sp_inherents::InherentData, - ) -> sp_inherents::CheckInherentsResult { - data.check_extrinsics(&block) - } - } - - impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { - fn validate_transaction( - source: TransactionSource, - tx: ::Extrinsic, - block_hash: ::Hash, - ) -> TransactionValidity { - Executive::validate_transaction(source, tx, block_hash) - } - } - - impl sp_offchain::OffchainWorkerApi for Runtime { - fn offchain_worker(header: &::Header) { - Executive::offchain_worker(header) - } - } - - impl sp_consensus_aura::AuraApi for Runtime { - fn slot_duration() -> sp_consensus_aura::SlotDuration { - sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) - } - - fn authorities() -> Vec { - pallet_aura::Authorities::::get().into_inner() - } - } - - impl sp_session::SessionKeys for Runtime { - fn generate_session_keys(seed: Option>) -> Vec { - opaque::SessionKeys::generate(seed) - } - - fn decode_session_keys( - encoded: Vec, - ) -> Option, KeyTypeId)>> { - opaque::SessionKeys::decode_into_raw_public_keys(&encoded) - } - } - - impl sp_consensus_grandpa::GrandpaApi for Runtime { - fn grandpa_authorities() -> sp_consensus_grandpa::AuthorityList { - Grandpa::grandpa_authorities() - } - - fn current_set_id() -> sp_consensus_grandpa::SetId { - Grandpa::current_set_id() - } - - fn submit_report_equivocation_unsigned_extrinsic( - _equivocation_proof: sp_consensus_grandpa::EquivocationProof< - ::Hash, - NumberFor, - >, - _key_owner_proof: sp_consensus_grandpa::OpaqueKeyOwnershipProof, - ) -> Option<()> { - None - } - - fn generate_key_ownership_proof( - _set_id: sp_consensus_grandpa::SetId, - _authority_id: GrandpaId, - ) -> Option { - // NOTE: this is the only implementation possible since we've - // defined our key owner proof type as a bottom type (i.e. a type - // with no values). - None - } - } - - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Nonce { - System::account_nonce(account) - } - } - - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { - fn query_info( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { - TransactionPayment::query_info(uxt, len) - } - fn query_fee_details( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_fee_details(uxt, len) - } - fn query_weight_to_fee(weight: Weight) -> Balance { - TransactionPayment::weight_to_fee(weight) - } - fn query_length_to_fee(length: u32) -> Balance { - TransactionPayment::length_to_fee(length) - } - } - - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi - for Runtime - { - fn query_call_info( - call: RuntimeCall, - len: u32, - ) -> pallet_transaction_payment::RuntimeDispatchInfo { - TransactionPayment::query_call_info(call, len) - } - fn query_call_fee_details( - call: RuntimeCall, - len: u32, - ) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_call_fee_details(call, len) - } - fn query_weight_to_fee(weight: Weight) -> Balance { - TransactionPayment::weight_to_fee(weight) - } - fn query_length_to_fee(length: u32) -> Balance { - TransactionPayment::length_to_fee(length) - } - } - - #[cfg(feature = "runtime-benchmarks")] - impl frame_benchmarking::Benchmark for Runtime { - fn benchmark_metadata(extra: bool) -> ( - Vec, - Vec, - ) { - use frame_benchmarking::{baseline, Benchmarking, BenchmarkList}; - use frame_support::traits::StorageInfoTrait; - use frame_system_benchmarking::Pallet as SystemBench; - use baseline::Pallet as BaselineBench; - - let mut list = Vec::::new(); - list_benchmarks!(list, extra); - - let storage_info = AllPalletsWithSystem::storage_info(); - - (list, storage_info) - } - - fn dispatch_benchmark( - config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { - use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch}; - use sp_storage::TrackedStorageKey; - use frame_system_benchmarking::Pallet as SystemBench; - use baseline::Pallet as BaselineBench; - - impl frame_system_benchmarking::Config for Runtime {} - impl baseline::Config for Runtime {} - - use frame_support::traits::WhitelistedStorageKeys; - let whitelist: Vec = AllPalletsWithSystem::whitelisted_storage_keys(); - - let mut batches = Vec::::new(); - let params = (&config, &whitelist); - add_benchmarks!(params, batches); - - Ok(batches) - } - } - - #[cfg(feature = "try-runtime")] - impl frame_try_runtime::TryRuntime for Runtime { - fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { - // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to - // have a backtrace here. If any of the pre/post migration checks fail, we shall stop - // right here and right now. - let weight = Executive::try_runtime_upgrade(checks).unwrap(); - (weight, BlockWeights::get().max_block) - } - - fn execute_block( - block: Block, - state_root_check: bool, - signature_check: bool, - select: frame_try_runtime::TryStateSelect - ) -> Weight { - // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to - // have a backtrace here. - Executive::try_execute_block(block, state_root_check, signature_check, select).expect("execute-block failed") - } - } - - impl sp_genesis_builder::GenesisBuilder for Runtime { - fn build_state(config: Vec) -> sp_genesis_builder::Result { - build_state::(config) - } - - fn get_preset(id: &Option) -> Option> { - get_preset::(id, |_| None) - } - - fn preset_names() -> Vec { - vec![] - } - } -} diff --git a/substrate-node-template b/substrate-node-template new file mode 160000 index 0000000..d89bff8 --- /dev/null +++ b/substrate-node-template @@ -0,0 +1 @@ +Subproject commit d89bff8292215d29798e2f99df7e1034af81ebf0