From 69f2516b26b2014148aa454c85f5b5428e20cdcc Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Mon, 9 Oct 2023 18:07:09 +0200 Subject: [PATCH 01/12] Add basics for reward-distribution pallet --- Cargo.toml | 1 + pallets/reward-distribution/Cargo.toml | 42 +++++ pallets/reward-distribution/README.md | 39 +++++ .../reward-distribution/src/benchmarking.rs | 38 +++++ .../src/default_weights.rs | 108 ++++++++++++ pallets/reward-distribution/src/lib.rs | 155 ++++++++++++++++++ pallets/reward-distribution/src/mock.rs | 91 ++++++++++ pallets/reward-distribution/src/tests.rs | 77 +++++++++ 8 files changed, 551 insertions(+) create mode 100644 pallets/reward-distribution/Cargo.toml create mode 100644 pallets/reward-distribution/README.md create mode 100644 pallets/reward-distribution/src/benchmarking.rs create mode 100644 pallets/reward-distribution/src/default_weights.rs create mode 100644 pallets/reward-distribution/src/lib.rs create mode 100644 pallets/reward-distribution/src/mock.rs create mode 100644 pallets/reward-distribution/src/tests.rs diff --git a/Cargo.toml b/Cargo.toml index a23de9ab2..d3b574f4c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ members = [ "pallets/nomination", "pallets/oracle", "pallets/reward", + "pallets/reward-distribution", "pallets/staking", "pallets/stellar-relay", "pallets/vault-registry", diff --git a/pallets/reward-distribution/Cargo.toml b/pallets/reward-distribution/Cargo.toml new file mode 100644 index 000000000..d66d376c9 --- /dev/null +++ b/pallets/reward-distribution/Cargo.toml @@ -0,0 +1,42 @@ +[package] +name = "reward-distribution" +authors = ["Pendulum Chain "] +version = "0.1.0" +edition = "2021" + +[dependencies] +codec = {package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive", "max-encoded-len"]} +scale-info = {version = "2.2.0", default-features = false, features = ["derive"]} +serde = {version = "1.0.130", default-features = false, features = ["derive"], optional = true} + +# Substrate dependencies +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false } +sp-arithmetic = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false } + +frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false } +frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false, optional = true } + +[features] +default = ["std"] +std = [ + "serde", + "codec/std", + "scale-info/std", + "sp-arithmetic/std", + "sp-core/std", + "sp-io/std", + "sp-runtime/std", + "sp-std/std", + "frame-support/std", + "frame-system/std", + "frame-benchmarking/std", +] +runtime-benchmarks = [ + "frame-benchmarking", + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", +] \ No newline at end of file diff --git a/pallets/reward-distribution/README.md b/pallets/reward-distribution/README.md new file mode 100644 index 000000000..df3f480d0 --- /dev/null +++ b/pallets/reward-distribution/README.md @@ -0,0 +1,39 @@ +# Reward distribution pallet + +This pallet contains the logic to distribute rewards to the Spacewalk vault clients and their nominators. + +## Testing + +To run the tests use: + +```bash +cargo test --package reward-distribution --features runtime-benchmarks +``` + +## Benchmarking + +Build the node with the `runtime-benchmarks` feature: + +```bash +cargo build --package spacewalk-standalone --release --features runtime-benchmarks +```bash + +```bash +# Show benchmarks for this pallet +./target/release/spacewalk-standalone benchmark pallet -p reward-distribution -e '*' --list +```bash + +Run the benchmarking for a pallet: + +```bash +./target/release/spacewalk-standalone benchmark pallet \ +--chain=dev \ +--pallet=reward-distribution \ +--extrinsic='*' \ +--steps=100 \ +--repeat=10 \ +--wasm-execution=compiled \ +--output=pallets/reward-distribution/src/default_weights.rs \ +--template=./.maintain/frame-weight-template.hbs +```bash + diff --git a/pallets/reward-distribution/src/benchmarking.rs b/pallets/reward-distribution/src/benchmarking.rs new file mode 100644 index 000000000..2ef002d15 --- /dev/null +++ b/pallets/reward-distribution/src/benchmarking.rs @@ -0,0 +1,38 @@ +use super::*; +use frame_benchmarking::v2::{benchmarks, impl_benchmark_test_suite, Linear}; +use frame_system::RawOrigin; +use sp_std::vec; + +#[allow(unused)] +use super::Pallet as ClientsInfo; + +#[benchmarks] +pub mod benchmarks { + use super::*; + + #[benchmark] + fn set_current_client_release(n: Linear<0, 255>, u: Linear<0, 255>) { + let name = BoundedVec::try_from(vec![0; n as usize]).unwrap(); + let uri = BoundedVec::try_from(vec![0; u as usize]).unwrap(); + let client_release = ClientRelease { uri, checksum: Default::default() }; + + #[extrinsic_call] + _(RawOrigin::Root, name.clone(), client_release.clone()); + + assert_eq!(CurrentClientReleases::::get(name), Some(client_release)); + } + + #[benchmark] + fn set_pending_client_release(n: Linear<0, 255>, u: Linear<0, 255>) { + let name = BoundedVec::try_from(vec![0; n as usize]).unwrap(); + let uri = BoundedVec::try_from(vec![0; u as usize]).unwrap(); + let client_release = ClientRelease { uri, checksum: Default::default() }; + + #[extrinsic_call] + _(RawOrigin::Root, name.clone(), client_release.clone()); + + assert_eq!(PendingClientReleases::::get(name), Some(client_release)); + } + + impl_benchmark_test_suite!(ClientsInfo, crate::mock::ExtBuilder::build(), crate::mock::Test); +} diff --git a/pallets/reward-distribution/src/default_weights.rs b/pallets/reward-distribution/src/default_weights.rs new file mode 100644 index 000000000..c50d2ed97 --- /dev/null +++ b/pallets/reward-distribution/src/default_weights.rs @@ -0,0 +1,108 @@ + +//! Autogenerated weights for clients_info +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-09-13, STEPS: `100`, REPEAT: `10`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `pop-os`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/release/spacewalk-standalone +// benchmark +// pallet +// --chain=dev +// --pallet=clients-info +// --extrinsic=* +// --steps=100 +// --repeat=10 +// --wasm-execution=compiled +// --output=pallets/clients-info/src/default_weights.rs +// --template=./.maintain/frame-weight-template.hbs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use core::marker::PhantomData; + +/// Weight functions needed for clients_info. +pub trait WeightInfo { + fn set_current_client_release(n: u32, u: u32, ) -> Weight; + fn set_pending_client_release(n: u32, u: u32, ) -> Weight; +} + +/// Weights for clients_info using the Substrate node and recommended hardware. +pub struct SubstrateWeight(PhantomData); +impl WeightInfo for SubstrateWeight { + /// Storage: ClientsInfo CurrentClientReleases (r:0 w:1) + /// Proof: ClientsInfo CurrentClientReleases (max_values: None, max_size: Some(562), added: 3037, mode: MaxEncodedLen) + /// The range of component `n` is `[0, 255]`. + /// The range of component `u` is `[0, 255]`. + fn set_current_client_release(n: u32, u: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_607_000 picoseconds. + Weight::from_parts(9_560_259, 0) + // Standard Error: 845 + .saturating_add(Weight::from_parts(2_586, 0).saturating_mul(n.into())) + // Standard Error: 845 + .saturating_add(Weight::from_parts(689, 0).saturating_mul(u.into())) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: ClientsInfo PendingClientReleases (r:0 w:1) + /// Proof: ClientsInfo PendingClientReleases (max_values: None, max_size: Some(562), added: 3037, mode: MaxEncodedLen) + /// The range of component `n` is `[0, 255]`. + /// The range of component `u` is `[0, 255]`. + fn set_pending_client_release(n: u32, u: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_557_000 picoseconds. + Weight::from_parts(9_238_573, 0) + // Standard Error: 840 + .saturating_add(Weight::from_parts(3_011, 0).saturating_mul(n.into())) + // Standard Error: 840 + .saturating_add(Weight::from_parts(892, 0).saturating_mul(u.into())) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } +} + +// For backwards compatibility and tests +impl WeightInfo for () { + /// Storage: ClientsInfo CurrentClientReleases (r:0 w:1) + /// Proof: ClientsInfo CurrentClientReleases (max_values: None, max_size: Some(562), added: 3037, mode: MaxEncodedLen) + /// The range of component `n` is `[0, 255]`. + /// The range of component `u` is `[0, 255]`. + fn set_current_client_release(n: u32, u: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_607_000 picoseconds. + Weight::from_parts(9_560_259, 0) + // Standard Error: 845 + .saturating_add(Weight::from_parts(2_586, 0).saturating_mul(n.into())) + // Standard Error: 845 + .saturating_add(Weight::from_parts(689, 0).saturating_mul(u.into())) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: ClientsInfo PendingClientReleases (r:0 w:1) + /// Proof: ClientsInfo PendingClientReleases (max_values: None, max_size: Some(562), added: 3037, mode: MaxEncodedLen) + /// The range of component `n` is `[0, 255]`. + /// The range of component `u` is `[0, 255]`. + fn set_pending_client_release(n: u32, u: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_557_000 picoseconds. + Weight::from_parts(9_238_573, 0) + // Standard Error: 840 + .saturating_add(Weight::from_parts(3_011, 0).saturating_mul(n.into())) + // Standard Error: 840 + .saturating_add(Weight::from_parts(892, 0).saturating_mul(u.into())) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } +} \ No newline at end of file diff --git a/pallets/reward-distribution/src/lib.rs b/pallets/reward-distribution/src/lib.rs new file mode 100644 index 000000000..218d8274d --- /dev/null +++ b/pallets/reward-distribution/src/lib.rs @@ -0,0 +1,155 @@ +//! # Reward Distribution Module +//! A module for distributing rewards to Spacewalk vaults and their nominators. + +#![deny(warnings)] +#![cfg_attr(test, feature(proc_macro_hygiene))] +#![cfg_attr(not(feature = "std"), no_std)] + +use codec::{Decode, Encode, MaxEncodedLen}; +use scale_info::TypeInfo; + +mod default_weights; + +pub use default_weights::{SubstrateWeight, WeightInfo}; + +use frame_support::{dispatch::DispatchResult, traits::Get, transactional, BoundedVec}; + +#[cfg(feature = "runtime-benchmarks")] +mod benchmarking; + +#[cfg(test)] +mod mock; + +type NameOf = BoundedVec::MaxNameLength>; +type UriOf = BoundedVec::MaxUriLength>; + +#[derive(Encode, Decode, Eq, PartialEq, Clone, Default, TypeInfo, Debug, MaxEncodedLen)] +pub struct ClientRelease { + /// URI to the client release binary. + pub uri: Uri, + /// The SHA256 checksum of the client binary. + pub checksum: Hash, +} + +pub use pallet::*; + +#[frame_support::pallet] +pub mod pallet { + use crate::*; + + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config { + /// The overarching event type. + type RuntimeEvent: From> + + Into<::RuntimeEvent> + + IsType<::RuntimeEvent>; + + /// Weight information for the extrinsics in this module. + type WeightInfo: WeightInfo; + + /// The maximum length of a client name. + #[pallet::constant] + type MaxNameLength: Get; + + /// The maximum length of a client URI. + #[pallet::constant] + type MaxUriLength: Get; + } + + #[pallet::hooks] + impl Hooks> for Pallet { + fn on_runtime_upgrade() -> frame_support::weights::Weight { + crate::upgrade_client_releases::try_upgrade_current_client_releases::() + } + } + + #[pallet::call] + impl Pallet { + /// Sets the current client release version, in case of a bug fix or patch. + /// + /// # Arguments + /// * `client_name` - raw byte string representation of the client name (e.g. `b"vault"`) + /// * `release` - The release information for the given `client_name` + #[pallet::call_index(0)] + #[pallet::weight(::WeightInfo::set_current_client_release(T::MaxNameLength::get(), T::MaxUriLength::get()))] + #[transactional] + pub fn set_current_client_release( + origin: OriginFor, + client_name: NameOf, + release: ClientRelease, T::Hash>, + ) -> DispatchResult { + ensure_root(origin)?; + CurrentClientReleases::::insert(client_name, release.clone()); + Self::deposit_event(Event::::ApplyClientRelease { release }); + Ok(()) + } + + /// Sets the pending client release version. To be batched alongside the + /// `parachainSystem.authorizeUpgrade` Cumulus call. + /// Clients include the vault, oracle, and faucet. + /// + /// # Arguments + /// * `client_name` - raw byte string representation of the client name (e.g. `b"vault"`) + /// * `release` - The release information for the given `client_name` + #[pallet::call_index(1)] + #[pallet::weight(::WeightInfo::set_pending_client_release(T::MaxNameLength::get(), T::MaxUriLength::get()))] + #[transactional] + pub fn set_pending_client_release( + origin: OriginFor, + client_name: NameOf, + release: ClientRelease, T::Hash>, + ) -> DispatchResult { + ensure_root(origin)?; + PendingClientReleases::::insert(client_name, release.clone()); + Self::deposit_event(Event::::NotifyClientRelease { release }); + Ok(()) + } + } + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + NotifyClientRelease { release: ClientRelease, T::Hash> }, + ApplyClientRelease { release: ClientRelease, T::Hash> }, + } + + #[pallet::error] + pub enum Error {} + + /// Mapping of client name (string literal represented as bytes) to its release details. + #[pallet::storage] + #[pallet::getter(fn current_client_release)] + pub(super) type CurrentClientReleases = + StorageMap<_, Blake2_128Concat, NameOf, ClientRelease, T::Hash>, OptionQuery>; + + /// Mapping of client name (string literal represented as bytes) to its pending release details. + #[pallet::storage] + #[pallet::getter(fn pending_client_release)] + pub(super) type PendingClientReleases = + StorageMap<_, Blake2_128Concat, NameOf, ClientRelease, T::Hash>, OptionQuery>; +} + +pub mod upgrade_client_releases { + + use crate::*; + use frame_support::weights::Weight; + + /// For each pending client release, set the current release to that. + /// The pending release entry is removed. + pub fn try_upgrade_current_client_releases() -> Weight { + let mut reads = 0; + for (key, release) in PendingClientReleases::::drain() { + //log::info!("Upgrading client release for key {:?}", key); + CurrentClientReleases::::insert(key, release.clone()); + Pallet::::deposit_event(Event::::ApplyClientRelease { release }); + reads += 1; + } + T::DbWeight::get().reads_writes(reads, reads * 2) + } +} diff --git a/pallets/reward-distribution/src/mock.rs b/pallets/reward-distribution/src/mock.rs new file mode 100644 index 000000000..4fb8c84b3 --- /dev/null +++ b/pallets/reward-distribution/src/mock.rs @@ -0,0 +1,91 @@ +use crate as clients_info; +use crate::Config; +use frame_support::{ + parameter_types, + traits::{ConstU32, Everything}, +}; +use sp_core::H256; +use sp_runtime::{ + generic::Header as GenericHeader, + traits::{BlakeTwo256, IdentityLookup}, +}; + +type Header = GenericHeader; +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; + +// Configure a mock runtime to test the pallet. +frame_support::construct_runtime!( + pub enum Test where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Storage, Config, Event}, + ClientsInfo: clients_info::{Pallet, Call, Storage, Event} + } +); + +pub type AccountId = u64; +pub type BlockNumber = u64; +pub type Index = u64; + +parameter_types! { + pub const BlockHashCount: u64 = 250; + pub const SS58Prefix: u8 = 42; +} + +impl frame_system::Config for Test { + type BaseCallFilter = Everything; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Index = Index; + type BlockNumber = BlockNumber; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Header = Header; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = BlockHashCount; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = SS58Prefix; + type OnSetCode = (); + type MaxConsumers = ConstU32<16>; +} + +impl Config for Test { + type RuntimeEvent = RuntimeEvent; + type WeightInfo = (); + type MaxNameLength = ConstU32<255>; + type MaxUriLength = ConstU32<255>; +} + +pub struct ExtBuilder; + +impl ExtBuilder { + pub fn build() -> sp_io::TestExternalities { + let storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + + storage.into() + } +} + +#[allow(dead_code)] +pub fn run_test(test: T) +where + T: FnOnce(), +{ + ExtBuilder::build().execute_with(|| { + System::set_block_number(1); + test(); + }); +} diff --git a/pallets/reward-distribution/src/tests.rs b/pallets/reward-distribution/src/tests.rs new file mode 100644 index 000000000..025ba94e0 --- /dev/null +++ b/pallets/reward-distribution/src/tests.rs @@ -0,0 +1,77 @@ +use crate::mock::*; +use sp_core::H256; +use sp_std::vec; +use std::collections::HashMap; +use upgrade_client_releases::*; + +#[cfg(test)] +#[test] +fn test_client_pending_release_migration() { + run_test(|| { + let vault_key = b"vault".to_vec(); + + let pre_migration_pending_releases: HashMap<_, _> = vec![( + vault_key.clone(), + ClientRelease { + uri: BoundedVec::try_from(b"https://github.com/pendulum-chain/spacewalk".to_vec()) + .unwrap(), + checksum: H256::default(), + }, + )] + .into_iter() + .collect(); + pre_migration_pending_releases.iter().for_each(|(key, value)| { + PendingClientReleases::::insert( + BoundedVec::try_from(key.clone()).unwrap(), + value.clone(), + ); + }); + + let pre_migration_current_releases: HashMap<_, _> = vec![( + vault_key.clone(), + ClientRelease { + uri: BoundedVec::try_from(b"https://github.com/pendulum-chain/spacewalk".to_vec()) + .unwrap(), + checksum: H256::default(), + }, + )] + .into_iter() + .collect(); + pre_migration_current_releases.iter().for_each(|(key, value)| { + CurrentClientReleases::::insert( + BoundedVec::try_from(key.clone()).unwrap(), + value.clone(), + ); + }); + + try_upgrade_current_client_releases::(); + + let pending_releases = PendingClientReleases::::iter_values().collect::>(); + assert_eq!(pending_releases.is_empty(), true); + + let current_releases = CurrentClientReleases::::iter() + .map(|(key, value)| (key.to_vec(), value)) + .collect::>(); + assert_eq!( + current_releases.get(&vault_key), + pre_migration_pending_releases.get(&vault_key) + ); + }); +} + +#[cfg(test)] +#[test] +fn test_decode_bounded_vec() { + run_test(|| { + let key = vec![0; 255]; + + CurrentClientReleases::::insert( + key.clone(), + ClientRelease { uri: vec![1; 255], checksum: H256::default() }, + ); + + let client_release = + crate::CurrentClientReleases::::get(BoundedVec::try_from(key).unwrap()); + assert_eq!(client_release.map(|c| c.uri.to_vec()), Some(vec![1; 255])); + }); +} From 3ffb25f0f9a9ea05da7766e7b0c7b237272f5e9b Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Mon, 9 Oct 2023 18:27:58 +0200 Subject: [PATCH 02/12] Finish base logic --- Cargo.lock | 18 ++++ pallets/reward-distribution/Cargo.toml | 9 +- pallets/reward-distribution/src/lib.rs | 130 +++++++---------------- pallets/reward-distribution/src/types.rs | 5 + 4 files changed, 68 insertions(+), 94 deletions(-) create mode 100644 pallets/reward-distribution/src/types.rs diff --git a/Cargo.lock b/Cargo.lock index c56b549ab..79df89d36 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6838,6 +6838,24 @@ dependencies = [ "spacewalk-primitives", ] +[[package]] +name = "reward-distribution" +version = "0.1.0" +dependencies = [ + "frame-benchmarking", + "frame-support", + "frame-system", + "parity-scale-codec", + "scale-info", + "security", + "serde", + "sp-arithmetic", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", +] + [[package]] name = "rfc6979" version = "0.3.1" diff --git a/pallets/reward-distribution/Cargo.toml b/pallets/reward-distribution/Cargo.toml index d66d376c9..8b5d0a984 100644 --- a/pallets/reward-distribution/Cargo.toml +++ b/pallets/reward-distribution/Cargo.toml @@ -5,9 +5,9 @@ version = "0.1.0" edition = "2021" [dependencies] -codec = {package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive", "max-encoded-len"]} -scale-info = {version = "2.2.0", default-features = false, features = ["derive"]} -serde = {version = "1.0.130", default-features = false, features = ["derive"], optional = true} +codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive", "max-encoded-len"] } +scale-info = { version = "2.2.0", default-features = false, features = ["derive"] } +serde = { version = "1.0.130", default-features = false, features = ["derive"], optional = true } # Substrate dependencies sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false } @@ -20,6 +20,8 @@ frame-support = { git = "https://github.com/paritytech/substrate", branch = "pol frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false } frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false, optional = true } +security = { path = "../security", default-features = false } + [features] default = ["std"] std = [ @@ -34,6 +36,7 @@ std = [ "frame-support/std", "frame-system/std", "frame-benchmarking/std", + "security/std", ] runtime-benchmarks = [ "frame-benchmarking", diff --git a/pallets/reward-distribution/src/lib.rs b/pallets/reward-distribution/src/lib.rs index 218d8274d..165b0dbf8 100644 --- a/pallets/reward-distribution/src/lib.rs +++ b/pallets/reward-distribution/src/lib.rs @@ -12,7 +12,13 @@ mod default_weights; pub use default_weights::{SubstrateWeight, WeightInfo}; -use frame_support::{dispatch::DispatchResult, traits::Get, transactional, BoundedVec}; +use crate::types::{AccountIdOf, BalanceOf}; +use frame_support::{ + dispatch::DispatchResult, + traits::{Currency, Get}, + transactional, BoundedVec, +}; +use sp_arithmetic::Perquintill; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; @@ -20,16 +26,7 @@ mod benchmarking; #[cfg(test)] mod mock; -type NameOf = BoundedVec::MaxNameLength>; -type UriOf = BoundedVec::MaxUriLength>; - -#[derive(Encode, Decode, Eq, PartialEq, Clone, Default, TypeInfo, Debug, MaxEncodedLen)] -pub struct ClientRelease { - /// URI to the client release binary. - pub uri: Uri, - /// The SHA256 checksum of the client binary. - pub checksum: Hash, -} +mod types; pub use pallet::*; @@ -44,7 +41,7 @@ pub mod pallet { pub struct Pallet(_); #[pallet::config] - pub trait Config: frame_system::Config { + pub trait Config: frame_system::Config + security::Config { /// The overarching event type. type RuntimeEvent: From> + Into<::RuntimeEvent> @@ -53,103 +50,54 @@ pub mod pallet { /// Weight information for the extrinsics in this module. type WeightInfo: WeightInfo; - /// The maximum length of a client name. - #[pallet::constant] - type MaxNameLength: Get; + /// The currency trait. + type Currency: Currency>; - /// The maximum length of a client URI. + /// Defines the interval (in number of blocks) at which the reward per block decays. #[pallet::constant] - type MaxUriLength: Get; - } - - #[pallet::hooks] - impl Hooks> for Pallet { - fn on_runtime_upgrade() -> frame_support::weights::Weight { - crate::upgrade_client_releases::try_upgrade_current_client_releases::() - } - } - - #[pallet::call] - impl Pallet { - /// Sets the current client release version, in case of a bug fix or patch. - /// - /// # Arguments - /// * `client_name` - raw byte string representation of the client name (e.g. `b"vault"`) - /// * `release` - The release information for the given `client_name` - #[pallet::call_index(0)] - #[pallet::weight(::WeightInfo::set_current_client_release(T::MaxNameLength::get(), T::MaxUriLength::get()))] - #[transactional] - pub fn set_current_client_release( - origin: OriginFor, - client_name: NameOf, - release: ClientRelease, T::Hash>, - ) -> DispatchResult { - ensure_root(origin)?; - CurrentClientReleases::::insert(client_name, release.clone()); - Self::deposit_event(Event::::ApplyClientRelease { release }); - Ok(()) - } + type DecayInterval: Get; - /// Sets the pending client release version. To be batched alongside the - /// `parachainSystem.authorizeUpgrade` Cumulus call. - /// Clients include the vault, oracle, and faucet. - /// - /// # Arguments - /// * `client_name` - raw byte string representation of the client name (e.g. `b"vault"`) - /// * `release` - The release information for the given `client_name` - #[pallet::call_index(1)] - #[pallet::weight(::WeightInfo::set_pending_client_release(T::MaxNameLength::get(), T::MaxUriLength::get()))] - #[transactional] - pub fn set_pending_client_release( - origin: OriginFor, - client_name: NameOf, - release: ClientRelease, T::Hash>, - ) -> DispatchResult { - ensure_root(origin)?; - PendingClientReleases::::insert(client_name, release.clone()); - Self::deposit_event(Event::::NotifyClientRelease { release }); - Ok(()) - } + /// Defines the rate at which the reward per block decays. + #[pallet::constant] + type DecayRate: Get; } #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - NotifyClientRelease { release: ClientRelease, T::Hash> }, - ApplyClientRelease { release: ClientRelease, T::Hash> }, + /// A new RewardPerBlock value has been set. + RewardsPerBlockAdapted(BalanceOf), } #[pallet::error] pub enum Error {} - /// Mapping of client name (string literal represented as bytes) to its release details. + /// Reward per block. #[pallet::storage] - #[pallet::getter(fn current_client_release)] - pub(super) type CurrentClientReleases = - StorageMap<_, Blake2_128Concat, NameOf, ClientRelease, T::Hash>, OptionQuery>; + #[pallet::getter(fn reward_per_block)] + pub type RewardPerBlock = StorageValue<_, BalanceOf, OptionQuery>; - /// Mapping of client name (string literal represented as bytes) to its pending release details. #[pallet::storage] - #[pallet::getter(fn pending_client_release)] - pub(super) type PendingClientReleases = - StorageMap<_, Blake2_128Concat, NameOf, ClientRelease, T::Hash>, OptionQuery>; -} + #[pallet::getter(fn rewards_adapted_at)] + pub(super) type RewardsAdaptedAt = StorageValue<_, BlockNumberFor, OptionQuery>; -pub mod upgrade_client_releases { + #[pallet::call] + impl Pallet { + /// Sets the reward per block. + #[pallet::call_index(0)] + #[pallet::weight(::WeightInfo::set_rewards_per_block())] + #[transactional] + pub fn set_rewards_per_block( + origin: OriginFor, + new_rewards_per_block: BalanceOf, + ) -> DispatchResult { + ensure_root(origin)?; - use crate::*; - use frame_support::weights::Weight; - - /// For each pending client release, set the current release to that. - /// The pending release entry is removed. - pub fn try_upgrade_current_client_releases() -> Weight { - let mut reads = 0; - for (key, release) in PendingClientReleases::::drain() { - //log::info!("Upgrading client release for key {:?}", key); - CurrentClientReleases::::insert(key, release.clone()); - Pallet::::deposit_event(Event::::ApplyClientRelease { release }); - reads += 1; + RewardPerBlock::::put(new_rewards_per_block); + RewardsAdaptedAt::::put(frame_system::Pallet::::block_number()); + + Self::deposit_event(Event::::RewardsPerBlockAdapted(new_rewards_per_block)); + Ok(()) } - T::DbWeight::get().reads_writes(reads, reads * 2) } } diff --git a/pallets/reward-distribution/src/types.rs b/pallets/reward-distribution/src/types.rs new file mode 100644 index 000000000..3480040a5 --- /dev/null +++ b/pallets/reward-distribution/src/types.rs @@ -0,0 +1,5 @@ +use crate::Config; + +pub type AccountIdOf = ::AccountId; + +pub(crate) type BalanceOf = ::Balance; From 74f69706b851716aeeafe19ff78272d00f10472c Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Mon, 9 Oct 2023 18:29:36 +0200 Subject: [PATCH 03/12] Include `tests` module --- pallets/reward-distribution/src/lib.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pallets/reward-distribution/src/lib.rs b/pallets/reward-distribution/src/lib.rs index 165b0dbf8..f59b33a04 100644 --- a/pallets/reward-distribution/src/lib.rs +++ b/pallets/reward-distribution/src/lib.rs @@ -26,6 +26,9 @@ mod benchmarking; #[cfg(test)] mod mock; +#[cfg(test)] +mod tests; + mod types; pub use pallet::*; From 203c27873c493974dc0b64305b968acf8733d4aa Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Mon, 9 Oct 2023 18:29:50 +0200 Subject: [PATCH 04/12] Fix tests not included in `clients-info` crate --- pallets/clients-info/src/lib.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pallets/clients-info/src/lib.rs b/pallets/clients-info/src/lib.rs index 1e73f5621..3c38f7e87 100644 --- a/pallets/clients-info/src/lib.rs +++ b/pallets/clients-info/src/lib.rs @@ -20,6 +20,9 @@ mod benchmarking; #[cfg(test)] mod mock; +#[cfg(test)] +mod tests; + type NameOf = BoundedVec::MaxNameLength>; type UriOf = BoundedVec::MaxUriLength>; From 17bd84c80aff752bf9ec868fb749dfea9d670cb2 Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Mon, 9 Oct 2023 18:49:03 +0200 Subject: [PATCH 05/12] Rewrite tests and mock --- Cargo.lock | 2 + pallets/reward-distribution/Cargo.toml | 5 ++ .../src/default_weights.rs | 61 +------------- pallets/reward-distribution/src/lib.rs | 7 +- pallets/reward-distribution/src/mock.rs | 64 +++++++++++++-- pallets/reward-distribution/src/tests.rs | 82 ++++--------------- pallets/reward-distribution/src/types.rs | 4 +- 7 files changed, 91 insertions(+), 134 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 79df89d36..b3ff3d73c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6845,6 +6845,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "pallet-balances", "parity-scale-codec", "scale-info", "security", @@ -6854,6 +6855,7 @@ dependencies = [ "sp-io", "sp-runtime", "sp-std", + "vault-registry", ] [[package]] diff --git a/pallets/reward-distribution/Cargo.toml b/pallets/reward-distribution/Cargo.toml index 8b5d0a984..6d9075166 100644 --- a/pallets/reward-distribution/Cargo.toml +++ b/pallets/reward-distribution/Cargo.toml @@ -20,7 +20,10 @@ frame-support = { git = "https://github.com/paritytech/substrate", branch = "pol frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false } frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false, optional = true } +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false } + security = { path = "../security", default-features = false } +vault-registry = { path = "../vault-registry", default-features = false } [features] default = ["std"] @@ -36,7 +39,9 @@ std = [ "frame-support/std", "frame-system/std", "frame-benchmarking/std", + "pallet-balances/std", "security/std", + "vault-registry/std", ] runtime-benchmarks = [ "frame-benchmarking", diff --git a/pallets/reward-distribution/src/default_weights.rs b/pallets/reward-distribution/src/default_weights.rs index c50d2ed97..9b7447afb 100644 --- a/pallets/reward-distribution/src/default_weights.rs +++ b/pallets/reward-distribution/src/default_weights.rs @@ -30,8 +30,7 @@ use core::marker::PhantomData; /// Weight functions needed for clients_info. pub trait WeightInfo { - fn set_current_client_release(n: u32, u: u32, ) -> Weight; - fn set_pending_client_release(n: u32, u: u32, ) -> Weight; + fn set_reward_per_block( ) -> Weight; } /// Weights for clients_info using the Substrate node and recommended hardware. @@ -41,68 +40,16 @@ impl WeightInfo for SubstrateWeight { /// Proof: ClientsInfo CurrentClientReleases (max_values: None, max_size: Some(562), added: 3037, mode: MaxEncodedLen) /// The range of component `n` is `[0, 255]`. /// The range of component `u` is `[0, 255]`. - fn set_current_client_release(n: u32, u: u32, ) -> Weight { + fn set_reward_per_block( ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` // Minimum execution time: 7_607_000 picoseconds. Weight::from_parts(9_560_259, 0) // Standard Error: 845 - .saturating_add(Weight::from_parts(2_586, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(2_586, 0)) // Standard Error: 845 - .saturating_add(Weight::from_parts(689, 0).saturating_mul(u.into())) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } - /// Storage: ClientsInfo PendingClientReleases (r:0 w:1) - /// Proof: ClientsInfo PendingClientReleases (max_values: None, max_size: Some(562), added: 3037, mode: MaxEncodedLen) - /// The range of component `n` is `[0, 255]`. - /// The range of component `u` is `[0, 255]`. - fn set_pending_client_release(n: u32, u: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 7_557_000 picoseconds. - Weight::from_parts(9_238_573, 0) - // Standard Error: 840 - .saturating_add(Weight::from_parts(3_011, 0).saturating_mul(n.into())) - // Standard Error: 840 - .saturating_add(Weight::from_parts(892, 0).saturating_mul(u.into())) + .saturating_add(Weight::from_parts(689, 0)) .saturating_add(T::DbWeight::get().writes(1_u64)) } } - -// For backwards compatibility and tests -impl WeightInfo for () { - /// Storage: ClientsInfo CurrentClientReleases (r:0 w:1) - /// Proof: ClientsInfo CurrentClientReleases (max_values: None, max_size: Some(562), added: 3037, mode: MaxEncodedLen) - /// The range of component `n` is `[0, 255]`. - /// The range of component `u` is `[0, 255]`. - fn set_current_client_release(n: u32, u: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 7_607_000 picoseconds. - Weight::from_parts(9_560_259, 0) - // Standard Error: 845 - .saturating_add(Weight::from_parts(2_586, 0).saturating_mul(n.into())) - // Standard Error: 845 - .saturating_add(Weight::from_parts(689, 0).saturating_mul(u.into())) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } - /// Storage: ClientsInfo PendingClientReleases (r:0 w:1) - /// Proof: ClientsInfo PendingClientReleases (max_values: None, max_size: Some(562), added: 3037, mode: MaxEncodedLen) - /// The range of component `n` is `[0, 255]`. - /// The range of component `u` is `[0, 255]`. - fn set_pending_client_release(n: u32, u: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 7_557_000 picoseconds. - Weight::from_parts(9_238_573, 0) - // Standard Error: 840 - .saturating_add(Weight::from_parts(3_011, 0).saturating_mul(n.into())) - // Standard Error: 840 - .saturating_add(Weight::from_parts(892, 0).saturating_mul(u.into())) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } -} \ No newline at end of file diff --git a/pallets/reward-distribution/src/lib.rs b/pallets/reward-distribution/src/lib.rs index f59b33a04..38af93915 100644 --- a/pallets/reward-distribution/src/lib.rs +++ b/pallets/reward-distribution/src/lib.rs @@ -5,8 +5,7 @@ #![cfg_attr(test, feature(proc_macro_hygiene))] #![cfg_attr(not(feature = "std"), no_std)] -use codec::{Decode, Encode, MaxEncodedLen}; -use scale_info::TypeInfo; +use codec::Encode; mod default_weights; @@ -16,7 +15,7 @@ use crate::types::{AccountIdOf, BalanceOf}; use frame_support::{ dispatch::DispatchResult, traits::{Currency, Get}, - transactional, BoundedVec, + transactional, }; use sp_arithmetic::Perquintill; @@ -44,7 +43,7 @@ pub mod pallet { pub struct Pallet(_); #[pallet::config] - pub trait Config: frame_system::Config + security::Config { + pub trait Config: frame_system::Config + security::Config + vault_registry::Config { /// The overarching event type. type RuntimeEvent: From> + Into<::RuntimeEvent> diff --git a/pallets/reward-distribution/src/mock.rs b/pallets/reward-distribution/src/mock.rs index 4fb8c84b3..8fdbb8cbe 100644 --- a/pallets/reward-distribution/src/mock.rs +++ b/pallets/reward-distribution/src/mock.rs @@ -1,13 +1,14 @@ -use crate as clients_info; +use crate as reward_distribution; use crate::Config; use frame_support::{ parameter_types, - traits::{ConstU32, Everything}, + traits::{ConstU32, Everything, Get}, }; use sp_core::H256; use sp_runtime::{ generic::Header as GenericHeader, traits::{BlakeTwo256, IdentityLookup}, + Perquintill, }; type Header = GenericHeader; @@ -22,13 +23,18 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Storage, Config, Event}, - ClientsInfo: clients_info::{Pallet, Call, Storage, Event} + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, + Security: security::{Pallet, Call, Storage, Event}, + VaultRegistry: vault_registry::{Pallet, Call, Storage, Event}, + RewardDistribution: reward_distribution::{Pallet, Call, Storage, Event}, } ); pub type AccountId = u64; +pub type Balance = u128; pub type BlockNumber = u64; pub type Index = u64; +pub type Currency = u64; parameter_types! { pub const BlockHashCount: u64 = 250; @@ -62,11 +68,59 @@ impl frame_system::Config for Test { type MaxConsumers = ConstU32<16>; } +parameter_types! { + pub const ExistentialDeposit: Balance = 1000; + pub const MaxReserves: u32 = 50; + pub const MaxLocks: u32 = 50; +} + +parameter_type_with_key! { + pub ExistentialDeposits: |_currency_id: CurrencyId| -> Balance { + 0 + }; +} + +impl pallet_balances::Config for Test { + type MaxLocks = MaxLocks; + /// The type for recording an account's balance. + type Balance = Balance; + /// The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = pallet_balances::weights::SubstrateWeight; + type MaxReserves = MaxReserves; + type ReserveIdentifier = (); +} + +impl security::Config for Test { + type RuntimeEvent = (); + type WeightInfo = (); +} + +parameter_types! { + pub const VaultPalletId: PalletId = PalletId(*b"mod/vreg"); +} + +impl vault_registry::Config for Test { + type PalletId = VaultPalletId; + type RuntimeEvent = TestEvent; + type Balance = Balance; + type WeightInfo = vault_registry::SubstrateWeight; + type GetGriefingCollateralCurrencyId = GetNativeCurrencyId; +} + +parameter_types! { + pub const DecayRate: Perquintill = Perquintill::from_percent(5); +} + impl Config for Test { type RuntimeEvent = RuntimeEvent; type WeightInfo = (); - type MaxNameLength = ConstU32<255>; - type MaxUriLength = ConstU32<255>; + type Currency = Currency; + type DecayInterval = ConstU32<100>; + type DecayRate = DecayRate; } pub struct ExtBuilder; diff --git a/pallets/reward-distribution/src/tests.rs b/pallets/reward-distribution/src/tests.rs index 025ba94e0..cd0697e3a 100644 --- a/pallets/reward-distribution/src/tests.rs +++ b/pallets/reward-distribution/src/tests.rs @@ -1,77 +1,29 @@ use crate::mock::*; -use sp_core::H256; -use sp_std::vec; -use std::collections::HashMap; -use upgrade_client_releases::*; +use frame_support::{assert_err, assert_ok}; +use frame_system::Origin; +use sp_runtime::DispatchError::BadOrigin; #[cfg(test)] #[test] -fn test_client_pending_release_migration() { +fn test_set_rewards_per_block() { run_test(|| { - let vault_key = b"vault".to_vec(); + let new_rewards_per_block = 100; - let pre_migration_pending_releases: HashMap<_, _> = vec![( - vault_key.clone(), - ClientRelease { - uri: BoundedVec::try_from(b"https://github.com/pendulum-chain/spacewalk".to_vec()) - .unwrap(), - checksum: H256::default(), - }, - )] - .into_iter() - .collect(); - pre_migration_pending_releases.iter().for_each(|(key, value)| { - PendingClientReleases::::insert( - BoundedVec::try_from(key.clone()).unwrap(), - value.clone(), - ); - }); - - let pre_migration_current_releases: HashMap<_, _> = vec![( - vault_key.clone(), - ClientRelease { - uri: BoundedVec::try_from(b"https://github.com/pendulum-chain/spacewalk".to_vec()) - .unwrap(), - checksum: H256::default(), - }, - )] - .into_iter() - .collect(); - pre_migration_current_releases.iter().for_each(|(key, value)| { - CurrentClientReleases::::insert( - BoundedVec::try_from(key.clone()).unwrap(), - value.clone(), - ); - }); - - try_upgrade_current_client_releases::(); - - let pending_releases = PendingClientReleases::::iter_values().collect::>(); - assert_eq!(pending_releases.is_empty(), true); - - let current_releases = CurrentClientReleases::::iter() - .map(|(key, value)| (key.to_vec(), value)) - .collect::>(); - assert_eq!( - current_releases.get(&vault_key), - pre_migration_pending_releases.get(&vault_key) + assert_err!( + RewardDistribution::set_rewards_per_block(Origin::signed(1), new_rewards_per_block), + BadOrigin ); - }); -} -#[cfg(test)] -#[test] -fn test_decode_bounded_vec() { - run_test(|| { - let key = vec![0; 255]; - - CurrentClientReleases::::insert( - key.clone(), - ClientRelease { uri: vec![1; 255], checksum: H256::default() }, + assert_err!( + RewardDistribution::set_rewards_per_block(Origin::none(), new_rewards_per_block), + BadOrigin ); - let client_release = - crate::CurrentClientReleases::::get(BoundedVec::try_from(key).unwrap()); - assert_eq!(client_release.map(|c| c.uri.to_vec()), Some(vec![1; 255])); + assert_ok!(RewardDistribution::set_rewards_per_block( + Origin::root(), + new_rewards_per_block + )); + + assert_eq!(RewardDistribution::rewards_per_block(), new_rewards_per_block); }); } diff --git a/pallets/reward-distribution/src/types.rs b/pallets/reward-distribution/src/types.rs index 3480040a5..51446c448 100644 --- a/pallets/reward-distribution/src/types.rs +++ b/pallets/reward-distribution/src/types.rs @@ -1,5 +1,3 @@ -use crate::Config; - pub type AccountIdOf = ::AccountId; -pub(crate) type BalanceOf = ::Balance; +pub(crate) type BalanceOf = ::Balance; From a5c5b1cedd50a7f9b0ce59fb7cca9fda83bd4f5b Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Tue, 10 Oct 2023 12:41:26 +0200 Subject: [PATCH 06/12] Fix tests and mock --- Cargo.lock | 1 - pallets/clients-info/src/tests.rs | 110 ++++++++++++----------- pallets/reward-distribution/Cargo.toml | 2 - pallets/reward-distribution/src/lib.rs | 16 ++-- pallets/reward-distribution/src/mock.rs | 32 ++----- pallets/reward-distribution/src/tests.rs | 14 +-- pallets/reward-distribution/src/types.rs | 5 +- 7 files changed, 81 insertions(+), 99 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b3ff3d73c..2d965fad6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6855,7 +6855,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-std", - "vault-registry", ] [[package]] diff --git a/pallets/clients-info/src/tests.rs b/pallets/clients-info/src/tests.rs index c8838eb6d..025ba94e0 100644 --- a/pallets/clients-info/src/tests.rs +++ b/pallets/clients-info/src/tests.rs @@ -1,75 +1,77 @@ - +use crate::mock::*; use sp_core::H256; use sp_std::vec; use std::collections::HashMap; use upgrade_client_releases::*; -use crate::mock::*; - #[cfg(test)] #[test] fn test_client_pending_release_migration() { - run_test(|| { - let vault_key = b"vault".to_vec(); + run_test(|| { + let vault_key = b"vault".to_vec(); - let pre_migration_pending_releases: HashMap<_, _> = vec![ - ( - vault_key.clone(), - ClientRelease { - uri: BoundedVec::try_from(b"https://github.com/pendulum-chain/spacewalk" - .to_vec()).unwrap(), - checksum: H256::default(), - } - ), - ].into_iter().collect(); - pre_migration_pending_releases.iter().for_each(|(key, value)| { - PendingClientReleases::::insert(BoundedVec::try_from(key.clone()).unwrap(), value.clone()); - }); + let pre_migration_pending_releases: HashMap<_, _> = vec![( + vault_key.clone(), + ClientRelease { + uri: BoundedVec::try_from(b"https://github.com/pendulum-chain/spacewalk".to_vec()) + .unwrap(), + checksum: H256::default(), + }, + )] + .into_iter() + .collect(); + pre_migration_pending_releases.iter().for_each(|(key, value)| { + PendingClientReleases::::insert( + BoundedVec::try_from(key.clone()).unwrap(), + value.clone(), + ); + }); - let pre_migration_current_releases: HashMap<_, _> = vec![ - ( - vault_key.clone(), - ClientRelease { - uri: BoundedVec::try_from(b"https://github.com/pendulum-chain/spacewalk" - .to_vec()).unwrap(), - checksum: H256::default(), - } - ), - ].into_iter().collect(); - pre_migration_current_releases.iter().for_each(|(key, value)| { - CurrentClientReleases::::insert(BoundedVec::try_from(key.clone()).unwrap(), value.clone()); - }); + let pre_migration_current_releases: HashMap<_, _> = vec![( + vault_key.clone(), + ClientRelease { + uri: BoundedVec::try_from(b"https://github.com/pendulum-chain/spacewalk".to_vec()) + .unwrap(), + checksum: H256::default(), + }, + )] + .into_iter() + .collect(); + pre_migration_current_releases.iter().for_each(|(key, value)| { + CurrentClientReleases::::insert( + BoundedVec::try_from(key.clone()).unwrap(), + value.clone(), + ); + }); - try_upgrade_current_client_releases::(); + try_upgrade_current_client_releases::(); - let pending_releases = PendingClientReleases::::iter_values().collect::>(); - assert_eq!(pending_releases.is_empty(), true); + let pending_releases = PendingClientReleases::::iter_values().collect::>(); + assert_eq!(pending_releases.is_empty(), true); - let current_releases = CurrentClientReleases::::iter() - .map(|(key, value)| (key.to_vec(), value)) - .collect::>(); - assert_eq!( - current_releases.get(&vault_key), - pre_migration_pending_releases.get(&vault_key) - ); - }); + let current_releases = CurrentClientReleases::::iter() + .map(|(key, value)| (key.to_vec(), value)) + .collect::>(); + assert_eq!( + current_releases.get(&vault_key), + pre_migration_pending_releases.get(&vault_key) + ); + }); } #[cfg(test)] #[test] fn test_decode_bounded_vec() { - run_test(|| { - let key = vec![0; 255]; + run_test(|| { + let key = vec![0; 255]; - CurrentClientReleases::::insert( - key.clone(), - ClientRelease { - uri: vec![1; 255], - checksum: H256::default(), - }, - ); + CurrentClientReleases::::insert( + key.clone(), + ClientRelease { uri: vec![1; 255], checksum: H256::default() }, + ); - let client_release = crate::CurrentClientReleases::::get(BoundedVec::try_from(key).unwrap()); - assert_eq!(client_release.map(|c| c.uri.to_vec()), Some(vec![1; 255])); - }); + let client_release = + crate::CurrentClientReleases::::get(BoundedVec::try_from(key).unwrap()); + assert_eq!(client_release.map(|c| c.uri.to_vec()), Some(vec![1; 255])); + }); } diff --git a/pallets/reward-distribution/Cargo.toml b/pallets/reward-distribution/Cargo.toml index 6d9075166..5523502a4 100644 --- a/pallets/reward-distribution/Cargo.toml +++ b/pallets/reward-distribution/Cargo.toml @@ -23,7 +23,6 @@ frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.40", default-features = false } security = { path = "../security", default-features = false } -vault-registry = { path = "../vault-registry", default-features = false } [features] default = ["std"] @@ -41,7 +40,6 @@ std = [ "frame-benchmarking/std", "pallet-balances/std", "security/std", - "vault-registry/std", ] runtime-benchmarks = [ "frame-benchmarking", diff --git a/pallets/reward-distribution/src/lib.rs b/pallets/reward-distribution/src/lib.rs index 38af93915..bdcdb13ae 100644 --- a/pallets/reward-distribution/src/lib.rs +++ b/pallets/reward-distribution/src/lib.rs @@ -5,8 +5,6 @@ #![cfg_attr(test, feature(proc_macro_hygiene))] #![cfg_attr(not(feature = "std"), no_std)] -use codec::Encode; - mod default_weights; pub use default_weights::{SubstrateWeight, WeightInfo}; @@ -43,7 +41,7 @@ pub mod pallet { pub struct Pallet(_); #[pallet::config] - pub trait Config: frame_system::Config + security::Config + vault_registry::Config { + pub trait Config: frame_system::Config + security::Config { /// The overarching event type. type RuntimeEvent: From> + Into<::RuntimeEvent> @@ -68,7 +66,7 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// A new RewardPerBlock value has been set. - RewardsPerBlockAdapted(BalanceOf), + RewardPerBlockAdapted(BalanceOf), } #[pallet::error] @@ -87,18 +85,18 @@ pub mod pallet { impl Pallet { /// Sets the reward per block. #[pallet::call_index(0)] - #[pallet::weight(::WeightInfo::set_rewards_per_block())] + #[pallet::weight(::WeightInfo::set_reward_per_block())] #[transactional] - pub fn set_rewards_per_block( + pub fn set_reward_per_block( origin: OriginFor, - new_rewards_per_block: BalanceOf, + new_reward_per_block: BalanceOf, ) -> DispatchResult { ensure_root(origin)?; - RewardPerBlock::::put(new_rewards_per_block); + RewardPerBlock::::put(new_reward_per_block); RewardsAdaptedAt::::put(frame_system::Pallet::::block_number()); - Self::deposit_event(Event::::RewardsPerBlockAdapted(new_rewards_per_block)); + Self::deposit_event(Event::::RewardPerBlockAdapted(new_reward_per_block)); Ok(()) } } diff --git a/pallets/reward-distribution/src/mock.rs b/pallets/reward-distribution/src/mock.rs index 8fdbb8cbe..315edfef9 100644 --- a/pallets/reward-distribution/src/mock.rs +++ b/pallets/reward-distribution/src/mock.rs @@ -2,7 +2,7 @@ use crate as reward_distribution; use crate::Config; use frame_support::{ parameter_types, - traits::{ConstU32, Everything, Get}, + traits::{ConstU32, ConstU64, Everything}, }; use sp_core::H256; use sp_runtime::{ @@ -25,7 +25,6 @@ frame_support::construct_runtime!( System: frame_system::{Pallet, Call, Storage, Config, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Security: security::{Pallet, Call, Storage, Event}, - VaultRegistry: vault_registry::{Pallet, Call, Storage, Event}, RewardDistribution: reward_distribution::{Pallet, Call, Storage, Event}, } ); @@ -34,7 +33,6 @@ pub type AccountId = u64; pub type Balance = u128; pub type BlockNumber = u64; pub type Index = u64; -pub type Currency = u64; parameter_types! { pub const BlockHashCount: u64 = 250; @@ -59,7 +57,7 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); + type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); @@ -74,12 +72,6 @@ parameter_types! { pub const MaxLocks: u32 = 50; } -parameter_type_with_key! { - pub ExistentialDeposits: |_currency_id: CurrencyId| -> Balance { - 0 - }; -} - impl pallet_balances::Config for Test { type MaxLocks = MaxLocks; /// The type for recording an account's balance. @@ -95,31 +87,19 @@ impl pallet_balances::Config for Test { } impl security::Config for Test { - type RuntimeEvent = (); + type RuntimeEvent = RuntimeEvent; type WeightInfo = (); } -parameter_types! { - pub const VaultPalletId: PalletId = PalletId(*b"mod/vreg"); -} - -impl vault_registry::Config for Test { - type PalletId = VaultPalletId; - type RuntimeEvent = TestEvent; - type Balance = Balance; - type WeightInfo = vault_registry::SubstrateWeight; - type GetGriefingCollateralCurrencyId = GetNativeCurrencyId; -} - parameter_types! { pub const DecayRate: Perquintill = Perquintill::from_percent(5); } impl Config for Test { type RuntimeEvent = RuntimeEvent; - type WeightInfo = (); - type Currency = Currency; - type DecayInterval = ConstU32<100>; + type WeightInfo = crate::default_weights::SubstrateWeight; + type Currency = Balances; + type DecayInterval = ConstU64<100>; type DecayRate = DecayRate; } diff --git a/pallets/reward-distribution/src/tests.rs b/pallets/reward-distribution/src/tests.rs index cd0697e3a..3b9ac4ca7 100644 --- a/pallets/reward-distribution/src/tests.rs +++ b/pallets/reward-distribution/src/tests.rs @@ -1,6 +1,5 @@ use crate::mock::*; use frame_support::{assert_err, assert_ok}; -use frame_system::Origin; use sp_runtime::DispatchError::BadOrigin; #[cfg(test)] @@ -10,20 +9,23 @@ fn test_set_rewards_per_block() { let new_rewards_per_block = 100; assert_err!( - RewardDistribution::set_rewards_per_block(Origin::signed(1), new_rewards_per_block), + RewardDistribution::set_reward_per_block( + RuntimeOrigin::signed(1), + new_rewards_per_block + ), BadOrigin ); assert_err!( - RewardDistribution::set_rewards_per_block(Origin::none(), new_rewards_per_block), + RewardDistribution::set_reward_per_block(RuntimeOrigin::none(), new_rewards_per_block), BadOrigin ); - assert_ok!(RewardDistribution::set_rewards_per_block( - Origin::root(), + assert_ok!(RewardDistribution::set_reward_per_block( + RuntimeOrigin::root(), new_rewards_per_block )); - assert_eq!(RewardDistribution::rewards_per_block(), new_rewards_per_block); + assert_eq!(RewardDistribution::reward_per_block(), Some(new_rewards_per_block)); }); } diff --git a/pallets/reward-distribution/src/types.rs b/pallets/reward-distribution/src/types.rs index 51446c448..e887f80dc 100644 --- a/pallets/reward-distribution/src/types.rs +++ b/pallets/reward-distribution/src/types.rs @@ -1,3 +1,6 @@ +use crate::Config; +use frame_support::traits::Currency; + pub type AccountIdOf = ::AccountId; -pub(crate) type BalanceOf = ::Balance; +pub(crate) type BalanceOf = <::Currency as Currency>>::Balance; From a2ac7345257957f4722d4bd75a2b8b89b71f2301 Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Tue, 10 Oct 2023 12:55:04 +0200 Subject: [PATCH 07/12] Fix benchmarking.rs --- .../reward-distribution/src/benchmarking.rs | 33 +++++++------------ 1 file changed, 11 insertions(+), 22 deletions(-) diff --git a/pallets/reward-distribution/src/benchmarking.rs b/pallets/reward-distribution/src/benchmarking.rs index 2ef002d15..d6bb1bc09 100644 --- a/pallets/reward-distribution/src/benchmarking.rs +++ b/pallets/reward-distribution/src/benchmarking.rs @@ -1,38 +1,27 @@ use super::*; -use frame_benchmarking::v2::{benchmarks, impl_benchmark_test_suite, Linear}; +use frame_benchmarking::v2::{benchmarks, impl_benchmark_test_suite}; use frame_system::RawOrigin; -use sp_std::vec; #[allow(unused)] -use super::Pallet as ClientsInfo; +use super::Pallet as RewardDistribution; #[benchmarks] pub mod benchmarks { use super::*; #[benchmark] - fn set_current_client_release(n: Linear<0, 255>, u: Linear<0, 255>) { - let name = BoundedVec::try_from(vec![0; n as usize]).unwrap(); - let uri = BoundedVec::try_from(vec![0; u as usize]).unwrap(); - let client_release = ClientRelease { uri, checksum: Default::default() }; + fn set_reward_per_block() { + let new_reward_per_block = Default::default(); #[extrinsic_call] - _(RawOrigin::Root, name.clone(), client_release.clone()); + _(RawOrigin::Root, new_reward_per_block); - assert_eq!(CurrentClientReleases::::get(name), Some(client_release)); + assert_eq!(RewardDistribution::::reward_per_block(), Some(new_reward_per_block)); } - #[benchmark] - fn set_pending_client_release(n: Linear<0, 255>, u: Linear<0, 255>) { - let name = BoundedVec::try_from(vec![0; n as usize]).unwrap(); - let uri = BoundedVec::try_from(vec![0; u as usize]).unwrap(); - let client_release = ClientRelease { uri, checksum: Default::default() }; - - #[extrinsic_call] - _(RawOrigin::Root, name.clone(), client_release.clone()); - - assert_eq!(PendingClientReleases::::get(name), Some(client_release)); - } - - impl_benchmark_test_suite!(ClientsInfo, crate::mock::ExtBuilder::build(), crate::mock::Test); + impl_benchmark_test_suite!( + RewardDistribution, + crate::mock::ExtBuilder::build(), + crate::mock::Test + ); } From 86e10787ef82da2ed752e9a9986ab96001a4af88 Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Tue, 10 Oct 2023 13:13:48 +0200 Subject: [PATCH 08/12] Configure reward-distribution pallet in testchain runtime --- Cargo.lock | 1 + pallets/reward-distribution/README.md | 6 +++--- pallets/reward-distribution/src/benchmarking.rs | 1 + testchain/runtime/Cargo.toml | 6 +++++- testchain/runtime/src/lib.rs | 17 ++++++++++++++++- 5 files changed, 26 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2d965fad6..2bdbe781d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9537,6 +9537,7 @@ dependencies = [ "redeem", "replace", "reward", + "reward-distribution", "scale-info", "security", "serde_json", diff --git a/pallets/reward-distribution/README.md b/pallets/reward-distribution/README.md index df3f480d0..9a4e4e737 100644 --- a/pallets/reward-distribution/README.md +++ b/pallets/reward-distribution/README.md @@ -16,12 +16,12 @@ Build the node with the `runtime-benchmarks` feature: ```bash cargo build --package spacewalk-standalone --release --features runtime-benchmarks -```bash +``` ```bash # Show benchmarks for this pallet ./target/release/spacewalk-standalone benchmark pallet -p reward-distribution -e '*' --list -```bash +``` Run the benchmarking for a pallet: @@ -35,5 +35,5 @@ Run the benchmarking for a pallet: --wasm-execution=compiled \ --output=pallets/reward-distribution/src/default_weights.rs \ --template=./.maintain/frame-weight-template.hbs -```bash +``` diff --git a/pallets/reward-distribution/src/benchmarking.rs b/pallets/reward-distribution/src/benchmarking.rs index d6bb1bc09..0658740da 100644 --- a/pallets/reward-distribution/src/benchmarking.rs +++ b/pallets/reward-distribution/src/benchmarking.rs @@ -1,6 +1,7 @@ use super::*; use frame_benchmarking::v2::{benchmarks, impl_benchmark_test_suite}; use frame_system::RawOrigin; +use sp_std::vec; #[allow(unused)] use super::Pallet as RewardDistribution; diff --git a/testchain/runtime/Cargo.toml b/testchain/runtime/Cargo.toml index 7eb066cbc..fcf715f50 100644 --- a/testchain/runtime/Cargo.toml +++ b/testchain/runtime/Cargo.toml @@ -64,6 +64,7 @@ oracle = {path = "../../pallets/oracle", default-features = false} redeem = {path = "../../pallets/redeem", default-features = false} replace = {path = "../../pallets/replace", default-features = false} reward = {path = "../../pallets/reward", default-features = false} +reward-distribution = {path = "../../pallets/reward-distribution", default-features = false} security = {path = "../../pallets/security", default-features = false} staking = {path = "../../pallets/staking", default-features = false} stellar-relay = {path = "../../pallets/stellar-relay", default-features = false} @@ -99,19 +100,21 @@ runtime-benchmarks = [ "frame-system/runtime-benchmarks", "frame-system-benchmarking/runtime-benchmarks", "hex-literal", + "clients-info/runtime-benchmarks", "fee/runtime-benchmarks", "issue/runtime-benchmarks", "nomination/runtime-benchmarks", "oracle/runtime-benchmarks", "redeem/runtime-benchmarks", "replace/runtime-benchmarks", + "reward-distribution/runtime-benchmarks", "stellar-relay/runtime-benchmarks", "vault-registry/runtime-benchmarks", - "clients-info/runtime-benchmarks" ] std = [ "codec/std", "currency/std", + "clients-info/std", "fee/std", "frame-executive/std", "frame-support/std", @@ -140,6 +143,7 @@ std = [ "redeem/std", "replace/std", "reward/std", + "reward-distribution/std", "scale-info/std", "security/std", "sp-api/std", diff --git a/testchain/runtime/src/lib.rs b/testchain/runtime/src/lib.rs index c8c80ad80..c8186c8c1 100644 --- a/testchain/runtime/src/lib.rs +++ b/testchain/runtime/src/lib.rs @@ -32,7 +32,8 @@ use sp_runtime::{ Zero, }, transaction_validity::{TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, DispatchError, FixedPointNumber, Perbill, SaturatedConversion, + ApplyExtrinsicResult, DispatchError, FixedPointNumber, Perbill, Perquintill, + SaturatedConversion, }; use sp_std::{marker::PhantomData, prelude::*}; #[cfg(feature = "std")] @@ -567,6 +568,18 @@ impl clients_info::Config for Runtime { type MaxUriLength = ConstU32<255>; } +parameter_types! { + pub const DecayRate: Perquintill = Perquintill::from_percent(5); +} + +impl reward_distribution::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type WeightInfo = reward_distribution::SubstrateWeight; + type Currency = Balances; + type DecayInterval = ConstU32<100>; + type DecayRate = DecayRate; +} + construct_runtime! { pub enum Runtime where Block = Block, @@ -600,6 +613,7 @@ construct_runtime! { Nomination: nomination::{Pallet, Call, Config, Storage, Event} = 28, DiaOracleModule: dia_oracle::{Pallet, Call, Config, Storage, Event} = 29, ClientsInfo: clients_info::{Pallet, Call, Storage, Event} = 30, + RewardDistribution: reward_distribution::{Pallet, Call, Storage, Event} = 31, } } @@ -652,6 +666,7 @@ mod benches { [replace, Replace] [vault_registry, VaultRegistry] [nomination, Nomination] + [reward_distribution, RewardDistribution] ); } From 2eec499813ccef2966b3083725629f036c59920d Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Tue, 10 Oct 2023 13:15:13 +0200 Subject: [PATCH 09/12] Generate `default_weights.rs` --- .../src/default_weights.rs | 52 ++++++++++++------- 1 file changed, 32 insertions(+), 20 deletions(-) diff --git a/pallets/reward-distribution/src/default_weights.rs b/pallets/reward-distribution/src/default_weights.rs index 9b7447afb..9947ff0c5 100644 --- a/pallets/reward-distribution/src/default_weights.rs +++ b/pallets/reward-distribution/src/default_weights.rs @@ -1,10 +1,10 @@ -//! Autogenerated weights for clients_info +//! Autogenerated weights for reward_distribution //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-09-13, STEPS: `100`, REPEAT: `10`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-10-10, STEPS: `100`, REPEAT: `10`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `pop-os`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! HOSTNAME: `Marcels-MBP`, CPU: `` //! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: @@ -12,12 +12,12 @@ // benchmark // pallet // --chain=dev -// --pallet=clients-info +// --pallet=reward-distribution // --extrinsic=* // --steps=100 // --repeat=10 // --wasm-execution=compiled -// --output=pallets/clients-info/src/default_weights.rs +// --output=pallets/reward-distribution/src/default_weights.rs // --template=./.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -28,28 +28,40 @@ use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use core::marker::PhantomData; -/// Weight functions needed for clients_info. +/// Weight functions needed for reward_distribution. pub trait WeightInfo { - fn set_reward_per_block( ) -> Weight; + fn set_reward_per_block() -> Weight; } -/// Weights for clients_info using the Substrate node and recommended hardware. +/// Weights for reward_distribution using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - /// Storage: ClientsInfo CurrentClientReleases (r:0 w:1) - /// Proof: ClientsInfo CurrentClientReleases (max_values: None, max_size: Some(562), added: 3037, mode: MaxEncodedLen) - /// The range of component `n` is `[0, 255]`. - /// The range of component `u` is `[0, 255]`. - fn set_reward_per_block( ) -> Weight { + /// Storage: RewardDistribution RewardsAdaptedAt (r:0 w:1) + /// Proof: RewardDistribution RewardsAdaptedAt (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) + /// Storage: RewardDistribution RewardPerBlock (r:0 w:1) + /// Proof: RewardDistribution RewardPerBlock (max_values: Some(1), max_size: Some(16), added: 511, mode: MaxEncodedLen) + fn set_reward_per_block() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_607_000 picoseconds. - Weight::from_parts(9_560_259, 0) - // Standard Error: 845 - .saturating_add(Weight::from_parts(2_586, 0)) - // Standard Error: 845 - .saturating_add(Weight::from_parts(689, 0)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 3_000_000 picoseconds. + Weight::from_parts(4_000_000, 0) + .saturating_add(T::DbWeight::get().writes(2_u64)) } } + +// For backwards compatibility and tests +impl WeightInfo for () { + /// Storage: RewardDistribution RewardsAdaptedAt (r:0 w:1) + /// Proof: RewardDistribution RewardsAdaptedAt (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) + /// Storage: RewardDistribution RewardPerBlock (r:0 w:1) + /// Proof: RewardDistribution RewardPerBlock (max_values: Some(1), max_size: Some(16), added: 511, mode: MaxEncodedLen) + fn set_reward_per_block() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_000_000 picoseconds. + Weight::from_parts(4_000_000, 0) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + } +} \ No newline at end of file From 28bff4a86e5c907ce87cda5b6365a54f9ac6b694 Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Tue, 10 Oct 2023 13:24:09 +0200 Subject: [PATCH 10/12] Amend test --- pallets/reward-distribution/src/tests.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pallets/reward-distribution/src/tests.rs b/pallets/reward-distribution/src/tests.rs index 3b9ac4ca7..4c0c4409b 100644 --- a/pallets/reward-distribution/src/tests.rs +++ b/pallets/reward-distribution/src/tests.rs @@ -21,11 +21,15 @@ fn test_set_rewards_per_block() { BadOrigin ); + assert_eq!(RewardDistribution::reward_per_block(), None); + assert_eq!(RewardDistribution::rewards_adapted_at(), None); + assert_ok!(RewardDistribution::set_reward_per_block( RuntimeOrigin::root(), new_rewards_per_block )); assert_eq!(RewardDistribution::reward_per_block(), Some(new_rewards_per_block)); + assert_eq!(RewardDistribution::rewards_adapted_at(), Some(1)); }); } From cd87f3e1faee74754a922bac87137f64e919057b Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Thu, 12 Oct 2023 19:28:56 +0200 Subject: [PATCH 11/12] Fix `clients_info` test --- pallets/clients-info/src/tests.rs | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/pallets/clients-info/src/tests.rs b/pallets/clients-info/src/tests.rs index 025ba94e0..05191b30a 100644 --- a/pallets/clients-info/src/tests.rs +++ b/pallets/clients-info/src/tests.rs @@ -1,8 +1,13 @@ -use crate::mock::*; +use crate::{ + mock::*, + pallet::{CurrentClientReleases, PendingClientReleases}, + upgrade_client_releases::*, + ClientRelease, UriOf, +}; +use frame_support::BoundedVec; use sp_core::H256; use sp_std::vec; use std::collections::HashMap; -use upgrade_client_releases::*; #[cfg(test)] #[test] @@ -63,15 +68,20 @@ fn test_client_pending_release_migration() { #[test] fn test_decode_bounded_vec() { run_test(|| { - let key = vec![0; 255]; + let key = BoundedVec::try_from(b"vault".to_vec()).expect("should be able to convert"); - CurrentClientReleases::::insert( - key.clone(), - ClientRelease { uri: vec![1; 255], checksum: H256::default() }, - ); + let uri_vec = b"http:://localhost:8080".to_vec(); + let uri: UriOf = + BoundedVec::try_from(uri_vec.clone()).expect("should be able to convert"); + + let checksum: ::Hash = H256::default(); + + let client_release: ClientRelease, ::Hash> = + ClientRelease { uri, checksum }; + + CurrentClientReleases::::insert(key.clone(), client_release); - let client_release = - crate::CurrentClientReleases::::get(BoundedVec::try_from(key).unwrap()); - assert_eq!(client_release.map(|c| c.uri.to_vec()), Some(vec![1; 255])); + let client_release = CurrentClientReleases::::get(key.clone()); + assert_eq!(client_release.map(|c| c.uri.to_vec()), Some(uri_vec)); }); } From 4140bed686f950eff1b59da1d47b8153e68a1b24 Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Thu, 12 Oct 2023 20:25:42 +0200 Subject: [PATCH 12/12] Update metadata-standalone.scale --- clients/runtime/metadata-standalone.scale | Bin 92683 -> 93834 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/clients/runtime/metadata-standalone.scale b/clients/runtime/metadata-standalone.scale index 554c40d1099a95ec2b50c7c5bcdf1e3dcc434f67..12322846b518319e377082d96dc470e83b2f3601 100644 GIT binary patch delta 4295 zcma)A4{%h~xj(;i?}iN|VNj zSei0`8Yvbz=#@TDQMAPxCB5Zsb&8Vl;VZUuhEdv5%t%HVhbL&MkB(?l`rW%Lgz8M+ z%$>9MeBbYU=R4o|{@va6uI-UQTasUksA=2!lVTFe#p_ZQD#d%!JghRt%Xdn-6?Iyd z8uBjlg(D%~`e?)#49Khu_)*BBw|Nr`F_7fM6r*(1+e>>=R{aapT;CBSLRhWMKrI>TqsSdmW#Y9~3nfw^lonJX83SMzObkB}+4#ktyP*h=^r*d}JwO{9@F7U8>|_SF)*3Yz^s8k4n_}I<|PN)PcJr^9fVjk zYJxGQ;Wds!##>GQ!|}X$wD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