From d3fd2f6ea302f412ceae677bc5c9bd16c375fb12 Mon Sep 17 00:00:00 2001 From: Minh Huy Tran Date: Wed, 17 Apr 2024 13:26:25 +0200 Subject: [PATCH 1/7] feat: update substrate sdk version to polkadot v1.9 Signed-off-by: Minh Huy Tran --- Cargo.toml | 52 ++++++++++++++++++++----------- src/lib.rs | 29 ++++++++++------- src/types.rs | 64 +++++++++++++++++++++++++++++++++----- src/weights.rs | 72 +++++++++++++++++++++---------------------- tests/common/mock.rs | 51 +++++++++++++++--------------- tests/common/utils.rs | 18 +++++------ tests/conclude.rs | 34 ++++++++++---------- tests/deposit.rs | 16 +++++----- tests/dispute.rs | 30 +++++++++--------- tests/progress.rs | 24 +++++++-------- tests/unit.rs | 20 ++++++++---- tests/withdraw.rs | 20 ++++++------ 12 files changed, 255 insertions(+), 175 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4dd64c9..52e2bda 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,37 +1,43 @@ [package] name = "pallet-perun" -version = "4.0.0-dev" authors = ["PolyCrypt GmbH "] -edition = "2018" license = "Apache-2.0" +version = "0.0.0" homepage = "https://polycry.pt/" keywords = ["blockchain", "channel", "perun"] repository = "https://github.com/perun-network/perun-polkadot-pallet" description = "FRAME pallet for Perun State Channels" readme = "README.md" +edition.workspace = true [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-core = {default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', tag = 'monthly-2021-09+1'} -sp-runtime = {default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', tag = 'monthly-2021-09+1'} -sp-std = {default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', tag = 'monthly-2021-09+1'} -sp-io = {default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', tag = 'monthly-2021-09+1'} +sp-core = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-v1.9.0", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-v1.9.0", default-features = false } +sp-std = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-v1.9.0", default-features = false } +sp-io = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-v1.9.0", default-features = false } -frame-support = {default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', tag = 'monthly-2021-09+1'} -frame-system = {default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', tag = 'monthly-2021-09+1'} -frame-benchmarking = {default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', tag = 'monthly-2021-09+1', optional=true} +frame-support = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-v1.9.0", default-features = false } +frame-system = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-v1.9.0", default-features = false } +frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-v1.9.0", default-features = false, optional = true } -pallet-balances = {default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', tag = 'monthly-2021-09+1'} -pallet-timestamp = {default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', tag = 'monthly-2021-09+1'} +pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-v1.9.0", default-features = false } +pallet-timestamp = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-v1.9.0", default-features = false } -codec = {package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"]} -syn = "=1.0.76" +codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = [ + "derive", +] } +scale-info = { version = "2.10.0", default-features = false, features = [ + "derive", +] } +syn = "=1.0.109" [dev-dependencies] -sp-io = {default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', tag = 'monthly-2021-09+1'} -sp-runtime = {default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', tag = 'monthly-2021-09+1'} +sp-core = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-v1.9.0" } +sp-io = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-v1.9.0" } +sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-v1.9.0" } [features] @@ -39,16 +45,26 @@ default = ["std"] # Used for testing only. expose_privates = [] # Enable Benchmarks. -runtime-benchmarks = ['frame-benchmarking'] +runtime-benchmarks = [ + "frame-benchmarking/runtime-benchmarks", + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", +] std = [ "codec/std", + "sp-core/std", "sp-std/std", "sp-io/std", "sp-runtime/std", - "frame-benchmarking/std", + "frame-benchmarking?/std", "frame-support/std", "frame-system/std", "pallet-balances/std", "pallet-timestamp/std", ] -try-runtime = ['frame-support/try-runtime'] +try-runtime = [ + "frame-support/try-runtime", + "frame-system/try-runtime", + "sp-runtime/try-runtime", +] diff --git a/src/lib.rs b/src/lib.rs index 6b85da6..c3d1353 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,7 +41,7 @@ use frame_support::{ PalletId, }; use frame_system::{ensure_signed, pallet_prelude::*}; -use sp_runtime::traits::{AccountIdConversion, CheckedAdd, IdentifyAccount, Verify}; +use sp_runtime::traits::{ AccountIdConversion, CheckedAdd, IdentifyAccount, Verify }; use sp_std::{cmp, convert::TryFrom, ops::Range, vec::Vec}; macro_rules! require { @@ -60,7 +60,8 @@ pub mod pallet { dispatch::DispatchResult, traits::{ExistenceRequirement, Get}, }; - use sp_runtime::traits::{CheckedAdd, Member}; + use sp_core::ByteArray; +use sp_runtime::traits::{CheckedAdd, Member}; #[pallet::config] pub trait Config: frame_system::Config + pallet_timestamp::Config { @@ -81,16 +82,16 @@ pub mod pallet { type ParticipantNum: Get>; /// Because this pallet emits events, it depends on the runtime's definition of an event. - type Event: From> + IsType<::Event>; + type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// On-Chain currency that should be used by the Perun Pallet. type Currency: Currency; /// Type of a [Params::nonce]. - type Nonce: Encode + Decode + Member; + type Nonce: Encode + Decode + Member + TypeInfo; /// Type of a [State::version]. - type Version: Encode + Decode + Member + PartialOrd + CheckedAdd + From; + type Version: Encode + Decode + Member + TypeInfo + PartialOrd + CheckedAdd + From; /// Cryptographically secure hashing algorithm that is used to calculate the /// ChannelId and FundingId. @@ -98,17 +99,17 @@ pub mod pallet { /// Define the output of the Hashing algorithm. /// The `FullCodec` ensures that it is usable as a `StorageMap` key. - type HashValue: FullCodec + Member + Copy; + type HashValue: FullCodec + Member + Copy + TypeInfo; /// Off-Chain signature type. /// /// Must be possible to verify that a [Config::PK] created a signature. - type Signature: Encode + Decode + Member + Verify; + type Signature: Encode + Decode + Member + TypeInfo + Verify; /// PK of a [Config::Signature]. - type PK: Encode + Decode + Member + IdentifyAccount; + type PK: Encode + Decode + Member + ByteArray + TypeInfo + IdentifyAccount; /// Represent a time duration in seconds. - type Seconds: FullCodec + Member + CheckedAdd + PartialOrd + From; + type Seconds: FullCodec + Member + TypeInfo + CheckedAdd + PartialOrd + From; /// Weight info for extrinsics in this pallet. type WeightInfo: WeightInfo; @@ -122,7 +123,7 @@ pub mod pallet { } #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] + #[pallet::without_storage_info] pub struct Pallet(_); #[pallet::storage] @@ -242,6 +243,7 @@ pub mod pallet { /// /// Emits an [Event::Deposited] event on success. #[pallet::weight(WeightInfoOf::::deposit())] + #[pallet::call_index(0)] pub fn deposit( origin: OriginFor, funding_id: FundingIdOf, @@ -278,6 +280,7 @@ pub mod pallet { /// Emits an [Event::Disputed] event on success. #[pallet::weight(WeightInfoOf::::dispute( cmp::min(state_sigs.len() as u32, T::ParticipantNum::get().end)))] + #[pallet::call_index(1)] pub fn dispute( origin: OriginFor, params: ParamsOf, @@ -341,6 +344,7 @@ pub mod pallet { /// /// Emits an [Event::Progressed] event on success. #[pallet::weight(WeightInfoOf::::progress::(params))] + #[pallet::call_index(2)] pub fn progress( origin: OriginFor, params: ParamsOf, @@ -400,6 +404,7 @@ pub mod pallet { /// /// Emits an [Event::Concluded] event on success. #[pallet::weight(WeightInfoOf::::conclude(params.participants.len() as u32))] + #[pallet::call_index(3)] pub fn conclude(origin: OriginFor, params: ParamsOf) -> DispatchResult { ensure_signed(origin)?; let channel_id = params.channel_id::(); @@ -446,6 +451,7 @@ pub mod pallet { /// /// Emits an [Event::Concluded] event on success. #[pallet::weight(WeightInfoOf::::conclude_final(params.participants.len() as u32))] + #[pallet::call_index(4)] pub fn conclude_final( origin: OriginFor, params: ParamsOf, @@ -493,6 +499,7 @@ pub mod pallet { /// /// Emits an [Event::Withdrawn] event on success. #[pallet::weight(WeightInfoOf::::withdraw())] + #[pallet::call_index(5)] pub fn withdraw( origin: OriginFor, withdrawal: WithdrawalOf, @@ -536,7 +543,7 @@ impl Pallet { /// Returns the account of the pallet. /// Cache it if it needed multiple times. fn account_id() -> T::AccountId { - T::PalletId::get().into_account() + T::PalletId::get().into_account_truncating() } /// Returns the current time in seconds since diff --git a/src/types.rs b/src/types.rs index 0debb2e..3616ecd 100755 --- a/src/types.rs +++ b/src/types.rs @@ -17,7 +17,8 @@ use crate::*; use codec::{Decode, Encode}; -use sp_core::Hasher; +use sp_core::{ByteArray, Hasher}; +use crate::pallet::Config; use sp_runtime::{ traits::{IdentifyAccount, Verify}, RuntimeDebug, @@ -49,8 +50,8 @@ pub type FundingOf = Funding, PkOf>; pub type AppIdOf = ::AppId; pub type AppData = Vec; -pub trait AppId: Encode + Decode + Member + PartialEq {} -impl AppId for T {} +pub trait AppId: Encode + Decode + TypeInfo + Member + PartialEq {} +impl AppId for T {} pub trait AppRegistry { fn valid_transition( @@ -63,7 +64,7 @@ pub trait AppRegistry { fn transition_weight(params: &ParamsOf) -> Weight; } -#[derive(Encode, Decode, Default, Clone, PartialEq, RuntimeDebug)] +#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)] #[codec(dumb_trait_bound)] /// Fixed parameters of a channel. /// @@ -82,7 +83,25 @@ pub struct Params { pub app: AppId, } -#[derive(Encode, Decode, Default, Clone, PartialEq, RuntimeDebug)] +impl Default for Params +where + Nonce: Default, + Vec: Default, // This is crucial for initializing an empty vector of PK + Seconds: Default, + AppId: Default, +{ + fn default() -> Self { + Self { + nonce: Nonce::default(), + participants: Vec::default(), // Initialize an empty vector of PK + challenge_duration: Seconds::default(), + app: AppId::default(), + } + } +} + + +#[derive(Encode, Decode, Default, Clone, PartialEq, RuntimeDebug, TypeInfo)] #[codec(dumb_trait_bound)] /// Off-Chain state of a channel. pub struct State { @@ -116,14 +135,14 @@ pub struct State { pub data: AppData, } -#[derive(Encode, Decode, Copy, Clone, PartialEq, RuntimeDebug)] +#[derive(Encode, Decode, Copy, Clone, PartialEq, RuntimeDebug, TypeInfo)] pub enum Phase { Register, Progress, Conclude, } -#[derive(Encode, Decode, Copy, Clone, PartialEq, RuntimeDebug)] +#[derive(Encode, Decode, Copy, Clone, PartialEq, RuntimeDebug, TypeInfo)] #[codec(dumb_trait_bound)] /// Off-chain [State] that was registered on-chain. /// @@ -141,7 +160,7 @@ pub struct RegisteredState { pub timeout: Seconds, } -#[derive(Encode, Decode, Default, Copy, Clone, PartialEq, RuntimeDebug)] +#[derive(Encode, Decode, Copy, Clone, PartialEq, RuntimeDebug, TypeInfo)] #[codec(dumb_trait_bound)] /// Withdrawal authorization for on-chain funds. /// @@ -160,6 +179,35 @@ pub struct Withdrawal { pub receiver: AccountId, } +impl Default for Withdrawal +where + ChannelId: Default, + PK: ByteArray + MaxEncodedLen, + AccountId: Default, +{ + fn default() -> Self { + let array_len = PK::max_encoded_len(); + // Create a zero-initialized byte array of the appropriate length + let zero_array = vec![0u8; array_len]; + + // Attempt to create a `PK` instance from the zero-initialized byte array + let part = match PK::from_slice(&zero_array) { + Ok(part) => part, + Err(_) => { + // If creation fails, handle the error (e.g., log an error message or panic) + panic!("Error creating PK instance from zero-initialized array"); + } + }; + + Self { + channel_id: ChannelId::default(), + part: part, + receiver: AccountId::default(), + } + } +} + + #[derive(Encode, Decode, Default, Copy, Clone, PartialEq, RuntimeDebug)] #[codec(dumb_trait_bound)] /// Funding is exclusively used to calculate funding ids via [Funding::id]. diff --git a/src/weights.rs b/src/weights.rs index b176411..22f4879 100644 --- a/src/weights.rs +++ b/src/weights.rs @@ -53,45 +53,45 @@ impl WeightInfo for SubstrateWeight { // Storage: PerunModule Deposits (r:1 w:1) // Storage: System Account (r:1 w:1) fn deposit() -> Weight { - (110_609_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) + (Weight::from_all(110_609_000)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) } // Storage: Timestamp Now (r:1 w:0) // Storage: PerunModule StateRegister (r:1 w:1) fn dispute(p: u32, ) -> Weight { - (1_396_000 as Weight) + (Weight::from_all(1_396_000)) // Standard Error: 25_000 - .saturating_add((87_897_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add((Weight::from_all(87_897_000)).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) } //TODO: benchmark weight and replace constant fn progress(params: &ParamsOf) -> Weight { - return 10_000 + U::AppRegistry::transition_weight(params); + return Weight::from_all(10_000).saturating_add(U::AppRegistry::transition_weight(params)); } // Storage: PerunModule StateRegister (r:1 w:1) // Storage: PerunModule Deposits (r:2 w:2) fn conclude(p: u32, ) -> Weight { - (17_600_000 as Weight) + (Weight::from_all(17_600_000)) // Standard Error: 426_000 - .saturating_add((97_182_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(p as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) + .saturating_add((Weight::from_all(97_182_000)).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(p.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(p.into()))) } //TODO: benchmark weight and replace constant fn conclude_final(_p: u32, ) -> Weight { - return 10_000; + return Weight::from_all(10_000); } // Storage: PerunModule StateRegister (r:1 w:0) // Storage: PerunModule Deposits (r:1 w:1) // Storage: System Account (r:1 w:1) fn withdraw() -> Weight { - (151_546_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) + (Weight::from_all(151_546_000)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) } } @@ -100,44 +100,44 @@ impl WeightInfo for () { // Storage: PerunModule Deposits (r:1 w:1) // Storage: System Account (r:1 w:1) fn deposit() -> Weight { - (110_609_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + (Weight::from_all(110_609_000)) + .saturating_add(RocksDbWeight::get().reads(2)) + .saturating_add(RocksDbWeight::get().writes(2)) } // Storage: Timestamp Now (r:1 w:0) // Storage: PerunModule StateRegister (r:1 w:1) fn dispute(p: u32, ) -> Weight { - (1_396_000 as Weight) + (Weight::from_all(1_396_000)) // Standard Error: 25_000 - .saturating_add((87_897_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add((Weight::from_all(87_897_000)).saturating_mul(p.into())) + .saturating_add(RocksDbWeight::get().reads(2)) + .saturating_add(RocksDbWeight::get().writes(1)) } //TODO: benchmark weight and replace constant fn progress(params: &ParamsOf) -> Weight { - return 10_000 + U::AppRegistry::transition_weight(params); + return Weight::from_all(10_000).saturating_add(U::AppRegistry::transition_weight(params)); } // Storage: PerunModule StateRegister (r:1 w:1) // Storage: PerunModule Deposits (r:2 w:2) fn conclude(p: u32, ) -> Weight { - (17_600_000 as Weight) + (Weight::from_all(17_600_000)) // Standard Error: 426_000 - .saturating_add((97_182_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(p as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) + .saturating_add((Weight::from_all(97_182_000)).saturating_mul(p.into())) + .saturating_add(RocksDbWeight::get().reads(1)) + .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(p.into()))) + .saturating_add(RocksDbWeight::get().writes(1)) + .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(p.into()))) } //TODO: benchmark weight and replace constant fn conclude_final(_p: u32) -> Weight { - return 10_000; + return Weight::from_all(10_000); } // Storage: PerunModule StateRegister (r:1 w:0) // Storage: PerunModule Deposits (r:1 w:1) // Storage: System Account (r:1 w:1) fn withdraw() -> Weight { - (151_546_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + (Weight::from_all(151_546_000)) + .saturating_add(RocksDbWeight::get().reads(3)) + .saturating_add(RocksDbWeight::get().writes(2)) } } diff --git a/tests/common/mock.rs b/tests/common/mock.rs index 2e93f24..13fdab8 100755 --- a/tests/common/mock.rs +++ b/tests/common/mock.rs @@ -16,32 +16,27 @@ use pallet_balances; use super::utils::increment_time; -use frame_support::{dispatch::Weight, parameter_types, PalletId}; +use frame_support::{derive_impl, parameter_types, weights::Weight, PalletId}; use pallet_perun::types::{ AppIdOf, AppRegistry, BalanceOf, FundingIdOf, HasherOf, ParamsOf, ParticipantIndex, StateOf, }; -use sp_core::{crypto::*, H256}; +use sp_core::{crypto::*, ConstU64, H256}; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; use sp_std::ops::Range; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; // For testing the pallet, we construct a mock runtime. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, + pub enum Test { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, - Perun: pallet_perun::{Pallet, Call, Storage, Event}, + System: frame_system, + Balances: pallet_balances, + Timestamp: pallet_timestamp, + Perun: pallet_perun, } ); @@ -50,22 +45,22 @@ parameter_types! { pub const SS58Prefix: u8 = 42; } +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); type BlockLength = (); type DbWeight = (); - type Origin = Origin; - type Call = Call; - type Index = u64; - type BlockNumber = u64; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; - type Header = Header; - type Event = Event; - type BlockHashCount = BlockHashCount; + type Block = Block; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = ConstU64<250>; type Version = (); type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData; @@ -74,6 +69,7 @@ impl frame_system::Config for Test { type SystemWeightInfo = (); type SS58Prefix = SS58Prefix; type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; } parameter_types! { @@ -85,10 +81,15 @@ impl pallet_balances::Config for Test { type ReserveIdentifier = [u8; 8]; type Balance = u64; type DustRemoval = (); - type Event = Event; + type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; type AccountStore = frame_system::Pallet; type WeightInfo = (); + + type RuntimeHoldReason = (); + type RuntimeFreezeReason = (); + type FreezeIdentifier = u64; + type MaxFreezes = (); } parameter_types! { @@ -110,7 +111,7 @@ parameter_types! { pub const NoApp: u64 = NO_APP; } impl pallet_perun::Config for Test { - type Event = Event; + type RuntimeEvent = RuntimeEvent; type PalletId = PerunPalletId; type MinDeposit = PerunMinDeposit; type ParticipantNum = PerunParticipantNum; @@ -173,8 +174,8 @@ impl AppRegistry for MockRegistry { fn transition_weight(params: &ParamsOf) -> Weight { match params.app { - MOCK_APP => return 10_000, - _ => return 0, + MOCK_APP => return Weight::from(10_000), + _ => return Weight::from(0), } } } @@ -229,7 +230,7 @@ pub fn new_setup(app: AppIdOf) -> Setup { /// The Setup is passed to `test`. pub fn run_test(app: AppIdOf, test: fn(&Setup) -> ()) { let setup = new_setup(app); - let mut ext: sp_io::TestExternalities = GenesisConfig { + let mut ext: sp_io::TestExternalities = RuntimeGenesisConfig { // We use default for brevity, but you can configure as desired if needed. system: Default::default(), balances: pallet_balances::GenesisConfig:: { @@ -247,4 +248,4 @@ pub fn run_test(app: AppIdOf, test: fn(&Setup) -> ()) { // Start at block 1 to enable event emission. ext.execute_with(|| increment_time(1)); ext.execute_with(|| test(&setup)) -} +} \ No newline at end of file diff --git a/tests/common/utils.rs b/tests/common/utils.rs index 7828423..d11194c 100644 --- a/tests/common/utils.rs +++ b/tests/common/utils.rs @@ -30,7 +30,7 @@ use sp_core::{crypto::*, H256}; pub fn assert_event_deposited(funding_id: H256, amount: u64) { assert_eq!( last_event(), - Event::Perun(pallet_perun::Event::Deposited(funding_id, amount)) + RuntimeEvent::Perun(pallet_perun::Event::Deposited(funding_id, amount)) ); } @@ -38,7 +38,7 @@ pub fn assert_event_deposited(funding_id: H256, amount: u64) { pub fn assert_event_disputed(channel_id: ChannelIdOf, state: StateOf) { assert_eq!( last_event(), - Event::Perun(pallet_perun::Event::Disputed(channel_id, state)) + RuntimeEvent::Perun(pallet_perun::Event::Disputed(channel_id, state)) ); } @@ -50,7 +50,7 @@ pub fn assert_event_progressed( ) { assert_eq!( last_event(), - Event::Perun(pallet_perun::Event::Progressed(channel_id, version, app)) + RuntimeEvent::Perun(pallet_perun::Event::Progressed(channel_id, version, app)) ); } @@ -58,7 +58,7 @@ pub fn assert_event_progressed( pub fn assert_event_concluded(channel_id: ChannelIdOf) { assert_eq!( last_event(), - Event::Perun(pallet_perun::Event::Concluded(channel_id)) + RuntimeEvent::Perun(pallet_perun::Event::Concluded(channel_id)) ); } @@ -66,13 +66,13 @@ pub fn assert_event_concluded(channel_id: ChannelIdOf) { pub fn event_withdrawn(funding_id: FundingIdOf) { assert_eq!( last_event(), - Event::Perun(pallet_perun::Event::Withdrawn(funding_id)) + RuntimeEvent::Perun(pallet_perun::Event::Withdrawn(funding_id)) ); } /// Returns the last events. /// Panics in case that there is none. -pub fn last_event() -> Event { +pub fn last_event() -> RuntimeEvent { System::events().pop().expect("Event list empty").event } @@ -115,7 +115,7 @@ pub fn call_dispute(setup: &Setup, finalized: bool) -> StateOf { state.finalized = finalized; let sigs = sign_state(&state, &setup); assert_ok!(Perun::dispute( - Origin::signed(setup.ids.carl), + RuntimeOrigin::signed(setup.ids.carl), setup.params.clone(), state.clone(), sigs @@ -141,12 +141,12 @@ pub fn sign_withdrawal(withdrawal: &WithdrawalOf, setup: &Setup) -> Vec::InvalidChannelId ); assert_no_events(); @@ -163,7 +163,7 @@ fn conclude_dispute() { increment_time(2 * setup.params.challenge_duration); assert_ok!(Perun::conclude( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), )); assert_event_concluded(state.channel_id); @@ -185,7 +185,7 @@ fn conclude_progressed() { let signer = 0; assert_ok!(Perun::progress( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs[signer].clone(), @@ -195,7 +195,7 @@ fn conclude_progressed() { increment_time(setup.params.challenge_duration); assert_ok!(Perun::conclude( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), )); assert_event_concluded(state.channel_id); @@ -218,7 +218,7 @@ fn conclude_insufficient_deposits() { let alice_deposits = Perun::deposits(setup.fids.alice); let bob_deposits = Perun::deposits(setup.fids.bob); assert_ok!(Perun::conclude_final( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs @@ -241,7 +241,7 @@ fn conclude_final_already_concluded() { let sigs = sign_state(&state, &setup); assert_ok!(Perun::conclude_final( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs.clone() @@ -250,7 +250,7 @@ fn conclude_final_already_concluded() { // Twice works, but no new event will be emitted. let events = num_events(); assert_ok!(Perun::conclude_final( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs.clone() @@ -262,7 +262,7 @@ fn conclude_final_already_concluded() { let sigs = sign_state(&state, &setup); assert_noop!( Perun::conclude_final( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs @@ -280,14 +280,14 @@ fn conclude_twice() { increment_time(2 * setup.params.challenge_duration); assert_ok!(Perun::conclude( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), )); // Twice works, but no new event will be emitted. let events = num_events(); assert_ok!(Perun::conclude( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), )); assert_num_event(events); @@ -302,7 +302,7 @@ fn conclude_too_early_app() { increment_time(setup.params.challenge_duration); assert_noop!( - Perun::conclude(Origin::signed(setup.ids.alice), setup.params.clone(),), + Perun::conclude(RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(),), pallet_perun::Error::::ConcludedTooEarly ); }); @@ -316,7 +316,7 @@ fn conclude_too_early_no_app() { increment_time(setup.params.challenge_duration / 2); assert_noop!( - Perun::conclude(Origin::signed(setup.ids.alice), setup.params.clone(),), + Perun::conclude(RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(),), pallet_perun::Error::::ConcludedTooEarly ); }); diff --git a/tests/deposit.rs b/tests/deposit.rs index 408a221..f473a55 100755 --- a/tests/deposit.rs +++ b/tests/deposit.rs @@ -29,7 +29,7 @@ fn deposit_some() { assert_eq!(Balances::free_balance(setup.ids.alice), 100); // Alice deposits 10. assert_ok!(Perun::deposit( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.fids.alice, 10 )); @@ -49,12 +49,12 @@ fn deposit_event_absolute() { run_test(MOCK_APP, |setup| { // Alice deposits 10 and then 20. assert_ok!(Perun::deposit( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.fids.alice, 10 )); assert_ok!(Perun::deposit( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.fids.alice, 20 )); @@ -79,7 +79,7 @@ fn deposit_amount_too_low() { ); // Charlie deposits too few. assert_noop!( - Perun::deposit(Origin::signed(setup.ids.carl), setup.fids.alice, min - 1), + Perun::deposit(RuntimeOrigin::signed(setup.ids.carl), setup.fids.alice, min - 1), Error::::DepositTooSmall ); // Holdings are now 0. @@ -105,11 +105,11 @@ fn deposit_insufficient_balance() { // Dora tries to deposit more than she has. assert_noop!( Perun::deposit( - Origin::signed(setup.ids.dora), + RuntimeOrigin::signed(setup.ids.dora), setup.fids.alice, PerunMinDeposit::get() ), - pallet_balances::Error::::InsufficientBalance + sp_runtime::TokenError::FundsUnavailable ); // Holdings are 0. assert_eq!(Perun::deposits(setup.fids.alice), None); @@ -125,14 +125,14 @@ fn deposit_overflow() { run_test(MOCK_APP, |setup| { // Alice deposits 10. assert_ok!(Perun::deposit( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.fids.alice, 10 )); assert_noop!( Perun::deposit( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.fids.alice, BalanceOf::::MAX, ), diff --git a/tests/dispute.rs b/tests/dispute.rs index 6151bd2..149c479 100755 --- a/tests/dispute.rs +++ b/tests/dispute.rs @@ -25,7 +25,7 @@ fn dispute_ok() { let sigs = sign_state(&setup.state, &setup); assert_ok!(Perun::dispute( - Origin::signed(setup.ids.carl), + RuntimeOrigin::signed(setup.ids.carl), setup.params.clone(), setup.state.clone(), sigs @@ -44,7 +44,7 @@ fn dispute_final() { assert_noop!( Perun::dispute( - Origin::signed(setup.ids.carl), + RuntimeOrigin::signed(setup.ids.carl), setup.params.clone(), state, sigs @@ -65,7 +65,7 @@ fn dispute_already_concluded() { let sigs = sign_state(&state, &setup); assert_ok!(Perun::conclude_final( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs.clone() @@ -74,7 +74,7 @@ fn dispute_already_concluded() { let sigs = sign_state(&setup.state, &setup); assert_noop!( Perun::dispute( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), setup.state.clone(), sigs @@ -95,7 +95,7 @@ fn dispute_challenge_duration_overflow() { increment_time(1); assert_noop!( - Perun::dispute(Origin::signed(setup.ids.carl), params, state, sigs), + Perun::dispute(RuntimeOrigin::signed(setup.ids.carl), params, state, sigs), pallet_perun::Error::::ChallengeDurationOverflow ); assert_no_events(); @@ -111,7 +111,7 @@ fn dispute_invalid_part_num() { for bad_sig in bad_sigs { assert_noop!( Perun::dispute( - Origin::signed(setup.ids.carl), + RuntimeOrigin::signed(setup.ids.carl), setup.params.clone(), setup.state.clone(), bad_sig @@ -134,7 +134,7 @@ fn dispute_invalid_sig_nums() { for bad_sig in bad_sigs { assert_noop!( Perun::dispute( - Origin::signed(setup.ids.carl), + RuntimeOrigin::signed(setup.ids.carl), setup.params.clone(), setup.state.clone(), bad_sig @@ -162,7 +162,7 @@ fn dispute_invalid_sig() { for sig in sigs { assert_noop!( Perun::dispute( - Origin::signed(setup.ids.carl), + RuntimeOrigin::signed(setup.ids.carl), setup.params.clone(), setup.state.clone(), sig, @@ -184,7 +184,7 @@ fn dispute_invalid_channel_id() { // Different nonce assert_noop!( Perun::dispute( - Origin::signed(setup.ids.carl), + RuntimeOrigin::signed(setup.ids.carl), params, setup.state.clone(), sigs, @@ -201,7 +201,7 @@ fn dispute_invalid_channel_id() { // Different parts assert_noop!( Perun::dispute( - Origin::signed(setup.ids.carl), + RuntimeOrigin::signed(setup.ids.carl), params, setup.state.clone(), sigs, @@ -218,7 +218,7 @@ fn dispute_invalid_channel_id() { // Different challenge duration assert_noop!( Perun::dispute( - Origin::signed(setup.ids.carl), + RuntimeOrigin::signed(setup.ids.carl), params, setup.state.clone(), sigs, @@ -235,7 +235,7 @@ fn dispute_invalid_channel_id() { // Different Channel ID in State assert_noop!( Perun::dispute( - Origin::signed(setup.ids.carl), + RuntimeOrigin::signed(setup.ids.carl), setup.params.clone(), state.clone(), sigs, @@ -256,7 +256,7 @@ fn dispute_same_version() { let sigs = sign_state(&setup.state, &setup); assert_noop!( Perun::dispute( - Origin::signed(setup.ids.carl), + RuntimeOrigin::signed(setup.ids.carl), setup.params.clone(), setup.state.clone(), sigs @@ -281,7 +281,7 @@ fn dispute_higher_version() { let sigs = sign_state(&state, &setup); assert_ok!(Perun::dispute( - Origin::signed(setup.ids.carl), + RuntimeOrigin::signed(setup.ids.carl), setup.params.clone(), state.clone(), sigs @@ -307,7 +307,7 @@ fn dispute_timeout() { assert_noop!( Perun::dispute( - Origin::signed(setup.ids.carl), + RuntimeOrigin::signed(setup.ids.carl), setup.params.clone(), state.clone(), sigs diff --git a/tests/progress.rs b/tests/progress.rs index 96f4bee..f0eda3f 100644 --- a/tests/progress.rs +++ b/tests/progress.rs @@ -36,7 +36,7 @@ fn progress() { let signer = 0; assert_ok!(Perun::progress( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs[signer].clone(), @@ -62,7 +62,7 @@ fn progress_no_app() { let signer = 0; assert_noop!( Perun::progress( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs[signer].clone(), @@ -90,7 +90,7 @@ fn progress_invalid_signature() { let not_signer = 1; assert_noop!( Perun::progress( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs[signer].clone(), @@ -116,7 +116,7 @@ fn progress_invalid_version() { let signer = 0; assert_noop!( Perun::progress( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs[signer].clone(), @@ -144,7 +144,7 @@ fn progress_invalid_balances() { let signer = 0; assert_noop!( Perun::progress( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs[signer].clone(), @@ -171,7 +171,7 @@ fn progress_final() { let signer = 0; assert_ok!(Perun::progress( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs[signer].clone(), @@ -185,7 +185,7 @@ fn progress_final() { let signer = 0; assert_noop!( Perun::progress( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs[signer].clone(), @@ -214,7 +214,7 @@ fn progress_invalid_app_transition() { let signer = 0; assert_noop!( Perun::progress( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs[signer].clone(), @@ -241,7 +241,7 @@ fn progress_too_early() { let signer = 0; assert_noop!( Perun::progress( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs[signer].clone(), @@ -267,7 +267,7 @@ fn progress_already_concluded() { let signer = 0; assert_ok!(Perun::progress( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs[signer].clone(), @@ -278,7 +278,7 @@ fn progress_already_concluded() { increment_time(setup.params.challenge_duration); assert_ok!(Perun::conclude( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), )); assert_event_concluded(state.channel_id); @@ -287,7 +287,7 @@ fn progress_already_concluded() { let sigs = sign_state(&state, &setup); assert_noop!( Perun::progress( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs[signer].clone(), diff --git a/tests/unit.rs b/tests/unit.rs index 69f2929..74bad9f 100755 --- a/tests/unit.rs +++ b/tests/unit.rs @@ -41,8 +41,15 @@ fn push_outcome_invalid_parts() { #[cfg(feature = "expose_privates")] #[test] fn push_outcome_invalid_outcome() { + use pallet_perun::types::PkOf; + run_test(MOCK_APP, |setup| { - let parts: Vec> = vec![Default::default(); 2]; + let mut parts = Vec::new(); + for _ in 0..2 { + let zero = vec![0; 33]; + let pk_instance = PkOf::::from_full(&zero).expect("Failed to create PkOf instance"); + parts.push(pk_instance); + } let bals: Vec> = vec![BalanceOf::::MAX, 1]; assert_noop!( @@ -69,14 +76,15 @@ fn time_now() { fn unsigned_tx() { run_test(MOCK_APP, |_| { assert_noop!( - Perun::deposit(Origin::none(), Default::default(), Default::default()), + Perun::deposit(RuntimeOrigin::none(), Default::default(), Default::default()), BadOrigin ); }); + run_test(MOCK_APP, |_| { assert_noop!( Perun::dispute( - Origin::none(), + RuntimeOrigin::none(), Default::default(), Default::default(), Default::default() @@ -86,14 +94,14 @@ fn unsigned_tx() { }); run_test(MOCK_APP, |_| { assert_noop!( - Perun::conclude(Origin::none(), Default::default(),), + Perun::conclude(RuntimeOrigin::none(), Default::default(),), BadOrigin ); }); run_test(MOCK_APP, |_| { assert_noop!( Perun::conclude_final( - Origin::none(), + RuntimeOrigin::none(), Default::default(), Default::default(), Default::default() @@ -103,7 +111,7 @@ fn unsigned_tx() { }); run_test(MOCK_APP, |_| { assert_noop!( - Perun::withdraw(Origin::none(), Default::default(), Default::default()), + Perun::withdraw(RuntimeOrigin::none(), Default::default(), Default::default()), BadOrigin ); }); diff --git a/tests/withdraw.rs b/tests/withdraw.rs index 8279e63..a8d411a 100755 --- a/tests/withdraw.rs +++ b/tests/withdraw.rs @@ -32,7 +32,7 @@ fn withdraw_invalid_sig() { assert_noop!( Perun::withdraw( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), withdrawal, Default::default() ), @@ -52,7 +52,7 @@ fn withdraw_unknown_channel() { let sigs = sign_withdrawal(&withdrawal, setup); assert_noop!( - Perun::withdraw(Origin::signed(setup.ids.alice), withdrawal, sigs[0].clone()), + Perun::withdraw(RuntimeOrigin::signed(setup.ids.alice), withdrawal, sigs[0].clone()), pallet_perun::Error::::UnknownChannel ); }); @@ -72,7 +72,7 @@ fn withdraw_not_concluded() { let sigs = sign_withdrawal(&withdrawal, setup); assert_noop!( - Perun::withdraw(Origin::signed(setup.ids.alice), withdrawal, sigs[0].clone()), + Perun::withdraw(RuntimeOrigin::signed(setup.ids.alice), withdrawal, sigs[0].clone()), pallet_perun::Error::::NotConcluded ); }); @@ -86,7 +86,7 @@ fn withdraw_unknown_participant() { state.balances = vec![0, 0]; let sigs = sign_state(&state, &setup); assert_ok!(Perun::conclude_final( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs @@ -102,7 +102,7 @@ fn withdraw_unknown_participant() { assert_noop!( Perun::withdraw( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), withdrawal, sig_carl.clone() ), @@ -128,7 +128,7 @@ fn withdraw_ok() { let sigs = sign_state(&state, &setup); assert_ok!(Perun::conclude_final( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), setup.params.clone(), state.clone(), sigs @@ -144,7 +144,7 @@ fn withdraw_ok() { let sigs = sign_withdrawal(&withdrawal, setup); assert_ok!(Perun::withdraw( - Origin::signed(setup.ids.alice), + RuntimeOrigin::signed(setup.ids.alice), withdrawal.clone(), sigs[0].clone() ),); @@ -153,7 +153,7 @@ fn withdraw_ok() { assert_eq!(Balances::free_balance(setup.ids.alice), 95); // Withdrawing twice errors. assert_noop!( - Perun::withdraw(Origin::signed(setup.ids.alice), withdrawal, sigs[0].clone()), + Perun::withdraw(RuntimeOrigin::signed(setup.ids.alice), withdrawal, sigs[0].clone()), pallet_perun::Error::::UnknownDeposit ); } @@ -167,7 +167,7 @@ fn withdraw_ok() { let sigs = sign_withdrawal(&withdrawal, setup); assert_ok!(Perun::withdraw( - Origin::signed(setup.ids.bob), + RuntimeOrigin::signed(setup.ids.bob), withdrawal.clone(), sigs[1].clone() ),); @@ -176,7 +176,7 @@ fn withdraw_ok() { assert_eq!(Balances::free_balance(setup.ids.bob), 105); // Withdrawing twice errors. assert_noop!( - Perun::withdraw(Origin::signed(setup.ids.bob), withdrawal, sigs[1].clone()), + Perun::withdraw(RuntimeOrigin::signed(setup.ids.bob), withdrawal, sigs[1].clone()), pallet_perun::Error::::UnknownDeposit ); } From a3310366bb4e3345eb73085cdb5db600d8bfad25 Mon Sep 17 00:00:00 2001 From: Minh Huy Tran Date: Mon, 22 Apr 2024 11:28:48 +0200 Subject: [PATCH 2/7] fix: add module edition Signed-off-by: Minh Huy Tran --- .github/workflows/rust.yml | 8 ++++---- Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 49baedc..b8eb26e 100755 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -17,14 +17,14 @@ jobs: KCOV_OUT: "target/cov/pallet_perun" KCOV: "~/cache/usr/local/bin/kcov" steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 with: fetch-depth: 2 # CodeCov needs this - uses: actions-rs/toolchain@v1 with: toolchain: nightly - - uses: Swatinem/rust-cache@v1 + - uses: Swatinem/rust-cache@v2 name: Setup Cache - uses: actions-rs/cargo@v1 @@ -64,7 +64,7 @@ jobs: args: --all-targets --all-features - name: kcov cache - uses: actions/cache@v2 + uses: actions/cache@v4 with: path: ~/cache key: ${{ runner.os }}-kcov-wget @@ -141,7 +141,7 @@ jobs: $KCOV --merge "$KCOV_OUT/merged" "$KCOV_OUT"/unmerged-* - name: CodeCov upload - uses: codecov/codecov-action@v2 + uses: codecov/codecov-action@v4 with: directory: "${{ env.KCOV_OUT }}/merged" fail_ci_if_error: true diff --git a/Cargo.toml b/Cargo.toml index 52e2bda..5dfc2dc 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ keywords = ["blockchain", "channel", "perun"] repository = "https://github.com/perun-network/perun-polkadot-pallet" description = "FRAME pallet for Perun State Channels" readme = "README.md" -edition.workspace = true +edition = "2021" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] From 8842a7cd9dc32f327afeefcd6f8a8c3a17e79a1c Mon Sep 17 00:00:00 2001 From: Minh Huy Tran Date: Mon, 22 Apr 2024 11:43:16 +0200 Subject: [PATCH 3/7] fix: CI cargo fmt Signed-off-by: Minh Huy Tran --- src/lib.rs | 13 +++++++--- src/types.rs | 62 +++++++++++++++++++++----------------------- tests/common/mock.rs | 10 +++---- tests/conclude.rs | 7 ++++- tests/deposit.rs | 6 ++++- tests/unit.rs | 17 +++++++++--- tests/withdraw.rs | 24 ++++++++++++++--- 7 files changed, 88 insertions(+), 51 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index c3d1353..c0bec7e 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,7 +41,7 @@ use frame_support::{ PalletId, }; use frame_system::{ensure_signed, pallet_prelude::*}; -use sp_runtime::traits::{ AccountIdConversion, CheckedAdd, IdentifyAccount, Verify }; +use sp_runtime::traits::{AccountIdConversion, CheckedAdd, IdentifyAccount, Verify}; use sp_std::{cmp, convert::TryFrom, ops::Range, vec::Vec}; macro_rules! require { @@ -61,7 +61,7 @@ pub mod pallet { traits::{ExistenceRequirement, Get}, }; use sp_core::ByteArray; -use sp_runtime::traits::{CheckedAdd, Member}; + use sp_runtime::traits::{CheckedAdd, Member}; #[pallet::config] pub trait Config: frame_system::Config + pallet_timestamp::Config { @@ -106,7 +106,12 @@ use sp_runtime::traits::{CheckedAdd, Member}; /// Must be possible to verify that a [Config::PK] created a signature. type Signature: Encode + Decode + Member + TypeInfo + Verify; /// PK of a [Config::Signature]. - type PK: Encode + Decode + Member + ByteArray + TypeInfo + IdentifyAccount; + type PK: Encode + + Decode + + Member + + ByteArray + + TypeInfo + + IdentifyAccount; /// Represent a time duration in seconds. type Seconds: FullCodec + Member + TypeInfo + CheckedAdd + PartialOrd + From; @@ -243,7 +248,7 @@ use sp_runtime::traits::{CheckedAdd, Member}; /// /// Emits an [Event::Deposited] event on success. #[pallet::weight(WeightInfoOf::::deposit())] - #[pallet::call_index(0)] + #[pallet::call_index(0)] pub fn deposit( origin: OriginFor, funding_id: FundingIdOf, diff --git a/src/types.rs b/src/types.rs index 3616ecd..0b897f6 100755 --- a/src/types.rs +++ b/src/types.rs @@ -16,9 +16,9 @@ use crate::*; +use crate::pallet::Config; use codec::{Decode, Encode}; use sp_core::{ByteArray, Hasher}; -use crate::pallet::Config; use sp_runtime::{ traits::{IdentifyAccount, Verify}, RuntimeDebug, @@ -86,21 +86,20 @@ pub struct Params { impl Default for Params where Nonce: Default, - Vec: Default, // This is crucial for initializing an empty vector of PK - Seconds: Default, - AppId: Default, + Vec: Default, // This is crucial for initializing an empty vector of PK + Seconds: Default, + AppId: Default, { - fn default() -> Self { - Self { - nonce: Nonce::default(), - participants: Vec::default(), // Initialize an empty vector of PK - challenge_duration: Seconds::default(), - app: AppId::default(), - } - } + fn default() -> Self { + Self { + nonce: Nonce::default(), + participants: Vec::default(), // Initialize an empty vector of PK + challenge_duration: Seconds::default(), + app: AppId::default(), + } + } } - #[derive(Encode, Decode, Default, Clone, PartialEq, RuntimeDebug, TypeInfo)] #[codec(dumb_trait_bound)] /// Off-Chain state of a channel. @@ -181,33 +180,32 @@ pub struct Withdrawal { impl Default for Withdrawal where - ChannelId: Default, + ChannelId: Default, PK: ByteArray + MaxEncodedLen, - AccountId: Default, + AccountId: Default, { - fn default() -> Self { + fn default() -> Self { let array_len = PK::max_encoded_len(); // Create a zero-initialized byte array of the appropriate length let zero_array = vec![0u8; array_len]; - // Attempt to create a `PK` instance from the zero-initialized byte array - let part = match PK::from_slice(&zero_array) { - Ok(part) => part, - Err(_) => { - // If creation fails, handle the error (e.g., log an error message or panic) - panic!("Error creating PK instance from zero-initialized array"); - } - }; - - Self { - channel_id: ChannelId::default(), - part: part, - receiver: AccountId::default(), - } - } + // Attempt to create a `PK` instance from the zero-initialized byte array + let part = match PK::from_slice(&zero_array) { + Ok(part) => part, + Err(_) => { + // If creation fails, handle the error (e.g., log an error message or panic) + panic!("Error creating PK instance from zero-initialized array"); + } + }; + + Self { + channel_id: ChannelId::default(), + part: part, + receiver: AccountId::default(), + } + } } - #[derive(Encode, Decode, Default, Copy, Clone, PartialEq, RuntimeDebug)] #[codec(dumb_trait_bound)] /// Funding is exclusively used to calculate funding ids via [Funding::id]. diff --git a/tests/common/mock.rs b/tests/common/mock.rs index 13fdab8..1886230 100755 --- a/tests/common/mock.rs +++ b/tests/common/mock.rs @@ -31,7 +31,7 @@ type Block = frame_system::mocking::MockBlock; // For testing the pallet, we construct a mock runtime. frame_support::construct_runtime!( - pub enum Test + pub enum Test { System: frame_system, Balances: pallet_balances, @@ -86,10 +86,10 @@ impl pallet_balances::Config for Test { type AccountStore = frame_system::Pallet; type WeightInfo = (); - type RuntimeHoldReason = (); + type RuntimeHoldReason = (); type RuntimeFreezeReason = (); - type FreezeIdentifier = u64; - type MaxFreezes = (); + type FreezeIdentifier = u64; + type MaxFreezes = (); } parameter_types! { @@ -248,4 +248,4 @@ pub fn run_test(app: AppIdOf, test: fn(&Setup) -> ()) { // Start at block 1 to enable event emission. ext.execute_with(|| increment_time(1)); ext.execute_with(|| test(&setup)) -} \ No newline at end of file +} diff --git a/tests/conclude.rs b/tests/conclude.rs index cfe347c..447cd76 100755 --- a/tests/conclude.rs +++ b/tests/conclude.rs @@ -147,7 +147,12 @@ fn conclude_invalid_channel_id() { // Different nonce assert_noop!( - Perun::conclude_final(RuntimeOrigin::signed(setup.ids.carl), params, state.clone(), sigs), + Perun::conclude_final( + RuntimeOrigin::signed(setup.ids.carl), + params, + state.clone(), + sigs + ), pallet_perun::Error::::InvalidChannelId ); assert_no_events(); diff --git a/tests/deposit.rs b/tests/deposit.rs index f473a55..b426408 100755 --- a/tests/deposit.rs +++ b/tests/deposit.rs @@ -79,7 +79,11 @@ fn deposit_amount_too_low() { ); // Charlie deposits too few. assert_noop!( - Perun::deposit(RuntimeOrigin::signed(setup.ids.carl), setup.fids.alice, min - 1), + Perun::deposit( + RuntimeOrigin::signed(setup.ids.carl), + setup.fids.alice, + min - 1 + ), Error::::DepositTooSmall ); // Holdings are now 0. diff --git a/tests/unit.rs b/tests/unit.rs index 74bad9f..908dec0 100755 --- a/tests/unit.rs +++ b/tests/unit.rs @@ -41,13 +41,14 @@ fn push_outcome_invalid_parts() { #[cfg(feature = "expose_privates")] #[test] fn push_outcome_invalid_outcome() { - use pallet_perun::types::PkOf; + use pallet_perun::types::PkOf; run_test(MOCK_APP, |setup| { let mut parts = Vec::new(); for _ in 0..2 { let zero = vec![0; 33]; - let pk_instance = PkOf::::from_full(&zero).expect("Failed to create PkOf instance"); + let pk_instance = + PkOf::::from_full(&zero).expect("Failed to create PkOf instance"); parts.push(pk_instance); } let bals: Vec> = vec![BalanceOf::::MAX, 1]; @@ -76,7 +77,11 @@ fn time_now() { fn unsigned_tx() { run_test(MOCK_APP, |_| { assert_noop!( - Perun::deposit(RuntimeOrigin::none(), Default::default(), Default::default()), + Perun::deposit( + RuntimeOrigin::none(), + Default::default(), + Default::default() + ), BadOrigin ); }); @@ -111,7 +116,11 @@ fn unsigned_tx() { }); run_test(MOCK_APP, |_| { assert_noop!( - Perun::withdraw(RuntimeOrigin::none(), Default::default(), Default::default()), + Perun::withdraw( + RuntimeOrigin::none(), + Default::default(), + Default::default() + ), BadOrigin ); }); diff --git a/tests/withdraw.rs b/tests/withdraw.rs index a8d411a..71f0496 100755 --- a/tests/withdraw.rs +++ b/tests/withdraw.rs @@ -52,7 +52,11 @@ fn withdraw_unknown_channel() { let sigs = sign_withdrawal(&withdrawal, setup); assert_noop!( - Perun::withdraw(RuntimeOrigin::signed(setup.ids.alice), withdrawal, sigs[0].clone()), + Perun::withdraw( + RuntimeOrigin::signed(setup.ids.alice), + withdrawal, + sigs[0].clone() + ), pallet_perun::Error::::UnknownChannel ); }); @@ -72,7 +76,11 @@ fn withdraw_not_concluded() { let sigs = sign_withdrawal(&withdrawal, setup); assert_noop!( - Perun::withdraw(RuntimeOrigin::signed(setup.ids.alice), withdrawal, sigs[0].clone()), + Perun::withdraw( + RuntimeOrigin::signed(setup.ids.alice), + withdrawal, + sigs[0].clone() + ), pallet_perun::Error::::NotConcluded ); }); @@ -153,7 +161,11 @@ fn withdraw_ok() { assert_eq!(Balances::free_balance(setup.ids.alice), 95); // Withdrawing twice errors. assert_noop!( - Perun::withdraw(RuntimeOrigin::signed(setup.ids.alice), withdrawal, sigs[0].clone()), + Perun::withdraw( + RuntimeOrigin::signed(setup.ids.alice), + withdrawal, + sigs[0].clone() + ), pallet_perun::Error::::UnknownDeposit ); } @@ -176,7 +188,11 @@ fn withdraw_ok() { assert_eq!(Balances::free_balance(setup.ids.bob), 105); // Withdrawing twice errors. assert_noop!( - Perun::withdraw(RuntimeOrigin::signed(setup.ids.bob), withdrawal, sigs[1].clone()), + Perun::withdraw( + RuntimeOrigin::signed(setup.ids.bob), + withdrawal, + sigs[1].clone() + ), pallet_perun::Error::::UnknownDeposit ); } From 450d952fe5914e6e78d8ab65659adba4dc6c56b5 Mon Sep 17 00:00:00 2001 From: Minh Huy Tran Date: Mon, 22 Apr 2024 12:30:58 +0200 Subject: [PATCH 4/7] fix: null PK in unit test Signed-off-by: Minh Huy Tran --- tests/unit.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/unit.rs b/tests/unit.rs index 908dec0..3570410 100755 --- a/tests/unit.rs +++ b/tests/unit.rs @@ -47,8 +47,13 @@ fn push_outcome_invalid_outcome() { let mut parts = Vec::new(); for _ in 0..2 { let zero = vec![0; 33]; - let pk_instance = - PkOf::::from_full(&zero).expect("Failed to create PkOf instance"); + let zero_slice: [u8; 33] = { + // Create an array of exactly 33 elements by converting the Vec to an array + let mut array = [0; 33]; + array.copy_from_slice(&zero[..33]); // Copy the first 33 elements of zero into the array + array + }; + let pk_instance = PkOf::::from_raw(zero_slice); parts.push(pk_instance); } let bals: Vec> = vec![BalanceOf::::MAX, 1]; From 84d3e4bc01d8436dcb1444066fb908dd82ce0fbf Mon Sep 17 00:00:00 2001 From: Minh Huy Tran Date: Mon, 22 Apr 2024 12:55:08 +0200 Subject: [PATCH 5/7] CI: add token for codecov Signed-off-by: Minh Huy Tran --- .github/workflows/rust.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index b8eb26e..25a3981 100755 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -143,5 +143,6 @@ jobs: - name: CodeCov upload uses: codecov/codecov-action@v4 with: + token: ${{ secrets.CODECOV_TOKEN }} directory: "${{ env.KCOV_OUT }}/merged" fail_ci_if_error: true From 0fd4c062f1f60f95bb3e83428a36fb09c9272bce Mon Sep 17 00:00:00 2001 From: Minh Huy Tran Date: Tue, 23 Apr 2024 10:38:48 +0200 Subject: [PATCH 6/7] chore: fix package name and unclean code Signed-off-by: Minh Huy Tran --- Cargo.toml | 3 +-- tests/unit.rs | 8 +------- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5dfc2dc..9bccff3 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,8 +31,7 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = ] } scale-info = { version = "2.10.0", default-features = false, features = [ "derive", -] } -syn = "=1.0.109" +] } [dev-dependencies] sp-core = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-v1.9.0" } diff --git a/tests/unit.rs b/tests/unit.rs index 3570410..e39f6ee 100755 --- a/tests/unit.rs +++ b/tests/unit.rs @@ -46,13 +46,7 @@ fn push_outcome_invalid_outcome() { run_test(MOCK_APP, |setup| { let mut parts = Vec::new(); for _ in 0..2 { - let zero = vec![0; 33]; - let zero_slice: [u8; 33] = { - // Create an array of exactly 33 elements by converting the Vec to an array - let mut array = [0; 33]; - array.copy_from_slice(&zero[..33]); // Copy the first 33 elements of zero into the array - array - }; + let zero_slice = [0u8; 33]; let pk_instance = PkOf::::from_raw(zero_slice); parts.push(pk_instance); } From 09452ee7e0bbbc84fc0186510bd665347a391c4f Mon Sep 17 00:00:00 2001 From: Minh Huy Tran Date: Tue, 23 Apr 2024 10:47:02 +0200 Subject: [PATCH 7/7] chore: cargo clippy Signed-off-by: Minh Huy Tran --- src/lib.rs | 18 +++++++++--------- src/types.rs | 4 ++-- src/weights.rs | 8 ++++---- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index c0bec7e..aebb810 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -257,7 +257,7 @@ pub mod pallet { let who = ensure_signed(origin)?; ensure!(amount >= T::MinDeposit::get(), Error::::DepositTooSmall); // Check that a deposit would not overflow, return on failure. - let holding = >::get(&funding_id).unwrap_or_default(); + let holding = >::get(funding_id).unwrap_or_default(); // An overflow here can happen if a user wants to deposit more than he has. let new_holdings = holding .checked_add(&amount) @@ -266,7 +266,7 @@ pub mod pallet { let account_id = Self::account_id(); T::Currency::transfer(&who, &account_id, amount, ExistenceRequirement::KeepAlive)?; // Update the holdings in the deposits map. - >::insert(&funding_id, &new_holdings); + >::insert(funding_id, new_holdings); // Emit the 'Deposited' event. Self::deposit_event(Event::Deposited(funding_id, new_holdings)); Ok(()) @@ -299,7 +299,7 @@ pub mod pallet { let channel_id = state.channel_id; let now = Self::now(); - match >::get(&channel_id) { + match >::get(channel_id) { None => { let timeout = now .checked_add(¶ms.challenge_duration) @@ -413,7 +413,7 @@ pub mod pallet { pub fn conclude(origin: OriginFor, params: ParamsOf) -> DispatchResult { ensure_signed(origin)?; let channel_id = params.channel_id::(); - match >::get(&channel_id) { + match >::get(channel_id) { Some(dispute) => { if dispute.phase == Phase::Conclude { return Ok(()); @@ -470,7 +470,7 @@ pub mod pallet { ensure!(state.finalized, Error::::StateNotFinal); // Check if this channel is being disputed. - if let Some(dispute) = >::get(&channel_id) { + if let Some(dispute) = >::get(channel_id) { if dispute.phase == Phase::Conclude { ensure!( dispute.state.version == state.version, @@ -587,7 +587,7 @@ impl Pallet { for (i, part) in parts.iter().enumerate() { let fid = Self::calc_funding_id(channel, part); fids.push(fid); - let deposit = >::get(&fid).unwrap_or_default(); + let deposit = >::get(fid).unwrap_or_default(); sum_outcome = sum_outcome .checked_add(&outcome[i]) @@ -607,7 +607,7 @@ impl Pallet { if sum_deposit >= sum_outcome { // We redistribute the funds according to the outcome. for (i, fid) in fids.iter().enumerate() { - >::insert(&fid, outcome[i]); + >::insert(fid, outcome[i]); } } Ok(()) @@ -694,7 +694,7 @@ impl Pallet { require!(cur_acc == next_acc); frame_support::runtime_print!("PerunPallet:after check balances"); - return T::AppRegistry::valid_transition(params, current, next, signer); + T::AppRegistry::valid_transition(params, current, next, signer) } fn accumulate_balances(balances: &[BalanceOf]) -> BalanceOf { @@ -702,6 +702,6 @@ impl Pallet { for b in balances.iter() { acc += *b; } - return acc; + acc } } diff --git a/src/types.rs b/src/types.rs index 0b897f6..ad83edf 100755 --- a/src/types.rs +++ b/src/types.rs @@ -200,7 +200,7 @@ where Self { channel_id: ChannelId::default(), - part: part, + part, receiver: AccountId::default(), } } @@ -226,7 +226,7 @@ where pub fn has_app>(&self) -> bool { let no_app = T::NoApp::get(); - return self.app != no_app; + self.app != no_app } } diff --git a/src/weights.rs b/src/weights.rs index 22f4879..73789f1 100644 --- a/src/weights.rs +++ b/src/weights.rs @@ -68,7 +68,7 @@ impl WeightInfo for SubstrateWeight { } //TODO: benchmark weight and replace constant fn progress(params: &ParamsOf) -> Weight { - return Weight::from_all(10_000).saturating_add(U::AppRegistry::transition_weight(params)); + Weight::from_all(10_000).saturating_add(U::AppRegistry::transition_weight(params)) } // Storage: PerunModule StateRegister (r:1 w:1) // Storage: PerunModule Deposits (r:2 w:2) @@ -83,7 +83,7 @@ impl WeightInfo for SubstrateWeight { } //TODO: benchmark weight and replace constant fn conclude_final(_p: u32, ) -> Weight { - return Weight::from_all(10_000); + Weight::from_all(10_000) } // Storage: PerunModule StateRegister (r:1 w:0) // Storage: PerunModule Deposits (r:1 w:1) @@ -115,7 +115,7 @@ impl WeightInfo for () { } //TODO: benchmark weight and replace constant fn progress(params: &ParamsOf) -> Weight { - return Weight::from_all(10_000).saturating_add(U::AppRegistry::transition_weight(params)); + Weight::from_all(10_000).saturating_add(U::AppRegistry::transition_weight(params)) } // Storage: PerunModule StateRegister (r:1 w:1) // Storage: PerunModule Deposits (r:2 w:2) @@ -130,7 +130,7 @@ impl WeightInfo for () { } //TODO: benchmark weight and replace constant fn conclude_final(_p: u32) -> Weight { - return Weight::from_all(10_000); + Weight::from_all(10_000) } // Storage: PerunModule StateRegister (r:1 w:0) // Storage: PerunModule Deposits (r:1 w:1)