diff --git a/Cargo.lock b/Cargo.lock index cc7097e..715f5d5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4566,6 +4566,7 @@ name = "node-template-runtime" version = "4.0.0-dev" dependencies = [ "department-funding", + "department-funding-runtime-api", "frame-benchmarking", "frame-executive", "frame-support", @@ -4584,9 +4585,11 @@ dependencies = [ "pallet-transaction-payment-rpc-runtime-api", "parity-scale-codec", "positive-externality", + "positive-externality-runtime-api", "profile-validation", "profile-validation-runtime-api", "project-tips", + "project-tips-runtime-api", "scale-info", "schelling-game-shared", "shared-storage", diff --git a/node/src/command.rs b/node/src/command.rs index e121db8..c90feef 100644 --- a/node/src/command.rs +++ b/node/src/command.rs @@ -42,8 +42,9 @@ impl SubstrateCli for Cli { Ok(match id { "dev" => Box::new(chain_spec::development_config()?), "" | "local" => Box::new(chain_spec::local_testnet_config()?), - path => - Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?), + path => { + Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?) + }, }) } @@ -121,7 +122,7 @@ pub fn run() -> sc_cli::Result<()> { "Runtime benchmarking wasn't enabled when building the node. \ You can enable it with `--features runtime-benchmarks`." .into(), - ) + ); } cmd.run::(config) @@ -170,8 +171,9 @@ pub fn run() -> sc_cli::Result<()> { cmd.run(client, inherent_benchmark_data()?, Vec::new(), &ext_factory) }, - BenchmarkCmd::Machine(cmd) => - cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()), + BenchmarkCmd::Machine(cmd) => { + cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()) + }, } }) }, diff --git a/node/src/rpc.rs b/node/src/rpc.rs index 4a94f77..e827041 100644 --- a/node/src/rpc.rs +++ b/node/src/rpc.rs @@ -37,12 +37,17 @@ where C::Api: substrate_frame_rpc_system::AccountNonceApi, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, C::Api: profile_validation_runtime_api::ProfileValidationApi, + C::Api: department_funding_runtime_api::DepartmentFundingApi, + C::Api: positive_externality_runtime_api::PositiveExternalityApi, + C::Api: project_tips_runtime_api::ProjectTipsApi, C::Api: BlockBuilder, P: TransactionPool + 'static, - { + use department_funding_rpc::DepartmentFundingApiServer; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; + use positive_externality_rpc::PositiveExternalityApiServer; use profile_validation_rpc::ProfileValidationApiServer; + use project_tips_rpc::ProjectTipsApiServer; use substrate_frame_rpc_system::{System, SystemApiServer}; let mut module = RpcModule::new(()); @@ -51,6 +56,9 @@ where module.merge(System::new(client.clone(), pool.clone(), deny_unsafe).into_rpc())?; module.merge(TransactionPayment::new(client.clone()).into_rpc())?; module.merge(profile_validation_rpc::ProfileValidation::new(client.clone()).into_rpc())?; + module.merge(department_funding_rpc::DepartmentFunding::new(client.clone()).into_rpc())?; + module.merge(positive_externality_rpc::PositiveExternality::new(client.clone()).into_rpc())?; + module.merge(project_tips_rpc::ProjectTips::new(client.clone()).into_rpc())?; // Extend this RPC with a custom API by using the following syntax. // `YourRpcStruct` should have a reference to a client, which is needed diff --git a/pallets/department-funding/department-funding-rpc/src/lib.rs b/pallets/department-funding/department-funding-rpc/src/lib.rs index 4f430cd..ba1e12d 100644 --- a/pallets/department-funding/department-funding-rpc/src/lib.rs +++ b/pallets/department-funding/department-funding-rpc/src/lib.rs @@ -1,27 +1,19 @@ +use department_funding_runtime_api::DepartmentFundingApi as DepartmentFundingRuntimeApi; use jsonrpsee::{ core::{Error as JsonRpseeError, RpcResult}, proc_macros::rpc, types::error::{CallError, ErrorCode, ErrorObject}, }; -use department_funding_runtime_api::DepartmentFundingApi as DepartmentFundingRuntimeApi; use sp_api::codec::Codec; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_runtime::traits::Block as BlockT; use std::sync::Arc; -type ChallengePostId = u64; + type DepartmentRequiredFundId = u64; #[rpc(client, server)] pub trait DepartmentFundingApi { - #[method(name = "departmentfunding_challengerevidence")] - fn get_challengers_evidence( - &self, - department_required_fund_id: DepartmentRequiredFundId, - offset: u64, - limit: u16, - at: Option, - ) -> RpcResult>; #[method(name = "departmentfunding_evidenceperiodendblock")] fn get_evidence_period_end_block( &self, @@ -76,7 +68,6 @@ impl DepartmentFunding { } } - /// Error type of this RPC api. pub enum Error { /// The transaction was not decodable. @@ -94,8 +85,8 @@ impl From for i32 { } } - -impl DepartmentFundingApiServer<::Hash, AccountId> for DepartmentFunding +impl DepartmentFundingApiServer<::Hash, AccountId> + for DepartmentFunding where Block: BlockT, AccountId: Codec, @@ -104,30 +95,6 @@ where C: HeaderBackend, C::Api: DepartmentFundingRuntimeApi, { - fn get_challengers_evidence( - &self, - department_required_fund_id: DepartmentRequiredFundId, - offset: u64, - limit: u16, - at: Option, - ) -> RpcResult> { - let api = self.client.runtime_api(); - let at = at.unwrap_or_else(|| - // If the block hash is not supplied assume the best block. - self.client.info().best_hash); - - let runtime_api_result = - api.get_challengers_evidence(at, department_required_fund_id, offset, limit); - fn map_err(error: impl ToString, desc: &'static str) -> CallError { - CallError::Custom(ErrorObject::owned( - Error::RuntimeError.into(), - desc, - Some(error.to_string()), - )) - } - let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) - } fn get_evidence_period_end_block( &self, department_required_fund_id: DepartmentRequiredFundId, @@ -147,7 +114,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_staking_period_end_block( &self, @@ -168,7 +135,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_drawing_period_end( &self, @@ -189,7 +156,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_commit_period_end_block( @@ -211,7 +178,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_vote_period_end_block( @@ -233,7 +200,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn selected_as_juror( @@ -256,6 +223,6 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } -} \ No newline at end of file +} diff --git a/pallets/department-funding/department-funding-runtime-api/src/lib.rs b/pallets/department-funding/department-funding-runtime-api/src/lib.rs index 1c7f702..a1084ce 100644 --- a/pallets/department-funding/department-funding-runtime-api/src/lib.rs +++ b/pallets/department-funding/department-funding-runtime-api/src/lib.rs @@ -2,14 +2,14 @@ // use frame_support::sp_std::{vec::Vec}; // or -use frame_support::sp_std::{prelude::*}; +use frame_support::sp_std::prelude::*; use sp_api::codec::Codec; -type ChallengePostId = u64; -type DepartmentRequiredFundId= u64; + +type DepartmentRequiredFundId = u64; sp_api::decl_runtime_apis! { pub trait DepartmentFundingApi where AccountId: Codec { - fn get_challengers_evidence(department_required_fund_id: DepartmentRequiredFundId, offset: u64, limit: u16) -> Vec; + fn get_evidence_period_end_block(department_required_fund_id: DepartmentRequiredFundId) -> Option; fn get_staking_period_end_block(department_required_fund_id: DepartmentRequiredFundId) -> Option; fn get_drawing_period_end(department_required_fund_id: DepartmentRequiredFundId) -> (u64, u64, bool); @@ -17,4 +17,4 @@ sp_api::decl_runtime_apis! { fn get_vote_period_end_block(department_required_fund_id: DepartmentRequiredFundId) -> Option; fn selected_as_juror(department_required_fund_id: DepartmentRequiredFundId, who: AccountId) -> bool; } -} \ No newline at end of file +} diff --git a/pallets/department-funding/src/extras.rs b/pallets/department-funding/src/extras.rs index 435004c..922c94a 100644 --- a/pallets/department-funding/src/extras.rs +++ b/pallets/department-funding/src/extras.rs @@ -158,17 +158,18 @@ impl Pallet { } } - pub fn get_evidence_period_end_block(department_required_fund_id: DepartmentRequiredFundId) -> Option { + pub fn get_evidence_period_end_block( + department_required_fund_id: DepartmentRequiredFundId, + ) -> Option { let now = >::block_number(); let block_number = - Self::get_block_number_of_schelling_game(department_required_fund_id).unwrap(); - - let key = SumTreeName::DepartmentRequiredFund { - department_required_fund_id, - block_number: block_number.clone(), - }; + Self::get_block_number_of_schelling_game(department_required_fund_id).unwrap(); + let key = SumTreeName::DepartmentRequiredFund { + department_required_fund_id, + block_number: block_number.clone(), + }; let phase_data = Self::get_phase_data(); @@ -176,24 +177,22 @@ impl Pallet { key, phase_data, now, ); result - - } - // End block code start - - pub fn get_staking_period_end_block(department_required_fund_id: DepartmentRequiredFundId) -> Option { + pub fn get_staking_period_end_block( + department_required_fund_id: DepartmentRequiredFundId, + ) -> Option { let now = >::block_number(); - + let block_number = - Self::get_block_number_of_schelling_game(department_required_fund_id).unwrap(); + Self::get_block_number_of_schelling_game(department_required_fund_id).unwrap(); - let key = SumTreeName::DepartmentRequiredFund { - department_required_fund_id, - block_number: block_number.clone(), - }; + let key = SumTreeName::DepartmentRequiredFund { + department_required_fund_id, + block_number: block_number.clone(), + }; let phase_data = Self::get_phase_data(); @@ -203,14 +202,16 @@ impl Pallet { result } - pub fn get_drawing_period_end(department_required_fund_id: DepartmentRequiredFundId) -> (u64, u64, bool) { + pub fn get_drawing_period_end( + department_required_fund_id: DepartmentRequiredFundId, + ) -> (u64, u64, bool) { let block_number = - Self::get_block_number_of_schelling_game(department_required_fund_id).unwrap(); + Self::get_block_number_of_schelling_game(department_required_fund_id).unwrap(); - let key = SumTreeName::DepartmentRequiredFund { - department_required_fund_id, - block_number: block_number.clone(), - }; + let key = SumTreeName::DepartmentRequiredFund { + department_required_fund_id, + block_number: block_number.clone(), + }; let phase_data = Self::get_phase_data(); let result = @@ -218,16 +219,18 @@ impl Pallet { result } - pub fn get_commit_period_end_block(department_required_fund_id: DepartmentRequiredFundId) -> Option { + pub fn get_commit_period_end_block( + department_required_fund_id: DepartmentRequiredFundId, + ) -> Option { let now = >::block_number(); - + let block_number = - Self::get_block_number_of_schelling_game(department_required_fund_id).unwrap(); + Self::get_block_number_of_schelling_game(department_required_fund_id).unwrap(); - let key = SumTreeName::DepartmentRequiredFund { - department_required_fund_id, - block_number: block_number.clone(), - }; + let key = SumTreeName::DepartmentRequiredFund { + department_required_fund_id, + block_number: block_number.clone(), + }; let phase_data = Self::get_phase_data(); @@ -237,16 +240,18 @@ impl Pallet { result } - pub fn get_vote_period_end_block(department_required_fund_id: DepartmentRequiredFundId) -> Option { + pub fn get_vote_period_end_block( + department_required_fund_id: DepartmentRequiredFundId, + ) -> Option { let now = >::block_number(); let block_number = - Self::get_block_number_of_schelling_game(department_required_fund_id).unwrap(); + Self::get_block_number_of_schelling_game(department_required_fund_id).unwrap(); - let key = SumTreeName::DepartmentRequiredFund { - department_required_fund_id, - block_number: block_number.clone(), - }; + let key = SumTreeName::DepartmentRequiredFund { + department_required_fund_id, + block_number: block_number.clone(), + }; let phase_data = Self::get_phase_data(); @@ -256,19 +261,21 @@ impl Pallet { result } - pub fn selected_as_juror(department_required_fund_id: DepartmentRequiredFundId, who: T::AccountId) -> bool { + pub fn selected_as_juror( + department_required_fund_id: DepartmentRequiredFundId, + who: T::AccountId, + ) -> bool { let block_number = - Self::get_block_number_of_schelling_game(department_required_fund_id).unwrap(); + Self::get_block_number_of_schelling_game(department_required_fund_id).unwrap(); - let key = SumTreeName::DepartmentRequiredFund { - department_required_fund_id, - block_number: block_number.clone(), - }; + let key = SumTreeName::DepartmentRequiredFund { + department_required_fund_id, + block_number: block_number.clone(), + }; let result = T::SchellingGameSharedSource::selected_as_juror_helper_link(key, who); result } // End block code end - } diff --git a/pallets/department-funding/src/mock.rs b/pallets/department-funding/src/mock.rs index af047a0..1021d9a 100644 --- a/pallets/department-funding/src/mock.rs +++ b/pallets/department-funding/src/mock.rs @@ -1,5 +1,8 @@ use crate as pallet_template; -use frame_support::{parameter_types, traits::{ConstU16, ConstU64, GenesisBuild}}; +use frame_support::{ + parameter_types, + traits::{ConstU16, ConstU64, GenesisBuild}, +}; use sp_core::H256; use sp_runtime::{ testing::Header, @@ -10,7 +13,6 @@ type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; use frame_support_test::TestRandomness; - // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( pub enum Test where @@ -55,17 +57,16 @@ impl frame_system::Config for Test { } parameter_types! { - pub const MinimumPeriod: u64 = 5; + pub const MinimumPeriod: u64 = 5; } impl pallet_timestamp::Config for Test { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); } - impl shared_storage::Config for Test { type RuntimeEvent = RuntimeEvent; type WeightInfo = (); diff --git a/pallets/department-funding/src/tests.rs b/pallets/department-funding/src/tests.rs index 5976760..b44278c 100644 --- a/pallets/department-funding/src/tests.rs +++ b/pallets/department-funding/src/tests.rs @@ -7,7 +7,6 @@ fn it_works_for_default_value() { // Go past genesis block so events get deposited System::set_block_number(1); // Dispatch a signed extrinsic. - }); } @@ -15,6 +14,5 @@ fn it_works_for_default_value() { fn correct_error_for_none_value() { new_test_ext().execute_with(|| { // Ensure the expected error is thrown when no value is present. - }); } diff --git a/pallets/department-funding/src/types.rs b/pallets/department-funding/src/types.rs index 806e6b5..0cfe89d 100644 --- a/pallets/department-funding/src/types.rs +++ b/pallets/department-funding/src/types.rs @@ -9,7 +9,6 @@ pub const TIME_FOR_STAKING_FUNDING_STATUS_FAILED: u64 = (3 * 30 * 24 * 60 * 60) pub const TIME_FOR_STAKING_FUNDING_STATUS_PASSED: u64 = (6 * 30 * 24 * 60 * 60) / 6; // 6 months time - #[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, RuntimeDebug, TypeInfo)] pub enum TippingName { SmallTipper, @@ -29,14 +28,13 @@ pub struct TippingValue { #[scale_info(skip_type_params(T))] pub struct DepartmentRequiredFund { pub created: WhoAndWhenOf, - pub department_required_fund_id: DepartmentRequiredFundId, + pub department_required_fund_id: DepartmentRequiredFundId, pub department_id: DepartmentId, pub tipping_name: TippingName, pub funding_needed: BalanceOf, pub creator: T::AccountId, } - #[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, RuntimeDebug, TypeInfo)] pub enum FundingStatus { Processing, @@ -49,7 +47,3 @@ pub struct DepartmentFundingStatus { pub block_number: BlockNumber, pub status: FundingStatus, } - - - - diff --git a/pallets/election/src/extras.rs b/pallets/election/src/extras.rs index 44d3939..b420259 100644 --- a/pallets/election/src/extras.rs +++ b/pallets/election/src/extras.rs @@ -58,8 +58,6 @@ impl Pallet { .collect::>() } - - pub(super) fn remove_and_replace_member( who: &T::AccountId, slash: bool, diff --git a/pallets/election/src/lib.rs b/pallets/election/src/lib.rs index b702ec9..75ec5ca 100644 --- a/pallets/election/src/lib.rs +++ b/pallets/election/src/lib.rs @@ -175,7 +175,10 @@ pub mod pallet { pub enum Event { /// Event documentation should end with an array that provides descriptive names for event /// parameters. [something, who] - SomethingStored { something: u32, who: T::AccountId }, + SomethingStored { + something: u32, + who: T::AccountId, + }, EmptyTerm, /// Note that old members and runners-up are also candidates. CandidateSlashed { @@ -220,7 +223,6 @@ pub mod pallet { // Dispatchable functions must be annotated with a weight and must return a DispatchResult. #[pallet::call] impl Pallet { - #[pallet::call_index(0)] #[pallet::weight(Weight::from_parts(10_000, u64::MAX) + T::DbWeight::get().writes(1))] // We get scores of the who for score schelling game pallet 🟩 @@ -252,7 +254,6 @@ pub mod pallet { Ok(None.into()) } - /// Submit oneself for candidacy. A fixed amount of deposit is recorded. /// @@ -269,7 +270,7 @@ pub mod pallet { /// # /// The number of current candidates must be provided as witness data. /// # - /// + /// #[pallet::call_index(1)] #[pallet::weight(Weight::from_parts(10_000, u64::MAX) + T::DbWeight::get().writes(1))] pub fn submit_candidacy( @@ -484,6 +485,5 @@ pub mod pallet { Ok(()) } - } } diff --git a/pallets/election/src/mock.rs b/pallets/election/src/mock.rs index b6cd1c5..a186a6c 100644 --- a/pallets/election/src/mock.rs +++ b/pallets/election/src/mock.rs @@ -1,5 +1,9 @@ use crate as pallet_template; -use frame_support::{parameter_types,dispatch::DispatchResultWithPostInfo, traits::{ConstU16, ConstU64}}; +use frame_support::{ + dispatch::DispatchResultWithPostInfo, + parameter_types, + traits::{ConstU16, ConstU64}, +}; use sp_core::H256; use sp_runtime::{ testing::Header, @@ -129,7 +133,6 @@ pub fn new_test_ext() -> sp_io::TestExternalities { t.into() } - pub(super) fn candidate_ids(departmentid: u128) -> Vec { Elections::candidates(departmentid) .into_iter() @@ -141,7 +144,10 @@ pub(super) fn balances(who: &u64) -> (u64, u64) { (Balances::free_balance(who), Balances::reserved_balance(who)) } -pub(super) fn submit_candidacy(origin: RuntimeOrigin, departmentid: u128) -> DispatchResultWithPostInfo { +pub(super) fn submit_candidacy( + origin: RuntimeOrigin, + departmentid: u128, +) -> DispatchResultWithPostInfo { Elections::submit_candidacy( origin, departmentid, @@ -165,9 +171,11 @@ pub(super) fn vote( Elections::vote(origin, departmentid, votes, score) } - pub(super) fn runners_up_ids(departmentid: u128) -> Vec { - Elections::runners_up(departmentid).into_iter().map(|r| r.who).collect::>() + Elections::runners_up(departmentid) + .into_iter() + .map(|r| r.who) + .collect::>() } pub(super) fn members_ids(departmentid: u128) -> Vec { diff --git a/pallets/election/src/tests.rs b/pallets/election/src/tests.rs index b968a46..148074c 100644 --- a/pallets/election/src/tests.rs +++ b/pallets/election/src/tests.rs @@ -1,7 +1,6 @@ use crate::{mock::*, Error, Event}; use frame_support::{assert_noop, assert_ok}; - #[test] fn simple_candidate_submission_should_work() { new_test_ext().execute_with(|| { diff --git a/pallets/positive-externality/positive-externality-rpc/Cargo.toml b/pallets/positive-externality/positive-externality-rpc/Cargo.toml index 5ac5119..a69087d 100644 --- a/pallets/positive-externality/positive-externality-rpc/Cargo.toml +++ b/pallets/positive-externality/positive-externality-rpc/Cargo.toml @@ -12,4 +12,4 @@ sp-api = { version = "4.0.0-dev", git = "https://github.com/paritytech/substrate sc-rpc-api = { version = "0.10.0-dev", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-blockchain = { version = "4.0.0-dev", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, version = "7.0.0", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -positive-externality-runtime-api = { default-features= false, path="../positive-externality-runtime-api"} +positive-externality-runtime-api = { default-features= false, path="../positive-externality-runtime-api"} \ No newline at end of file diff --git a/pallets/positive-externality/positive-externality-rpc/src/lib.rs b/pallets/positive-externality/positive-externality-rpc/src/lib.rs index ca52719..60d9331 100644 --- a/pallets/positive-externality/positive-externality-rpc/src/lib.rs +++ b/pallets/positive-externality/positive-externality-rpc/src/lib.rs @@ -9,18 +9,9 @@ use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_runtime::traits::Block as BlockT; use std::sync::Arc; -type ChallengePostId = u64; #[rpc(client, server)] pub trait PositiveExternalityApi { - #[method(name = "positiveexternality_challengerevidence")] - fn get_challengers_evidence( - &self, - user_to_calculate: AccountId, - offset: u64, - limit: u16, - at: Option, - ) -> RpcResult>; #[method(name = "positiveexternality_evidenceperiodendblock")] fn get_evidence_period_end_block( &self, @@ -75,7 +66,6 @@ impl PositiveExternality { } } - /// Error type of this RPC api. pub enum Error { /// The transaction was not decodable. @@ -93,8 +83,8 @@ impl From for i32 { } } - -impl PositiveExternalityApiServer<::Hash, AccountId> for PositiveExternality +impl PositiveExternalityApiServer<::Hash, AccountId> + for PositiveExternality where Block: BlockT, AccountId: Codec, @@ -103,30 +93,6 @@ where C: HeaderBackend, C::Api: PositiveExternalityRuntimeApi, { - fn get_challengers_evidence( - &self, - user_to_calculate: AccountId, - offset: u64, - limit: u16, - at: Option, - ) -> RpcResult> { - let api = self.client.runtime_api(); - let at = at.unwrap_or_else(|| - // If the block hash is not supplied assume the best block. - self.client.info().best_hash); - - let runtime_api_result = - api.get_challengers_evidence(at, user_to_calculate, offset, limit); - fn map_err(error: impl ToString, desc: &'static str) -> CallError { - CallError::Custom(ErrorObject::owned( - Error::RuntimeError.into(), - desc, - Some(error.to_string()), - )) - } - let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) - } fn get_evidence_period_end_block( &self, user_to_calculate: AccountId, @@ -146,7 +112,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_staking_period_end_block( &self, @@ -167,7 +133,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_drawing_period_end( &self, @@ -188,7 +154,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_commit_period_end_block( @@ -210,7 +176,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_vote_period_end_block( @@ -232,7 +198,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn selected_as_juror( @@ -255,6 +221,6 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } } diff --git a/pallets/positive-externality/positive-externality-runtime-api/Cargo.toml b/pallets/positive-externality/positive-externality-runtime-api/Cargo.toml index 14d17ce..27aec6b 100644 --- a/pallets/positive-externality/positive-externality-runtime-api/Cargo.toml +++ b/pallets/positive-externality/positive-externality-runtime-api/Cargo.toml @@ -14,4 +14,4 @@ default = ["std"] std = [ "sp-api/std", "frame-support/std", -] +] \ No newline at end of file diff --git a/pallets/positive-externality/positive-externality-runtime-api/src/lib.rs b/pallets/positive-externality/positive-externality-runtime-api/src/lib.rs index 543e2dd..b8c2483 100644 --- a/pallets/positive-externality/positive-externality-runtime-api/src/lib.rs +++ b/pallets/positive-externality/positive-externality-runtime-api/src/lib.rs @@ -2,14 +2,12 @@ // use frame_support::sp_std::{vec::Vec}; // or -use frame_support::sp_std::{prelude::*}; +use frame_support::sp_std::prelude::*; use sp_api::codec::Codec; -type ChallengePostId = u64; - sp_api::decl_runtime_apis! { pub trait PositiveExternalityApi where AccountId: Codec { - fn get_challengers_evidence(user_to_calculate: AccountId, offset: u64, limit: u16) -> Vec; + fn get_evidence_period_end_block(user_to_calculate: AccountId) -> Option; fn get_staking_period_end_block(user_to_calculate: AccountId) -> Option; fn get_drawing_period_end(user_to_calculate: AccountId) -> (u64, u64, bool); diff --git a/pallets/positive-externality/src/extras.rs b/pallets/positive-externality/src/extras.rs index dea660d..3b891e3 100644 --- a/pallets/positive-externality/src/extras.rs +++ b/pallets/positive-externality/src/extras.rs @@ -27,7 +27,6 @@ impl PositiveExternalityPost { } impl Pallet { - pub(super) fn get_phase_data() -> PhaseData { T::SchellingGameSharedSource::create_phase_data(50, 5, 3, 100, (100, 100)) } @@ -75,13 +74,12 @@ impl Pallet { let now = >::block_number(); let pe_block_number = - >::get(user_to_calculate.clone()); - - let key = SumTreeName::PositiveExternality { - user_address: user_to_calculate, - block_number: pe_block_number.clone(), - }; + >::get(user_to_calculate.clone()); + let key = SumTreeName::PositiveExternality { + user_address: user_to_calculate, + block_number: pe_block_number.clone(), + }; let phase_data = Self::get_phase_data(); @@ -89,21 +87,18 @@ impl Pallet { key, phase_data, now, ); result - - } - pub fn get_staking_period_end_block(user_to_calculate: T::AccountId) -> Option { let now = >::block_number(); - + let pe_block_number = - >::get(user_to_calculate.clone()); + >::get(user_to_calculate.clone()); - let key = SumTreeName::PositiveExternality { - user_address: user_to_calculate, - block_number: pe_block_number.clone(), - }; + let key = SumTreeName::PositiveExternality { + user_address: user_to_calculate, + block_number: pe_block_number.clone(), + }; let phase_data = Self::get_phase_data(); @@ -115,12 +110,12 @@ impl Pallet { pub fn get_drawing_period_end(user_to_calculate: T::AccountId) -> (u64, u64, bool) { let pe_block_number = - >::get(user_to_calculate.clone()); + >::get(user_to_calculate.clone()); - let key = SumTreeName::PositiveExternality { - user_address: user_to_calculate, - block_number: pe_block_number.clone(), - }; + let key = SumTreeName::PositiveExternality { + user_address: user_to_calculate, + block_number: pe_block_number.clone(), + }; let phase_data = Self::get_phase_data(); let result = @@ -130,14 +125,14 @@ impl Pallet { pub fn get_commit_period_end_block(user_to_calculate: T::AccountId) -> Option { let now = >::block_number(); - + let pe_block_number = - >::get(user_to_calculate.clone()); + >::get(user_to_calculate.clone()); - let key = SumTreeName::PositiveExternality { - user_address: user_to_calculate, - block_number: pe_block_number.clone(), - }; + let key = SumTreeName::PositiveExternality { + user_address: user_to_calculate, + block_number: pe_block_number.clone(), + }; let phase_data = Self::get_phase_data(); @@ -151,12 +146,12 @@ impl Pallet { let now = >::block_number(); let pe_block_number = - >::get(user_to_calculate.clone()); + >::get(user_to_calculate.clone()); - let key = SumTreeName::PositiveExternality { - user_address: user_to_calculate, - block_number: pe_block_number.clone(), - }; + let key = SumTreeName::PositiveExternality { + user_address: user_to_calculate, + block_number: pe_block_number.clone(), + }; let phase_data = Self::get_phase_data(); @@ -168,12 +163,12 @@ impl Pallet { pub fn selected_as_juror(user_to_calculate: T::AccountId, who: T::AccountId) -> bool { let pe_block_number = - >::get(user_to_calculate.clone()); + >::get(user_to_calculate.clone()); - let key = SumTreeName::PositiveExternality { - user_address: user_to_calculate, - block_number: pe_block_number.clone(), - }; + let key = SumTreeName::PositiveExternality { + user_address: user_to_calculate, + block_number: pe_block_number.clone(), + }; let result = T::SchellingGameSharedSource::selected_as_juror_helper_link(key, who); result diff --git a/pallets/positive-externality/src/lib.rs b/pallets/positive-externality/src/lib.rs index c822ddd..86c563c 100644 --- a/pallets/positive-externality/src/lib.rs +++ b/pallets/positive-externality/src/lib.rs @@ -35,7 +35,7 @@ use pallet_support::{ ensure_content_is_valid, new_who_and_when, remove_from_vec, Content, PositiveExternalityPostId, WhoAndWhen, WhoAndWhenOf, }; -use schelling_game_shared::types::{Period, RangePoint, SchellingGameType, PhaseData}; +use schelling_game_shared::types::{Period, PhaseData, RangePoint, SchellingGameType}; use schelling_game_shared_link::SchellingGameSharedLink; use shared_storage_link::SharedStorageLink; use sortition_sum_game::types::SumTreeName; @@ -44,7 +44,6 @@ type BalanceOf = <::Currency as Currency>>::Balan pub type BlockNumberOf = ::BlockNumber; pub type SumTreeNameType = SumTreeName, BlockNumberOf>; - #[frame_support::pallet(dev_mode)] pub mod pallet { use super::*; @@ -57,7 +56,9 @@ pub mod pallet { /// Configure the pallet by specifying the parameters and types on which it depends. #[pallet::config] - pub trait Config: frame_system::Config + pallet_timestamp::Config + schelling_game_shared::Config { + pub trait Config: + frame_system::Config + pallet_timestamp::Config + schelling_game_shared::Config + { /// Because this pallet emits events, it depends on the runtime's definition of an event. type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// Type representing the weight of this pallet @@ -131,7 +132,6 @@ pub mod pallet { pub type ValidationPositiveExternalityBlock = StorageMap<_, Blake2_128Concat, T::AccountId, BlockNumberOf, ValueQuery>; - // Pallets use events to inform users when important changes are made. // https://docs.substrate.io/main-docs/build/events-errors/ #[pallet::event] @@ -161,7 +161,6 @@ pub mod pallet { // Dispatchable functions must be annotated with a weight and must return a DispatchResult. #[pallet::call] impl Pallet { - #[pallet::call_index(0)] #[pallet::weight(0)] pub fn create_positive_externality_post( @@ -393,7 +392,6 @@ pub mod pallet { choice: i64, salt: Vec, ) -> DispatchResult { - let who = ensure_signed(origin)?; ensure!(choice <= 5 && choice >= 1, Error::::ChoiceOutOfRange); diff --git a/pallets/positive-externality/src/mock.rs b/pallets/positive-externality/src/mock.rs index 2715141..2e056b2 100644 --- a/pallets/positive-externality/src/mock.rs +++ b/pallets/positive-externality/src/mock.rs @@ -1,11 +1,14 @@ use crate as pallet_template; -use frame_support::{parameter_types, traits::{ConstU16, ConstU64, GenesisBuild}}; +use frame_support::{ + parameter_types, + traits::{ConstU16, ConstU64, GenesisBuild}, +}; +use frame_support_test::TestRandomness; use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; -use frame_support_test::TestRandomness; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -54,23 +57,21 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; // New code } - impl shared_storage::Config for Test { type RuntimeEvent = RuntimeEvent; type WeightInfo = (); } parameter_types! { - pub const MinimumPeriod: u64 = 5; + pub const MinimumPeriod: u64 = 5; } impl pallet_timestamp::Config for Test { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); } - impl pallet_balances::Config for Test { type MaxLocks = (); type MaxReserves = (); diff --git a/pallets/positive-externality/src/tests.rs b/pallets/positive-externality/src/tests.rs index 646e853..30b565a 100644 --- a/pallets/positive-externality/src/tests.rs +++ b/pallets/positive-externality/src/tests.rs @@ -1,7 +1,7 @@ +use crate::types::PositiveExternalityPost; use crate::{mock::*, Error, Event}; use frame_support::{assert_noop, assert_ok}; use pallet_support::{Content, WhoAndWhen}; -use crate::types::PositiveExternalityPost; #[test] fn test_positive_externality_post() { @@ -43,7 +43,10 @@ fn test_adding_positive_externality_stake() { #[test] fn test_setting_positive_externality_validation() { new_test_ext().execute_with(|| { - assert_ok!(TemplateModule::set_validate_positive_externality(RuntimeOrigin::signed(1), true)); + assert_ok!(TemplateModule::set_validate_positive_externality( + RuntimeOrigin::signed(1), + true + )); let value = TemplateModule::validate_positive_externality(1); assert_eq!(value, true); }); @@ -52,7 +55,10 @@ fn test_setting_positive_externality_validation() { #[test] fn test_applying_for_staking_period() { new_test_ext().execute_with(|| { - assert_ok!(TemplateModule::set_validate_positive_externality(RuntimeOrigin::signed(1), true)); + assert_ok!(TemplateModule::set_validate_positive_externality( + RuntimeOrigin::signed(1), + true + )); assert_ok!(TemplateModule::add_positive_externality_stake(RuntimeOrigin::signed(1), 10000)); System::set_block_number(1298000); assert_ok!(TemplateModule::apply_staking_period(RuntimeOrigin::signed(2), 1)); @@ -64,7 +70,10 @@ fn test_applying_for_staking_period() { #[test] fn test_appying_jurors() { new_test_ext().execute_with(|| { - assert_ok!(TemplateModule::set_validate_positive_externality(RuntimeOrigin::signed(1), true)); + assert_ok!(TemplateModule::set_validate_positive_externality( + RuntimeOrigin::signed(1), + true + )); assert_ok!(TemplateModule::add_positive_externality_stake(RuntimeOrigin::signed(1), 10000)); System::set_block_number(1298000); assert_ok!(TemplateModule::apply_staking_period(RuntimeOrigin::signed(2), 1)); @@ -75,7 +84,10 @@ fn test_appying_jurors() { #[test] fn test_change_period() { new_test_ext().execute_with(|| { - assert_ok!(TemplateModule::set_validate_positive_externality(RuntimeOrigin::signed(1), true)); + assert_ok!(TemplateModule::set_validate_positive_externality( + RuntimeOrigin::signed(1), + true + )); assert_ok!(TemplateModule::add_positive_externality_stake(RuntimeOrigin::signed(1), 10000)); System::set_block_number(1298000); assert_ok!(TemplateModule::apply_staking_period(RuntimeOrigin::signed(2), 1)); @@ -92,7 +104,10 @@ fn test_change_period() { #[test] fn test_draw_jurors_period() { new_test_ext().execute_with(|| { - assert_ok!(TemplateModule::set_validate_positive_externality(RuntimeOrigin::signed(1), true)); + assert_ok!(TemplateModule::set_validate_positive_externality( + RuntimeOrigin::signed(1), + true + )); assert_ok!(TemplateModule::add_positive_externality_stake(RuntimeOrigin::signed(1), 10000)); System::set_block_number(1298000); assert_ok!(TemplateModule::apply_staking_period(RuntimeOrigin::signed(2), 1)); @@ -110,7 +125,10 @@ fn test_draw_jurors_period() { #[test] fn test_drawn_jurors() { new_test_ext().execute_with(|| { - assert_ok!(TemplateModule::set_validate_positive_externality(RuntimeOrigin::signed(1), true)); + assert_ok!(TemplateModule::set_validate_positive_externality( + RuntimeOrigin::signed(1), + true + )); assert_ok!(TemplateModule::add_positive_externality_stake(RuntimeOrigin::signed(1), 10000)); System::set_block_number(1298000); assert_ok!(TemplateModule::apply_staking_period(RuntimeOrigin::signed(2), 1)); @@ -135,7 +153,10 @@ fn test_drawn_jurors() { #[test] fn test_commit_and_incentives_vote() { new_test_ext().execute_with(|| { - assert_ok!(TemplateModule::set_validate_positive_externality(RuntimeOrigin::signed(1), true)); + assert_ok!(TemplateModule::set_validate_positive_externality( + RuntimeOrigin::signed(1), + true + )); assert_ok!(TemplateModule::add_positive_externality_stake(RuntimeOrigin::signed(1), 10000)); System::set_block_number(1298000); assert_ok!(TemplateModule::apply_staking_period(RuntimeOrigin::signed(2), 1)); diff --git a/pallets/positive-externality/src/types.rs b/pallets/positive-externality/src/types.rs index 1044141..deb8f67 100644 --- a/pallets/positive-externality/src/types.rs +++ b/pallets/positive-externality/src/types.rs @@ -11,28 +11,25 @@ pub const FIRST_POST_ID: u64 = 1; #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)] #[scale_info(skip_type_params(T))] pub struct PositiveExternalityPost { - pub id: PositiveExternalityPostId, + pub id: PositiveExternalityPostId, - pub created: WhoAndWhenOf, + pub created: WhoAndWhenOf, - pub edited: bool, + pub edited: bool, - pub owner: T::AccountId, + pub owner: T::AccountId, - pub content: Content, + pub content: Content, - pub hidden: bool, + pub hidden: bool, - pub upvotes_count: u32, + pub upvotes_count: u32, - pub downvotes_count: u32, + pub downvotes_count: u32, } - #[derive(Encode, Decode, Default, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)] pub struct PositiveExternalityPostUpdate { - - pub content: Option, - pub hidden: Option, + pub content: Option, + pub hidden: Option, } - diff --git a/pallets/posts/src/extras.rs b/pallets/posts/src/extras.rs index 2581ace..f38657e 100644 --- a/pallets/posts/src/extras.rs +++ b/pallets/posts/src/extras.rs @@ -1,5 +1,3 @@ use crate::*; -impl Pallet { - -} +impl Pallet {} diff --git a/pallets/posts/src/functions.rs b/pallets/posts/src/functions.rs index a149064..620ec7b 100644 --- a/pallets/posts/src/functions.rs +++ b/pallets/posts/src/functions.rs @@ -6,134 +6,134 @@ use pallet_support::{remove_from_vec, SpaceId}; use super::*; impl Post { - pub fn new( - id: PostId, - created_by: T::AccountId, - space_id_opt: Option, - extension: PostExtension, - content: Content, - ) -> Self { - Post { - id, - created: new_who_and_when::(created_by.clone()), - edited: false, - owner: created_by, - extension, - space_id: space_id_opt, - content, - hidden: false, - upvotes_count: 0, - downvotes_count: 0, - } - } - - pub fn ensure_owner(&self, account: &T::AccountId) -> DispatchResult { - ensure!(self.is_owner(account), Error::::NotAPostOwner); - Ok(()) - } - - pub fn is_owner(&self, account: &T::AccountId) -> bool { - self.owner == *account - } - - pub fn is_root_post(&self) -> bool { - !self.is_comment() - } - - pub fn is_regular_post(&self) -> bool { - matches!(self.extension, PostExtension::RegularPost) - } - - pub fn is_comment(&self) -> bool { - matches!(self.extension, PostExtension::Comment(_)) - } - - pub fn is_shared_post(&self) -> bool { - matches!(self.extension, PostExtension::SharedPost(_)) - } - - pub fn get_comment_ext(&self) -> Result { - match self.extension { - PostExtension::Comment(comment_ext) => Ok(comment_ext), - _ => Err(Error::::NotComment.into()), - } - } - - pub fn get_original_post_id(&self) -> Result { - match self.extension { - PostExtension::SharedPost(original_post_id) => Ok(original_post_id), - _ => Err(Error::::NotASharedPost.into()), - } - } - - pub fn get_root_post(&self) -> Result, DispatchError> { - match self.extension { - PostExtension::RegularPost | PostExtension::SharedPost(_) => Ok(self.clone()), - PostExtension::Comment(comment) => Pallet::::require_post(comment.root_post_id), - } - } - - pub fn get_space_id(&self) -> Result { - Self::try_get_space_id(self).ok_or_else(|| Error::::PostHasNoSpaceId.into()) - } - - pub fn try_get_space_id(&self) -> Option { - if let Ok(root_post) = self.get_root_post() { - return root_post.space_id - } - - None - } - - pub fn get_space(&self) -> Result, DispatchError> { - let root_post = self.get_root_post()?; - let space_id = root_post.space_id.ok_or(Error::::PostHasNoSpaceId)?; - Spaces::require_space(space_id) - } - - pub fn try_get_space(&self) -> Option> { - if let Ok(root_post) = self.get_root_post() { - return root_post.space_id.and_then(|space_id| Spaces::require_space(space_id).ok()) - } - - None - } - - pub fn try_get_parent_id(&self) -> Option { - match self.extension { - PostExtension::Comment(comment_ext) => comment_ext.parent_id, - _ => None, - } - } - - pub fn inc_upvotes(&mut self) { - self.upvotes_count.saturating_inc(); - } - - pub fn dec_upvotes(&mut self) { - self.upvotes_count.saturating_dec(); - } - - pub fn inc_downvotes(&mut self) { - self.downvotes_count.saturating_inc(); - } - - pub fn dec_downvotes(&mut self) { - self.downvotes_count.saturating_dec(); - } - - pub fn is_public(&self) -> bool { - !self.hidden && self.content.is_some() - } - - pub fn is_unlisted(&self) -> bool { - !self.is_public() - } + pub fn new( + id: PostId, + created_by: T::AccountId, + space_id_opt: Option, + extension: PostExtension, + content: Content, + ) -> Self { + Post { + id, + created: new_who_and_when::(created_by.clone()), + edited: false, + owner: created_by, + extension, + space_id: space_id_opt, + content, + hidden: false, + upvotes_count: 0, + downvotes_count: 0, + } + } + + pub fn ensure_owner(&self, account: &T::AccountId) -> DispatchResult { + ensure!(self.is_owner(account), Error::::NotAPostOwner); + Ok(()) + } + + pub fn is_owner(&self, account: &T::AccountId) -> bool { + self.owner == *account + } + + pub fn is_root_post(&self) -> bool { + !self.is_comment() + } + + pub fn is_regular_post(&self) -> bool { + matches!(self.extension, PostExtension::RegularPost) + } + + pub fn is_comment(&self) -> bool { + matches!(self.extension, PostExtension::Comment(_)) + } + + pub fn is_shared_post(&self) -> bool { + matches!(self.extension, PostExtension::SharedPost(_)) + } + + pub fn get_comment_ext(&self) -> Result { + match self.extension { + PostExtension::Comment(comment_ext) => Ok(comment_ext), + _ => Err(Error::::NotComment.into()), + } + } + + pub fn get_original_post_id(&self) -> Result { + match self.extension { + PostExtension::SharedPost(original_post_id) => Ok(original_post_id), + _ => Err(Error::::NotASharedPost.into()), + } + } + + pub fn get_root_post(&self) -> Result, DispatchError> { + match self.extension { + PostExtension::RegularPost | PostExtension::SharedPost(_) => Ok(self.clone()), + PostExtension::Comment(comment) => Pallet::::require_post(comment.root_post_id), + } + } + + pub fn get_space_id(&self) -> Result { + Self::try_get_space_id(self).ok_or_else(|| Error::::PostHasNoSpaceId.into()) + } + + pub fn try_get_space_id(&self) -> Option { + if let Ok(root_post) = self.get_root_post() { + return root_post.space_id; + } + + None + } + + pub fn get_space(&self) -> Result, DispatchError> { + let root_post = self.get_root_post()?; + let space_id = root_post.space_id.ok_or(Error::::PostHasNoSpaceId)?; + Spaces::require_space(space_id) + } + + pub fn try_get_space(&self) -> Option> { + if let Ok(root_post) = self.get_root_post() { + return root_post.space_id.and_then(|space_id| Spaces::require_space(space_id).ok()); + } + + None + } + + pub fn try_get_parent_id(&self) -> Option { + match self.extension { + PostExtension::Comment(comment_ext) => comment_ext.parent_id, + _ => None, + } + } + + pub fn inc_upvotes(&mut self) { + self.upvotes_count.saturating_inc(); + } + + pub fn dec_upvotes(&mut self) { + self.upvotes_count.saturating_dec(); + } + + pub fn inc_downvotes(&mut self) { + self.downvotes_count.saturating_inc(); + } + + pub fn dec_downvotes(&mut self) { + self.downvotes_count.saturating_dec(); + } + + pub fn is_public(&self) -> bool { + !self.hidden && self.content.is_some() + } + + pub fn is_unlisted(&self) -> bool { + !self.is_public() + } } impl Pallet { - /// Get `Post` by id from the storage or return `PostNotFound` error. - pub fn require_post(post_id: SpaceId) -> Result, DispatchError> { - Ok(Self::post_by_id(post_id).ok_or(Error::::PostNotFound)?) - } + /// Get `Post` by id from the storage or return `PostNotFound` error. + pub fn require_post(post_id: SpaceId) -> Result, DispatchError> { + Ok(Self::post_by_id(post_id).ok_or(Error::::PostNotFound)?) + } } diff --git a/pallets/posts/src/mock.rs b/pallets/posts/src/mock.rs index c60271b..648822d 100644 --- a/pallets/posts/src/mock.rs +++ b/pallets/posts/src/mock.rs @@ -1,5 +1,8 @@ use crate as pallet_template; -use frame_support::{parameter_types, traits::{ConstU16, ConstU64, GenesisBuild}}; +use frame_support::{ + parameter_types, + traits::{ConstU16, ConstU64, GenesisBuild}, +}; use sp_core::H256; use sp_runtime::{ testing::Header, @@ -61,18 +64,16 @@ impl pallet_spaces::Config for Test { } parameter_types! { - pub const MinimumPeriod: u64 = 5; + pub const MinimumPeriod: u64 = 5; } impl pallet_timestamp::Config for Test { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); } - - // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { frame_system::GenesisConfig::default().build_storage::().unwrap().into() diff --git a/pallets/posts/src/tests.rs b/pallets/posts/src/tests.rs index ef0e38a..d07fba9 100644 --- a/pallets/posts/src/tests.rs +++ b/pallets/posts/src/tests.rs @@ -6,13 +6,10 @@ fn it_works_for_default_value() { new_test_ext().execute_with(|| { // Go past genesis block so events get deposited System::set_block_number(1); - }); } #[test] fn correct_error_for_none_value() { - new_test_ext().execute_with(|| { - - }); + new_test_ext().execute_with(|| {}); } diff --git a/pallets/posts/src/types.rs b/pallets/posts/src/types.rs index 600b33b..2f3b410 100644 --- a/pallets/posts/src/types.rs +++ b/pallets/posts/src/types.rs @@ -6,63 +6,63 @@ pub const FIRST_POST_ID: u64 = 1; #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)] #[scale_info(skip_type_params(T))] pub struct Post { - /// Unique sequential identifier of a post. Examples of post ids: `1`, `2`, `3`, and so on. - pub id: PostId, + /// Unique sequential identifier of a post. Examples of post ids: `1`, `2`, `3`, and so on. + pub id: PostId, - pub created: WhoAndWhenOf, - /// True, if the content of this post was edited. - pub edited: bool, + pub created: WhoAndWhenOf, + /// True, if the content of this post was edited. + pub edited: bool, - /// The current owner of a given post. - pub owner: T::AccountId, + /// The current owner of a given post. + pub owner: T::AccountId, - /// Through post extension you can provide specific information necessary for different kinds - /// of posts such as regular posts, comments, and shared posts. - pub extension: PostExtension, + /// Through post extension you can provide specific information necessary for different kinds + /// of posts such as regular posts, comments, and shared posts. + pub extension: PostExtension, - /// An id of a space which contains a given post. - pub space_id: Option, + /// An id of a space which contains a given post. + pub space_id: Option, - pub content: Content, + pub content: Content, - /// Hidden field is used to recommend to end clients (web and mobile apps) that a particular - /// posts and its' comments should not be shown. - pub hidden: bool, + /// Hidden field is used to recommend to end clients (web and mobile apps) that a particular + /// posts and its' comments should not be shown. + pub hidden: bool, - /// The number of times a given post has been upvoted. - pub upvotes_count: u32, + /// The number of times a given post has been upvoted. + pub upvotes_count: u32, - /// The number of times a given post has been downvoted. - pub downvotes_count: u32, + /// The number of times a given post has been downvoted. + pub downvotes_count: u32, } #[derive(Encode, Decode, Default, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)] pub struct PostUpdate { - /// Deprecated: This field has no effect in `fn update_post()` extrinsic. - /// See `fn move_post()` extrinsic if you want to move a post to another space. - pub space_id: Option, + /// Deprecated: This field has no effect in `fn update_post()` extrinsic. + /// See `fn move_post()` extrinsic if you want to move a post to another space. + pub space_id: Option, - pub content: Option, - pub hidden: Option, + pub content: Option, + pub hidden: Option, } /// Post extension provides specific information necessary for different kinds /// of posts such as regular posts, comments, and shared posts. #[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, RuntimeDebug, TypeInfo)] pub enum PostExtension { - RegularPost, - Comment(Comment), - SharedPost(PostId), + RegularPost, + Comment(Comment), + SharedPost(PostId), } #[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, RuntimeDebug, TypeInfo)] pub struct Comment { - pub root_post_id: PostId, - pub parent_id: Option, + pub root_post_id: PostId, + pub parent_id: Option, } impl Default for PostExtension { - fn default() -> Self { - PostExtension::RegularPost - } + fn default() -> Self { + PostExtension::RegularPost + } } diff --git a/pallets/profile-validation/profile-validation-rpc/Cargo.toml b/pallets/profile-validation/profile-validation-rpc/Cargo.toml index db8fa25..1e7e27d 100644 --- a/pallets/profile-validation/profile-validation-rpc/Cargo.toml +++ b/pallets/profile-validation/profile-validation-rpc/Cargo.toml @@ -12,4 +12,4 @@ sp-api = { version = "4.0.0-dev", git = "https://github.com/paritytech/substrate sc-rpc-api = { version = "0.10.0-dev", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-blockchain = { version = "4.0.0-dev", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, version = "7.0.0", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -profile-validation-runtime-api = { default-features= false, path="../profile-validation-runtime-api"} +profile-validation-runtime-api = { default-features= false, path="../profile-validation-runtime-api"} \ No newline at end of file diff --git a/pallets/profile-validation/profile-validation-rpc/src/lib.rs b/pallets/profile-validation/profile-validation-rpc/src/lib.rs index 7b96482..87a3fc2 100644 --- a/pallets/profile-validation/profile-validation-rpc/src/lib.rs +++ b/pallets/profile-validation/profile-validation-rpc/src/lib.rs @@ -9,6 +9,7 @@ use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_runtime::traits::Block as BlockT; use std::sync::Arc; + type ChallengePostId = u64; #[rpc(client, server)] @@ -21,6 +22,7 @@ pub trait ProfileValidationApi { limit: u16, at: Option, ) -> RpcResult>; + #[method(name = "profilevalidation_evidenceperiodendblock")] fn get_evidence_period_end_block( &self, @@ -75,7 +77,6 @@ impl ProfileValidation { } } - /// Error type of this RPC api. pub enum Error { /// The transaction was not decodable. @@ -93,8 +94,8 @@ impl From for i32 { } } - -impl ProfileValidationApiServer<::Hash, AccountId> for ProfileValidation +impl ProfileValidationApiServer<::Hash, AccountId> + for ProfileValidation where Block: BlockT, AccountId: Codec, @@ -117,16 +118,17 @@ where let runtime_api_result = api.get_challengers_evidence(at, profile_user_account, offset, limit); - fn map_err(error: impl ToString, desc: &'static str) -> CallError { - CallError::Custom(ErrorObject::owned( - Error::RuntimeError.into(), - desc, - Some(error.to_string()), - )) - } - let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + fn map_err(error: impl ToString, desc: &'static str) -> CallError { + CallError::Custom(ErrorObject::owned( + Error::RuntimeError.into(), + desc, + Some(error.to_string()), + )) + } + let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; + Ok(res) } + fn get_evidence_period_end_block( &self, profile_user_account: AccountId, @@ -146,7 +148,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_staking_period_end_block( &self, @@ -167,7 +169,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_drawing_period_end( &self, @@ -188,7 +190,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_commit_period_end_block( @@ -210,7 +212,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_vote_period_end_block( @@ -232,7 +234,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn selected_as_juror( @@ -255,6 +257,6 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } } diff --git a/pallets/profile-validation/profile-validation-runtime-api/Cargo.toml b/pallets/profile-validation/profile-validation-runtime-api/Cargo.toml index 3182c5e..5abf0c2 100644 --- a/pallets/profile-validation/profile-validation-runtime-api/Cargo.toml +++ b/pallets/profile-validation/profile-validation-runtime-api/Cargo.toml @@ -14,4 +14,4 @@ default = ["std"] std = [ "sp-api/std", "frame-support/std", -] +] \ No newline at end of file diff --git a/pallets/profile-validation/profile-validation-runtime-api/src/lib.rs b/pallets/profile-validation/profile-validation-runtime-api/src/lib.rs index a8f5290..47fa5f9 100644 --- a/pallets/profile-validation/profile-validation-runtime-api/src/lib.rs +++ b/pallets/profile-validation/profile-validation-runtime-api/src/lib.rs @@ -2,13 +2,16 @@ // use frame_support::sp_std::{vec::Vec}; // or -use frame_support::sp_std::{prelude::*}; +use frame_support::sp_std::prelude::*; use sp_api::codec::Codec; + type ChallengePostId = u64; sp_api::decl_runtime_apis! { pub trait ProfileValidationApi where AccountId: Codec { + fn get_challengers_evidence(profile_user_account: AccountId, offset: u64, limit: u16) -> Vec; + fn get_evidence_period_end_block(profile_user_account: AccountId) -> Option; fn get_staking_period_end_block(profile_user_account: AccountId) -> Option; fn get_drawing_period_end(profile_user_account: AccountId) -> (u64, u64, bool); @@ -16,4 +19,4 @@ sp_api::decl_runtime_apis! { fn get_vote_period_end_block(profile_user_account: AccountId) -> Option; fn selected_as_juror(profile_user_account: AccountId, who: AccountId) -> bool; } -} \ No newline at end of file +} diff --git a/pallets/profile-validation/src/extras.rs b/pallets/profile-validation/src/extras.rs index 09b6fa0..1f53ee8 100644 --- a/pallets/profile-validation/src/extras.rs +++ b/pallets/profile-validation/src/extras.rs @@ -53,7 +53,19 @@ impl ChallengeEvidencePost { impl Pallet { pub(super) fn get_phase_data() -> PhaseData { - T::SchellingGameSharedSource::create_phase_with_all_data(10, 100, 100, 100, 100, 100, 100, 5, 5, 100, (100, 100)) + T::SchellingGameSharedSource::create_phase_with_all_data( + 10, + 100, + 100, + 100, + 100, + 100, + 100, + 5, + 5, + 100, + (100, 100), + ) // T::SchellingGameSharedSource::create_phase_data(100, 5, 3, 100, (100, 100)) } @@ -72,7 +84,7 @@ impl Pallet { input.saturated_into::>() } - pub(super) fn balance_to_u64_saturated(input: BalanceOf) -> u64 { + pub(super) fn balance_to_u64_saturated(input: BalanceOf) -> u64 { input.saturated_into::() } @@ -109,11 +121,8 @@ impl Pallet { key, phase_data, now, ); result - - } - pub fn get_staking_period_end_block(profile_user_account: T::AccountId) -> Option { let now = >::block_number(); let block_number = >::get(&profile_user_account); @@ -189,7 +198,7 @@ impl Pallet { result } - pub fn profile_fund_required(profile_user_account: T::AccountId) -> Option { + pub fn profile_fund_required(profile_user_account: T::AccountId) -> Option { let registration_fee = Self::profile_registration_challenge_fees(); let total_funded = Self::total_fund_for_profile_collected(profile_user_account); let registration_fee_u64 = Self::balance_to_u64_saturated(registration_fee); diff --git a/pallets/profile-validation/src/lib.rs b/pallets/profile-validation/src/lib.rs index 720eca4..3c7ef98 100644 --- a/pallets/profile-validation/src/lib.rs +++ b/pallets/profile-validation/src/lib.rs @@ -349,7 +349,7 @@ pub mod pallet { amount_to_fund: BalanceOf, ) -> DispatchResult { let who = ensure_signed(origin)?; - + // Ensure that the `profile_user_account`` exists in `GetCitizenId` storage. Self::ensure_account_id_has_profile(profile_user_account.clone())?; @@ -361,11 +361,10 @@ pub mod pallet { // Calculate the required fund by subtracting the total funded from the registration fee. let required_fund = registration_fee.checked_sub(&total_funded).expect("Overflow"); - + // Check if the amount_to_fund is less than or equal to the required fund. if amount_to_fund <= required_fund { if amount_to_fund == required_fund { - // If the funded amount matches the required amount, update variables required for profile validation. let now = >::block_number(); let key = SumTreeName::ProfileValidation { diff --git a/pallets/profile-validation/src/mock.rs b/pallets/profile-validation/src/mock.rs index 981e022..c0b9332 100644 --- a/pallets/profile-validation/src/mock.rs +++ b/pallets/profile-validation/src/mock.rs @@ -1,16 +1,18 @@ use crate as pallet_template; -use frame_support::{parameter_types, traits::{ConstU16, ConstU64}}; +use frame_support::{ + parameter_types, + traits::{ConstU16, ConstU64}, +}; +use frame_support_test::TestRandomness; use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; -use frame_support_test::TestRandomness; 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 @@ -52,21 +54,19 @@ impl frame_system::Config for Test { type OnSetCode = (); type MaxConsumers = frame_support::traits::ConstU32<16>; type AccountData = pallet_balances::AccountData; // New code - } parameter_types! { - pub const MinimumPeriod: u64 = 5; + pub const MinimumPeriod: u64 = 5; } impl pallet_timestamp::Config for Test { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); } - impl pallet_balances::Config for Test { type MaxLocks = (); type MaxReserves = (); diff --git a/pallets/profile-validation/src/tests.rs b/pallets/profile-validation/src/tests.rs index 532ac22..7d41717 100644 --- a/pallets/profile-validation/src/tests.rs +++ b/pallets/profile-validation/src/tests.rs @@ -451,7 +451,6 @@ fn test_draw_juror() { challenge_content.clone() )); - assert_ok!(ProfileValidation::apply_jurors(RuntimeOrigin::signed(5), 1, 100)); assert_ok!(ProfileValidation::apply_jurors(RuntimeOrigin::signed(6), 1, 500)); assert_ok!(ProfileValidation::apply_jurors(RuntimeOrigin::signed(7), 1, 1000)); @@ -465,9 +464,5 @@ fn test_draw_juror() { assert_ok!(ProfileValidation::draw_jurors(RuntimeOrigin::signed(5), 1, 6)); // assert_ok!(ProfileValidation::draw_jurors(RuntimeOrigin::signed(5), 1, 5)); - - - - }) } diff --git a/pallets/profile-validation/src/types.rs b/pallets/profile-validation/src/types.rs index 4b16d2e..0bcf118 100644 --- a/pallets/profile-validation/src/types.rs +++ b/pallets/profile-validation/src/types.rs @@ -1,52 +1,54 @@ -use frame_support::{pallet_prelude::*}; +use frame_support::pallet_prelude::*; use scale_info::TypeInfo; // use frame_support::sp_std::{vec::Vec}; use super::*; -pub const FIRST_CITIZEN_ID: CitizenId = 1; +pub const FIRST_CITIZEN_ID: CitizenId = 1; pub const FIRST_CHALLENGE_POST_ID: ChallengePostId = 1; - #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)] #[scale_info(skip_type_params(T))] pub struct CitizenDetailsPost { - pub created: WhoAndWhenOf, - pub content: Content, - pub citizen_id: CitizenId, - pub owner: T::AccountId, - pub edited: bool, - pub hidden: bool, - pub upvotes_count: u32, - pub downvotes_count: u32, + pub created: WhoAndWhenOf, + pub content: Content, + pub citizen_id: CitizenId, + pub owner: T::AccountId, + pub edited: bool, + pub hidden: bool, + pub upvotes_count: u32, + pub downvotes_count: u32, } - -#[derive(PartialEq, Eq, PartialOrd, Ord, Default, Clone, Encode, Decode, MaxEncodedLen, TypeInfo)] +#[derive( + PartialEq, Eq, PartialOrd, Ord, Default, Clone, Encode, Decode, MaxEncodedLen, TypeInfo, +)] #[cfg_attr(feature = "std", derive(Debug))] pub struct ProfileFundInfo { - pub funder_account_id: AccountId, - pub validation_account_id: AccountId, - pub deposit: Balance, - pub deposit_returned:bool, + pub funder_account_id: AccountId, + pub validation_account_id: AccountId, + pub deposit: Balance, + pub deposit_returned: bool, } -#[derive(PartialEq, Eq, PartialOrd, Ord, Default, Clone, Encode, Decode, MaxEncodedLen, TypeInfo)] +#[derive( + PartialEq, Eq, PartialOrd, Ord, Default, Clone, Encode, Decode, MaxEncodedLen, TypeInfo, +)] #[cfg_attr(feature = "std", derive(Debug))] pub struct ChallengerFundInfo { - pub challengerid: AccountId, - pub deposit: Balance, - pub start: BlockNumber, - pub challenge_completed: bool, + pub challengerid: AccountId, + pub deposit: Balance, + pub start: BlockNumber, + pub challenge_completed: bool, } #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)] #[scale_info(skip_type_params(T))] pub struct ChallengeEvidencePost { - pub created: WhoAndWhenOf, - pub owner: T::AccountId, - pub kyc_profile_id: T::AccountId, - pub content: Content, - pub post_id_if_comment: Option, - pub is_comment: bool, -} \ No newline at end of file + pub created: WhoAndWhenOf, + pub owner: T::AccountId, + pub kyc_profile_id: T::AccountId, + pub content: Content, + pub post_id_if_comment: Option, + pub is_comment: bool, +} diff --git a/pallets/project-tips/project-tips-rpc/Cargo.toml b/pallets/project-tips/project-tips-rpc/Cargo.toml index 1878c33..7927d2f 100644 --- a/pallets/project-tips/project-tips-rpc/Cargo.toml +++ b/pallets/project-tips/project-tips-rpc/Cargo.toml @@ -12,4 +12,4 @@ sp-api = { version = "4.0.0-dev", git = "https://github.com/paritytech/substrate sc-rpc-api = { version = "0.10.0-dev", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-blockchain = { version = "4.0.0-dev", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, version = "7.0.0", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -project-tips-runtime-api = { default-features= false, path="../project-tips-runtime-api"} +project-tips-runtime-api = { default-features= false, path="../project-tips-runtime-api"} \ No newline at end of file diff --git a/pallets/project-tips/project-tips-rpc/src/lib.rs b/pallets/project-tips/project-tips-rpc/src/lib.rs index a8c6709..32bff04 100644 --- a/pallets/project-tips/project-tips-rpc/src/lib.rs +++ b/pallets/project-tips/project-tips-rpc/src/lib.rs @@ -9,20 +9,11 @@ use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_runtime::traits::Block as BlockT; use std::sync::Arc; -type ChallengePostId = u64; type ProjectId = u64; #[rpc(client, server)] pub trait ProjectTipsApi { - #[method(name = "projecttips_challengerevidence")] - fn get_challengers_evidence( - &self, - project_id: ProjectId, - offset: u64, - limit: u16, - at: Option, - ) -> RpcResult>; #[method(name = "projecttips_evidenceperiodendblock")] fn get_evidence_period_end_block( &self, @@ -77,7 +68,6 @@ impl ProjectTips { } } - /// Error type of this RPC api. pub enum Error { /// The transaction was not decodable. @@ -95,8 +85,8 @@ impl From for i32 { } } - -impl ProjectTipsApiServer<::Hash, AccountId> for ProjectTips +impl ProjectTipsApiServer<::Hash, AccountId> + for ProjectTips where Block: BlockT, AccountId: Codec, @@ -105,30 +95,6 @@ where C: HeaderBackend, C::Api: ProjectTipsRuntimeApi, { - fn get_challengers_evidence( - &self, - project_id: ProjectId, - offset: u64, - limit: u16, - at: Option, - ) -> RpcResult> { - let api = self.client.runtime_api(); - let at = at.unwrap_or_else(|| - // If the block hash is not supplied assume the best block. - self.client.info().best_hash); - - let runtime_api_result = - api.get_challengers_evidence(at, project_id, offset, limit); - fn map_err(error: impl ToString, desc: &'static str) -> CallError { - CallError::Custom(ErrorObject::owned( - Error::RuntimeError.into(), - desc, - Some(error.to_string()), - )) - } - let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) - } fn get_evidence_period_end_block( &self, project_id: ProjectId, @@ -148,7 +114,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_staking_period_end_block( &self, @@ -169,7 +135,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_drawing_period_end( &self, @@ -190,7 +156,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_commit_period_end_block( @@ -212,7 +178,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn get_vote_period_end_block( @@ -234,7 +200,7 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } fn selected_as_juror( @@ -257,6 +223,6 @@ where )) } let res = runtime_api_result.map_err(|e| map_err(e, "Unable to query dispatch info."))?; - Ok(res) + Ok(res) } } diff --git a/pallets/project-tips/project-tips-runtime-api/Cargo.toml b/pallets/project-tips/project-tips-runtime-api/Cargo.toml index fee90dc..5cee691 100644 --- a/pallets/project-tips/project-tips-runtime-api/Cargo.toml +++ b/pallets/project-tips/project-tips-runtime-api/Cargo.toml @@ -14,4 +14,4 @@ default = ["std"] std = [ "sp-api/std", "frame-support/std", -] +] \ No newline at end of file diff --git a/pallets/project-tips/project-tips-runtime-api/src/lib.rs b/pallets/project-tips/project-tips-runtime-api/src/lib.rs index 44be8bb..46b107d 100644 --- a/pallets/project-tips/project-tips-runtime-api/src/lib.rs +++ b/pallets/project-tips/project-tips-runtime-api/src/lib.rs @@ -2,16 +2,14 @@ // use frame_support::sp_std::{vec::Vec}; // or -use frame_support::sp_std::{prelude::*}; +use frame_support::sp_std::prelude::*; use sp_api::codec::Codec; -type ChallengePostId = u64; type ProjectId = u64; - sp_api::decl_runtime_apis! { pub trait ProjectTipsApi where AccountId: Codec { - fn get_challengers_evidence(project_id: ProjectId, offset: u64, limit: u16) -> Vec; + fn get_evidence_period_end_block(project_id: ProjectId) -> Option; fn get_staking_period_end_block(project_id: ProjectId) -> Option; fn get_drawing_period_end(project_id: ProjectId) -> (u64, u64, bool); diff --git a/pallets/project-tips/src/extras.rs b/pallets/project-tips/src/extras.rs index 261d103..8edd6a3 100644 --- a/pallets/project-tips/src/extras.rs +++ b/pallets/project-tips/src/extras.rs @@ -92,7 +92,6 @@ impl Pallet { } } - // Block code start pub fn get_evidence_period_end_block(project_id: ProjectId) -> Option { @@ -100,8 +99,7 @@ impl Pallet { let block_number = Self::get_block_number_of_schelling_game(project_id).unwrap(); - let key = SumTreeName::ProjectTips { project_id, block_number: block_number.clone() }; - + let key = SumTreeName::ProjectTips { project_id, block_number: block_number.clone() }; let phase_data = Self::get_phase_data(); @@ -109,17 +107,14 @@ impl Pallet { key, phase_data, now, ); result - - } - pub fn get_staking_period_end_block(project_id: ProjectId) -> Option { let now = >::block_number(); - + let block_number = Self::get_block_number_of_schelling_game(project_id).unwrap(); - let key = SumTreeName::ProjectTips { project_id, block_number: block_number.clone() }; + let key = SumTreeName::ProjectTips { project_id, block_number: block_number.clone() }; let phase_data = Self::get_phase_data(); @@ -132,7 +127,7 @@ impl Pallet { pub fn get_drawing_period_end(project_id: ProjectId) -> (u64, u64, bool) { let block_number = Self::get_block_number_of_schelling_game(project_id).unwrap(); - let key = SumTreeName::ProjectTips { project_id, block_number: block_number.clone() }; + let key = SumTreeName::ProjectTips { project_id, block_number: block_number.clone() }; let phase_data = Self::get_phase_data(); let result = @@ -142,10 +137,10 @@ impl Pallet { pub fn get_commit_period_end_block(project_id: ProjectId) -> Option { let now = >::block_number(); - + let block_number = Self::get_block_number_of_schelling_game(project_id).unwrap(); - let key = SumTreeName::ProjectTips { project_id, block_number: block_number.clone() }; + let key = SumTreeName::ProjectTips { project_id, block_number: block_number.clone() }; let phase_data = Self::get_phase_data(); @@ -160,7 +155,7 @@ impl Pallet { let block_number = Self::get_block_number_of_schelling_game(project_id).unwrap(); - let key = SumTreeName::ProjectTips { project_id, block_number: block_number.clone() }; + let key = SumTreeName::ProjectTips { project_id, block_number: block_number.clone() }; let phase_data = Self::get_phase_data(); @@ -173,12 +168,11 @@ impl Pallet { pub fn selected_as_juror(project_id: ProjectId, who: T::AccountId) -> bool { let block_number = Self::get_block_number_of_schelling_game(project_id).unwrap(); - let key = SumTreeName::ProjectTips { project_id, block_number: block_number.clone() }; + let key = SumTreeName::ProjectTips { project_id, block_number: block_number.clone() }; let result = T::SchellingGameSharedSource::selected_as_juror_helper_link(key, who); result } // Block code end - } diff --git a/pallets/project-tips/src/lib.rs b/pallets/project-tips/src/lib.rs index ef026d5..03dee59 100644 --- a/pallets/project-tips/src/lib.rs +++ b/pallets/project-tips/src/lib.rs @@ -241,7 +241,12 @@ pub mod pallet { let phase_data = Self::get_phase_data(); - T::SchellingGameSharedSource::apply_jurors_helper_link(key, phase_data, who.clone(), stake)?; + T::SchellingGameSharedSource::apply_jurors_helper_link( + key, + phase_data, + who.clone(), + stake, + )?; Self::deposit_event(Event::ApplyJurors { project_id, block_number, account: who }); Ok(()) @@ -249,10 +254,7 @@ pub mod pallet { #[pallet::call_index(3)] #[pallet::weight(0)] - pub fn pass_period( - origin: OriginFor, - project_id: ProjectId, - ) -> DispatchResult { + pub fn pass_period(origin: OriginFor, project_id: ProjectId) -> DispatchResult { let _who = ensure_signed(origin)?; let block_number = Self::get_block_number_of_schelling_game(project_id)?; @@ -289,10 +291,7 @@ pub mod pallet { // Stop drawn juror to unstake ✔️ #[pallet::call_index(5)] #[pallet::weight(0)] - pub fn unstaking( - origin: OriginFor, - project_id: ProjectId, - ) -> DispatchResult { + pub fn unstaking(origin: OriginFor, project_id: ProjectId) -> DispatchResult { let who = ensure_signed(origin)?; let block_number = Self::get_block_number_of_schelling_game(project_id)?; let key = SumTreeName::ProjectTips { project_id, block_number: block_number.clone() }; diff --git a/pallets/project-tips/src/mock.rs b/pallets/project-tips/src/mock.rs index 2bddfe3..91a2be6 100644 --- a/pallets/project-tips/src/mock.rs +++ b/pallets/project-tips/src/mock.rs @@ -1,5 +1,8 @@ use crate as pallet_template; -use frame_support::{parameter_types, traits::{ConstU16, ConstU64, GenesisBuild}}; +use frame_support::{ + parameter_types, + traits::{ConstU16, ConstU64, GenesisBuild}, +}; use sp_core::H256; use sp_runtime::{ testing::Header, @@ -10,7 +13,6 @@ type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; use frame_support_test::TestRandomness; - // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( pub enum Test where @@ -56,17 +58,16 @@ impl frame_system::Config for Test { } parameter_types! { - pub const MinimumPeriod: u64 = 5; + pub const MinimumPeriod: u64 = 5; } impl pallet_timestamp::Config for Test { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); } - impl shared_storage::Config for Test { type RuntimeEvent = RuntimeEvent; type WeightInfo = (); diff --git a/pallets/project-tips/src/tests.rs b/pallets/project-tips/src/tests.rs index a6a5927..ec44199 100644 --- a/pallets/project-tips/src/tests.rs +++ b/pallets/project-tips/src/tests.rs @@ -1,10 +1,8 @@ use crate::types::TippingName; use crate::{mock::*, Error, Event}; use frame_support::{assert_noop, assert_ok}; -use sortition_sum_game::types::SumTreeName; use schelling_game_shared::types::Period; - - +use sortition_sum_game::types::SumTreeName; #[test] fn check_create_project_function() { @@ -81,170 +79,162 @@ fn check_apply_staking_period_function() { }); } - #[test] fn schelling_game_test() { new_test_ext().execute_with(|| { - System::set_block_number(1); - let tipping_name = TippingName::SmallTipper; - let tipping_value = ProjectTips::value_of_tipping_name(tipping_name); - let max_tipping_value = tipping_value.max_tipping_value; - let stake_required = tipping_value.stake_required; - let funding_needed = max_tipping_value - 100; - let balance = Balances::free_balance(1); - assert_ok!(ProjectTips::create_project( - RuntimeOrigin::signed(1), - 2, - tipping_name, - funding_needed - )); - - let after_balance = Balances::free_balance(1); - - assert_eq!(after_balance, balance - stake_required); - - assert_ok!(ProjectTips::apply_staking_period(RuntimeOrigin::signed(1), 1)); - - let phase_data = ProjectTips::get_phase_data(); - - - let balance = Balances::free_balance(29); - assert_eq!(300000, balance); - for j in 4..30 { - assert_ok!(ProjectTips::apply_jurors(RuntimeOrigin::signed(j), 1, j * 100)); - } - - let balance = Balances::free_balance(29); - assert_eq!(300000 - 29 * 100, balance); - - assert_noop!( - ProjectTips::draw_jurors(RuntimeOrigin::signed(5), 1, 5), - >::PeriodDontMatch - ); - - assert_noop!( - ProjectTips::pass_period(RuntimeOrigin::signed(5), 1), - >::StakingPeriodNotOver - ); - - System::set_block_number(1 + phase_data.staking_length); - - assert_ok!(ProjectTips::pass_period(RuntimeOrigin::signed(5), 1)); - - assert_ok!(ProjectTips::draw_jurors(RuntimeOrigin::signed(5), 1, 5)); - - let key = SumTreeName::ProjectTips { project_id: 1, block_number: 1 }; - - let draws_in_round = SchellingGameShared::draws_in_round(key.clone()); - assert_eq!(5, draws_in_round); - - let drawn_jurors = SchellingGameShared::drawn_jurors(key.clone()); - assert_eq!(vec![(4, 400), (7, 700), (13, 1300), (14, 1400), (15, 1500)], drawn_jurors); - - assert_ok!(ProjectTips::pass_period(RuntimeOrigin::signed(5), 1)); - - let period = SchellingGameShared::get_period(key.clone()); - - assert_eq!(Some(Period::Commit), period); - - let balance: u64 = Balances::free_balance(5); - assert_eq!(300000 - 5 * 100, balance); - assert_ok!(ProjectTips::unstaking(RuntimeOrigin::signed(5), 1)); - let balance = Balances::free_balance(5); - assert_eq!(300000, balance); - - let hash = sp_io::hashing::keccak_256("1salt".as_bytes()); - assert_noop!( - ProjectTips::commit_vote(RuntimeOrigin::signed(6), 1, hash), - >::JurorDoesNotExists - ); - let hash = sp_io::hashing::keccak_256("1salt".as_bytes()); - assert_ok!(ProjectTips::commit_vote(RuntimeOrigin::signed(4), 1, hash)); - - // You can replace vote within the commit period. - let hash = sp_io::hashing::keccak_256("1salt2".as_bytes()); - assert_ok!(ProjectTips::commit_vote(RuntimeOrigin::signed(4), 1, hash)); - - let hash = sp_io::hashing::keccak_256("1salt3".as_bytes()); - assert_ok!(ProjectTips::commit_vote(RuntimeOrigin::signed(7), 1, hash)); - - let hash = sp_io::hashing::keccak_256("1salt4".as_bytes()); - assert_ok!(ProjectTips::commit_vote(RuntimeOrigin::signed(13), 1, hash)); - - let hash = sp_io::hashing::keccak_256("1salt5".as_bytes()); - assert_ok!(ProjectTips::commit_vote(RuntimeOrigin::signed(14), 1, hash)); - - let hash = sp_io::hashing::keccak_256("0salt6".as_bytes()); - assert_ok!(ProjectTips::commit_vote(RuntimeOrigin::signed(15), 1, hash)); - - assert_noop!( - ProjectTips::pass_period(RuntimeOrigin::signed(5), 1), - >::CommitPeriodNotOver - ); - System::set_block_number( - phase_data.evidence_length + 1 + phase_data.staking_length + phase_data.commit_length, - ); - assert_ok!(ProjectTips::pass_period(RuntimeOrigin::signed(5), 1)); - - assert_noop!( - ProjectTips::reveal_vote( - RuntimeOrigin::signed(4), - 1, - 2, - "salt2".as_bytes().to_vec() - ), - >::CommitDoesNotMatch - ); - - assert_ok!(ProjectTips::reveal_vote( - RuntimeOrigin::signed(4), - 1, - 1, - "salt2".as_bytes().to_vec() - )); - - assert_ok!(ProjectTips::reveal_vote( - RuntimeOrigin::signed(7), - 1, - 1, - "salt3".as_bytes().to_vec() - )); - - assert_ok!(ProjectTips::reveal_vote( - RuntimeOrigin::signed(13), - 1, - 1, - "salt4".as_bytes().to_vec() - )); - - assert_ok!(ProjectTips::reveal_vote( - RuntimeOrigin::signed(14), - 1, - 1, - "salt5".as_bytes().to_vec() - )); - - assert_noop!( - ProjectTips::pass_period(RuntimeOrigin::signed(5), 1), - >::VotePeriodNotOver - ); - System::set_block_number( - phase_data.evidence_length - + 1 + phase_data.staking_length - + phase_data.commit_length - + phase_data.vote_length, - ); - assert_ok!(ProjectTips::pass_period(RuntimeOrigin::signed(5), 1)); - - assert_noop!( - ProjectTips::get_incentives(RuntimeOrigin::signed(15), 1), - >::VoteNotRevealed - ); - let balance: u64 = Balances::free_balance(14); - assert_eq!(300000 - 14 * 100, balance); - assert_ok!(ProjectTips::get_incentives(RuntimeOrigin::signed(14), 1)); - let balance: u64 = Balances::free_balance(14); - assert_eq!(300025, balance); - }) + System::set_block_number(1); + let tipping_name = TippingName::SmallTipper; + let tipping_value = ProjectTips::value_of_tipping_name(tipping_name); + let max_tipping_value = tipping_value.max_tipping_value; + let stake_required = tipping_value.stake_required; + let funding_needed = max_tipping_value - 100; + let balance = Balances::free_balance(1); + assert_ok!(ProjectTips::create_project( + RuntimeOrigin::signed(1), + 2, + tipping_name, + funding_needed + )); + + let after_balance = Balances::free_balance(1); + + assert_eq!(after_balance, balance - stake_required); + + assert_ok!(ProjectTips::apply_staking_period(RuntimeOrigin::signed(1), 1)); + + let phase_data = ProjectTips::get_phase_data(); + + let balance = Balances::free_balance(29); + assert_eq!(300000, balance); + for j in 4..30 { + assert_ok!(ProjectTips::apply_jurors(RuntimeOrigin::signed(j), 1, j * 100)); + } + + let balance = Balances::free_balance(29); + assert_eq!(300000 - 29 * 100, balance); + + assert_noop!( + ProjectTips::draw_jurors(RuntimeOrigin::signed(5), 1, 5), + >::PeriodDontMatch + ); + + assert_noop!( + ProjectTips::pass_period(RuntimeOrigin::signed(5), 1), + >::StakingPeriodNotOver + ); + + System::set_block_number(1 + phase_data.staking_length); + + assert_ok!(ProjectTips::pass_period(RuntimeOrigin::signed(5), 1)); + + assert_ok!(ProjectTips::draw_jurors(RuntimeOrigin::signed(5), 1, 5)); + let key = SumTreeName::ProjectTips { project_id: 1, block_number: 1 }; + + let draws_in_round = SchellingGameShared::draws_in_round(key.clone()); + assert_eq!(5, draws_in_round); + + let drawn_jurors = SchellingGameShared::drawn_jurors(key.clone()); + assert_eq!(vec![(4, 400), (7, 700), (13, 1300), (14, 1400), (15, 1500)], drawn_jurors); + + assert_ok!(ProjectTips::pass_period(RuntimeOrigin::signed(5), 1)); + + let period = SchellingGameShared::get_period(key.clone()); + + assert_eq!(Some(Period::Commit), period); + + let balance: u64 = Balances::free_balance(5); + assert_eq!(300000 - 5 * 100, balance); + assert_ok!(ProjectTips::unstaking(RuntimeOrigin::signed(5), 1)); + let balance = Balances::free_balance(5); + assert_eq!(300000, balance); + + let hash = sp_io::hashing::keccak_256("1salt".as_bytes()); + assert_noop!( + ProjectTips::commit_vote(RuntimeOrigin::signed(6), 1, hash), + >::JurorDoesNotExists + ); + let hash = sp_io::hashing::keccak_256("1salt".as_bytes()); + assert_ok!(ProjectTips::commit_vote(RuntimeOrigin::signed(4), 1, hash)); + + // You can replace vote within the commit period. + let hash = sp_io::hashing::keccak_256("1salt2".as_bytes()); + assert_ok!(ProjectTips::commit_vote(RuntimeOrigin::signed(4), 1, hash)); + + let hash = sp_io::hashing::keccak_256("1salt3".as_bytes()); + assert_ok!(ProjectTips::commit_vote(RuntimeOrigin::signed(7), 1, hash)); + + let hash = sp_io::hashing::keccak_256("1salt4".as_bytes()); + assert_ok!(ProjectTips::commit_vote(RuntimeOrigin::signed(13), 1, hash)); + + let hash = sp_io::hashing::keccak_256("1salt5".as_bytes()); + assert_ok!(ProjectTips::commit_vote(RuntimeOrigin::signed(14), 1, hash)); + + let hash = sp_io::hashing::keccak_256("0salt6".as_bytes()); + assert_ok!(ProjectTips::commit_vote(RuntimeOrigin::signed(15), 1, hash)); + + assert_noop!( + ProjectTips::pass_period(RuntimeOrigin::signed(5), 1), + >::CommitPeriodNotOver + ); + System::set_block_number( + phase_data.evidence_length + 1 + phase_data.staking_length + phase_data.commit_length, + ); + assert_ok!(ProjectTips::pass_period(RuntimeOrigin::signed(5), 1)); + + assert_noop!( + ProjectTips::reveal_vote(RuntimeOrigin::signed(4), 1, 2, "salt2".as_bytes().to_vec()), + >::CommitDoesNotMatch + ); + + assert_ok!(ProjectTips::reveal_vote( + RuntimeOrigin::signed(4), + 1, + 1, + "salt2".as_bytes().to_vec() + )); + + assert_ok!(ProjectTips::reveal_vote( + RuntimeOrigin::signed(7), + 1, + 1, + "salt3".as_bytes().to_vec() + )); + + assert_ok!(ProjectTips::reveal_vote( + RuntimeOrigin::signed(13), + 1, + 1, + "salt4".as_bytes().to_vec() + )); + + assert_ok!(ProjectTips::reveal_vote( + RuntimeOrigin::signed(14), + 1, + 1, + "salt5".as_bytes().to_vec() + )); + + assert_noop!( + ProjectTips::pass_period(RuntimeOrigin::signed(5), 1), + >::VotePeriodNotOver + ); + System::set_block_number( + phase_data.evidence_length + + 1 + phase_data.staking_length + + phase_data.commit_length + + phase_data.vote_length, + ); + assert_ok!(ProjectTips::pass_period(RuntimeOrigin::signed(5), 1)); + + assert_noop!( + ProjectTips::get_incentives(RuntimeOrigin::signed(15), 1), + >::VoteNotRevealed + ); + let balance: u64 = Balances::free_balance(14); + assert_eq!(300000 - 14 * 100, balance); + assert_ok!(ProjectTips::get_incentives(RuntimeOrigin::signed(14), 1)); + let balance: u64 = Balances::free_balance(14); + assert_eq!(300025, balance); + }) } diff --git a/pallets/project-tips/src/types.rs b/pallets/project-tips/src/types.rs index d12371a..f3a36e2 100644 --- a/pallets/project-tips/src/types.rs +++ b/pallets/project-tips/src/types.rs @@ -5,9 +5,6 @@ use scale_info::TypeInfo; pub const PROJECT_ID: ProjectId = 1; - - - #[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, RuntimeDebug, TypeInfo)] pub enum TippingName { SmallTipper, @@ -33,6 +30,3 @@ pub struct Project { pub funding_needed: BalanceOf, pub project_leader: T::AccountId, } - - - diff --git a/pallets/schelling-game-shared/src/functions.rs b/pallets/schelling-game-shared/src/functions.rs index 359381a..889684f 100644 --- a/pallets/schelling-game-shared/src/functions.rs +++ b/pallets/schelling-game-shared/src/functions.rs @@ -95,7 +95,7 @@ impl PhaseData { let commit_length = commit_length.saturated_into::>(); let vote_length = vote_length.saturated_into::>(); let appeal_length = appeal_length.saturated_into::>(); - + let min_juror_stake = min_juror_stake.saturated_into::>(); PhaseData { evidence_length, diff --git a/pallets/schelling-game-shared/src/lib.rs b/pallets/schelling-game-shared/src/lib.rs index cfe9414..865089d 100644 --- a/pallets/schelling-game-shared/src/lib.rs +++ b/pallets/schelling-game-shared/src/lib.rs @@ -11,8 +11,6 @@ mod mock; #[cfg(test)] mod tests; - - #[cfg(feature = "runtime-benchmarks")] mod benchmarking; pub mod weights; @@ -20,9 +18,9 @@ pub use weights::*; mod extras; mod functions; -pub mod types; mod score_game; mod share_link; +pub mod types; use crate::types::{ CommitVote, Period, PhaseData, RangePoint, RevealedVote, SchellingGameType, ScoreCommitVote, @@ -96,7 +94,6 @@ pub mod pallet { #[pallet::storage] pub type Nonce = StorageValue<_, u64, ValueQuery>; - #[pallet::storage] #[pallet::getter(fn get_period)] pub type PeriodName = StorageMap<_, Blake2_128Concat, SumTreeNameType, Period>; diff --git a/pallets/schelling-game-shared/src/score_game.rs b/pallets/schelling-game-shared/src/score_game.rs index 07dc518..07971ff 100644 --- a/pallets/schelling-game-shared/src/score_game.rs +++ b/pallets/schelling-game-shared/src/score_game.rs @@ -99,7 +99,6 @@ impl Pallet { .collect::>(); reveal_votes.sort_by(|a, b| a.0.cmp(&b.0)); - // println!("reveal votes, {:?}",reveal_votes); let mut winners = vec![]; for juror in drawn_jurors { @@ -109,8 +108,8 @@ impl Pallet { let account_n_vote = &reveal_votes[index]; if let Some(i) = account_n_vote.1 { // println!("vote {:?}", i); - if i*1000 >= new_mean.checked_sub(incentives_range).unwrap() - && i*1000 <= new_mean.checked_add(incentives_range).unwrap() + if i * 1000 >= new_mean.checked_sub(incentives_range).unwrap() + && i * 1000 <= new_mean.checked_add(incentives_range).unwrap() { // get incentives winners.push((juror.0.clone(), juror.1.clone())); @@ -150,14 +149,13 @@ impl Pallet { >::remove(&key); // Remove UnstakedJurors (all jurors can be returned their incentives at a time) - // Remove ScoreVoteCommits >::remove_prefix(key.clone(), None); // Deprecated: Use clear_prefix instead - // let reveal_votes_iterator2 = >::iter_prefix(&key); - // reveal_votes_iterator2.for_each(|(account_id, _)|{ - // >::remove(key.clone(), account_id); - // }); + // let reveal_votes_iterator2 = >::iter_prefix(&key); + // reveal_votes_iterator2.for_each(|(account_id, _)|{ + // >::remove(key.clone(), account_id); + // }); // Remove RevealScoreValues >::remove(&key); @@ -165,12 +163,10 @@ impl Pallet { Ok(()) } - - pub(super) fn get_mean_value(key: SumTreeNameType) -> i64 { - let value = >::get(key.clone()); - value - } - + pub(super) fn get_mean_value(key: SumTreeNameType) -> i64 { + let value = >::get(key.clone()); + value + } /// Calculate the mean of integer pub(super) fn mean_integer(data: &Vec) -> Option { diff --git a/pallets/schelling-game-shared/src/types.rs b/pallets/schelling-game-shared/src/types.rs index 47529c9..3dbfa85 100644 --- a/pallets/schelling-game-shared/src/types.rs +++ b/pallets/schelling-game-shared/src/types.rs @@ -1,7 +1,7 @@ +use super::*; use frame_support::pallet_prelude::*; use frame_support::sp_std::prelude::*; use scale_info::TypeInfo; -use super::*; #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, MaxEncodedLen, TypeInfo)] #[cfg_attr(feature = "std", derive(Debug))] @@ -11,7 +11,7 @@ pub enum Period { Drawing, // Jurors can be drawn. Pass after all disputes have jurors or `maxDrawingTime` passes. Commit, // Jurors commit a hashed vote. This is skipped for courts without hidden votes. Vote, // Jurors reveal/cast their vote depending on whether the court has hidden votes or not. - Appeal, // The dispute can be appealed. + Appeal, // The dispute can be appealed. Execution, // Tokens are redistributed and the ruling is executed. } @@ -26,7 +26,6 @@ pub enum SchellingGameType { DepartmentScore, } - #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)] #[scale_info(skip_type_params(T))] pub struct PhaseData { @@ -43,7 +42,6 @@ pub struct PhaseData { pub juror_incentives: (u64, u64), // (looser burn, winner mint) } - // #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, MaxEncodedLen, TypeInfo)] // #[cfg_attr(feature = "std", derive(Debug))] // pub struct StakingTime { @@ -85,10 +83,9 @@ pub enum RevealedVote { pub enum WinningDecision { WinnerYes, WinnerNo, - Draw + Draw, } - #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, MaxEncodedLen, TypeInfo)] #[cfg_attr(feature = "std", derive(Debug))] pub struct ScoreCommitVote { @@ -97,10 +94,8 @@ pub struct ScoreCommitVote { pub revealed_vote: Option, } - - /// RangePoint enum to determine whether score values are from -/// 1) ZeroToTen: 0 to 10 +/// 1) ZeroToTen: 0 to 10 /// 2) MinusTenToPlusTen: -10 to +10 /// 3) ZeroToFive: 0 to 5 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, MaxEncodedLen, TypeInfo)] @@ -109,4 +104,4 @@ pub enum RangePoint { ZeroToTen, MinusTenToPlusTen, ZeroToFive, -} \ No newline at end of file +} diff --git a/pallets/shared-storage/src/extras.rs b/pallets/shared-storage/src/extras.rs index 07b93ce..22292ce 100644 --- a/pallets/shared-storage/src/extras.rs +++ b/pallets/shared-storage/src/extras.rs @@ -12,7 +12,7 @@ impl SharedStorageLink for Pallet { Self::get_approved_citizen_count() } - fn set_positive_externality_link(address: Self::AccountId, score: i64)-> DispatchResult { + fn set_positive_externality_link(address: Self::AccountId, score: i64) -> DispatchResult { Self::set_positive_externality(address, score) } } @@ -33,7 +33,7 @@ impl Pallet { } pub(super) fn set_positive_externality(address: T::AccountId, score: Score) -> DispatchResult { - PositiveExternalityScore::::insert(address,score); + PositiveExternalityScore::::insert(address, score); Ok(()) } } diff --git a/pallets/shared-storage/src/lib.rs b/pallets/shared-storage/src/lib.rs index eb2b976..6d0183a 100644 --- a/pallets/shared-storage/src/lib.rs +++ b/pallets/shared-storage/src/lib.rs @@ -17,7 +17,7 @@ pub mod weights; pub use weights::*; mod extras; -use frame_support::sp_std::{prelude::*}; +use frame_support::sp_std::prelude::*; use frame_support::{dispatch::DispatchResult, pallet_prelude::*}; type AccountIdOf = ::AccountId; @@ -54,14 +54,13 @@ pub mod pallet { #[pallet::getter(fn approved_citizen_address)] pub type ApprovedCitizenAddress = StorageValue<_, Vec, ValueQuery>; // Its set, add element through binary_search - #[pallet::storage] #[pallet::getter(fn positive_externality_score)] - pub type PositiveExternalityScore = StorageMap<_, Blake2_128Concat, T::AccountId, Score, ValueQuery>; + pub type PositiveExternalityScore = + StorageMap<_, Blake2_128Concat, T::AccountId, Score, ValueQuery>; // Keep winning representatives of department in shared storage - #[pallet::genesis_config] pub struct GenesisConfig { pub approved_citizen_address: Vec, diff --git a/pallets/sortition-sum-game/src/extras.rs b/pallets/sortition-sum-game/src/extras.rs index 60d6685..358901a 100644 --- a/pallets/sortition-sum-game/src/extras.rs +++ b/pallets/sortition-sum-game/src/extras.rs @@ -16,9 +16,12 @@ impl SortitionSumGameLink for Pallet { ) -> Result, DispatchError> { Self::stake_of(key, citizen_id) } - fn draw_link(key: Self::SumTreeName, draw_number: u64) -> Result { - Self::draw(key, draw_number) - } + fn draw_link( + key: Self::SumTreeName, + draw_number: u64, + ) -> Result { + Self::draw(key, draw_number) + } fn remove_tree_link(key: Self::SumTreeName) -> DispatchResult { Self::remove_tree(key) } @@ -196,7 +199,10 @@ impl Pallet { } } - pub fn draw(key: SumTreeNameType, draw_number: u64) -> Result, DispatchError> { + pub fn draw( + key: SumTreeNameType, + draw_number: u64, + ) -> Result, DispatchError> { let tree_option = >::get(&key); match tree_option { @@ -276,7 +282,7 @@ impl Pallet { } } - pub fn remove_tree(key: SumTreeNameType)-> DispatchResult { + pub fn remove_tree(key: SumTreeNameType) -> DispatchResult { >::remove(&key); Ok(()) } diff --git a/pallets/sortition-sum-game/src/lib.rs b/pallets/sortition-sum-game/src/lib.rs index 1120bb4..3162357 100644 --- a/pallets/sortition-sum-game/src/lib.rs +++ b/pallets/sortition-sum-game/src/lib.rs @@ -16,8 +16,8 @@ mod benchmarking; pub mod weights; pub use weights::*; -pub mod types; mod extras; +pub mod types; use crate::types::{SortitionSumTree, SumTreeName}; use frame_support::sp_std::{collections::btree_map::BTreeMap, vec::Vec}; @@ -85,7 +85,7 @@ pub mod pallet { impl Pallet { /// An example dispatchable that takes a singles value as a parameter, writes the value to /// storage and emits an event. This function must be dispatched by a signed extrinsic. - + /// An example dispatchable that may throw a custom error. #[pallet::call_index(1)] #[pallet::weight(T::WeightInfo::cause_error())] diff --git a/pallets/sortition-sum-game/src/types.rs b/pallets/sortition-sum-game/src/types.rs index 48e8388..2c77d08 100644 --- a/pallets/sortition-sum-game/src/types.rs +++ b/pallets/sortition-sum-game/src/types.rs @@ -1,5 +1,5 @@ -use frame_support::{pallet_prelude::*}; -use frame_support::sp_std::{vec::Vec, collections::btree_map::BTreeMap}; +use frame_support::pallet_prelude::*; +use frame_support::sp_std::{collections::btree_map::BTreeMap, vec::Vec}; use scale_info::TypeInfo; type CitizenId = u64; @@ -7,23 +7,18 @@ type CitizenId = u64; #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, TypeInfo)] #[cfg_attr(feature = "std", derive(Debug))] pub enum SumTreeName { - ProfileValidation { citizen_address: AccountId, block_number: BlockNumber}, - PositiveExternality {user_address: AccountId, block_number: BlockNumber }, - DepartmentRequiredFund {department_required_fund_id: u64, block_number: BlockNumber}, - ProjectTips { project_id: u64, block_number: BlockNumber }, + ProfileValidation { citizen_address: AccountId, block_number: BlockNumber }, + PositiveExternality { user_address: AccountId, block_number: BlockNumber }, + DepartmentRequiredFund { department_required_fund_id: u64, block_number: BlockNumber }, + ProjectTips { project_id: u64, block_number: BlockNumber }, } - #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, TypeInfo)] #[cfg_attr(feature = "std", derive(Debug))] pub struct SortitionSumTree { - pub k: u64, - pub stack: Vec, - pub nodes: Vec, - pub ids_to_node_indexes: BTreeMap, // citizen id, node index - pub node_indexes_to_ids: BTreeMap, // node index, citizen id + pub k: u64, + pub stack: Vec, + pub nodes: Vec, + pub ids_to_node_indexes: BTreeMap, // citizen id, node index + pub node_indexes_to_ids: BTreeMap, // node index, citizen id } - - - - diff --git a/pallets/spaces/src/extras.rs b/pallets/spaces/src/extras.rs index 390a90c..cb85d65 100644 --- a/pallets/spaces/src/extras.rs +++ b/pallets/spaces/src/extras.rs @@ -1,8 +1,8 @@ use crate::*; impl Pallet { - /// Get `Space` by id from the storage or return `SpaceNotFound` error. - pub fn require_space(space_id: SpaceId) -> Result, DispatchError> { - Ok(Self::space_by_id(space_id).ok_or(Error::::SpaceNotFound)?) - } + /// Get `Space` by id from the storage or return `SpaceNotFound` error. + pub fn require_space(space_id: SpaceId) -> Result, DispatchError> { + Ok(Self::space_by_id(space_id).ok_or(Error::::SpaceNotFound)?) + } } diff --git a/pallets/spaces/src/lib.rs b/pallets/spaces/src/lib.rs index 29cd64d..722a7fd 100644 --- a/pallets/spaces/src/lib.rs +++ b/pallets/spaces/src/lib.rs @@ -16,23 +16,18 @@ mod benchmarking; pub mod weights; pub use weights::*; - pub mod extras; pub mod types; - - use frame_support::sp_std::prelude::*; // use scale_info::prelude::format; use crate::types::RESERVED_SPACE_COUNT; - use frame_support::pallet_prelude::{DispatchResult, *}; use frame_system::pallet_prelude::*; use pallet_support::{Content, SpaceId}; use types::Space; - #[frame_support::pallet] pub mod pallet { use super::*; @@ -45,7 +40,7 @@ pub mod pallet { /// Configure the pallet by specifying the parameters and types on which it depends. #[pallet::config] - pub trait Config: frame_system::Config + pallet_timestamp::Config{ + pub trait Config: frame_system::Config + pallet_timestamp::Config { /// Because this pallet emits events, it depends on the runtime's definition of an event. type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// Type representing the weight of this pallet @@ -61,21 +56,19 @@ pub mod pallet { pub type Something = StorageValue<_, u32>; #[pallet::type_value] - pub fn DefaultForNextSpaceId() -> SpaceId { - RESERVED_SPACE_COUNT + 1 - } + pub fn DefaultForNextSpaceId() -> SpaceId { + RESERVED_SPACE_COUNT + 1 + } /// The next space id. - #[pallet::storage] - #[pallet::getter(fn next_space_id)] - pub type NextSpaceId = StorageValue<_, SpaceId, ValueQuery, DefaultForNextSpaceId>; + #[pallet::storage] + #[pallet::getter(fn next_space_id)] + pub type NextSpaceId = StorageValue<_, SpaceId, ValueQuery, DefaultForNextSpaceId>; /// Get the details of a space by its' id. - #[pallet::storage] - #[pallet::getter(fn space_by_id)] - pub type SpaceById = StorageMap<_, Twox64Concat, SpaceId, Space>; - - + #[pallet::storage] + #[pallet::getter(fn space_by_id)] + pub type SpaceById = StorageMap<_, Twox64Concat, SpaceId, Space>; // Pallets use events to inform users when important changes are made. // https://docs.substrate.io/main-docs/build/events-errors/ diff --git a/pallets/spaces/src/mock.rs b/pallets/spaces/src/mock.rs index 9cab0e9..48186f4 100644 --- a/pallets/spaces/src/mock.rs +++ b/pallets/spaces/src/mock.rs @@ -1,5 +1,8 @@ use crate as pallet_template; -use frame_support::{parameter_types, traits::{ConstU16, ConstU64}}; +use frame_support::{ + parameter_types, + traits::{ConstU16, ConstU64}, +}; use sp_core::H256; use sp_runtime::{ testing::Header, @@ -55,14 +58,14 @@ impl pallet_template::Config for Test { } parameter_types! { - pub const MinimumPeriod: u64 = 5; + pub const MinimumPeriod: u64 = 5; } impl pallet_timestamp::Config for Test { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); } // Build genesis storage according to the mock runtime. diff --git a/pallets/spaces/src/types.rs b/pallets/spaces/src/types.rs index a78dbc7..0a2c2ef 100644 --- a/pallets/spaces/src/types.rs +++ b/pallets/spaces/src/types.rs @@ -1,63 +1,55 @@ -use frame_support::{pallet_prelude::*}; -use frame_support::sp_std::{vec::Vec}; +use frame_support::pallet_prelude::*; +use frame_support::sp_std::vec::Vec; use scale_info::TypeInfo; use super::*; use pallet_support::{new_who_and_when, WhoAndWhenOf}; - pub const FIRST_SPACE_ID: u64 = 1; pub const RESERVED_SPACE_COUNT: u64 = 1000; - /// Information about a space's owner, its' content, visibility and custom permissions. #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)] #[scale_info(skip_type_params(T))] pub struct Space { - /// Unique sequential identifier of a space. Examples of space ids: `1`, `2`, `3`, and so on. - pub id: SpaceId, + /// Unique sequential identifier of a space. Examples of space ids: `1`, `2`, `3`, and so on. + pub id: SpaceId, - pub created: WhoAndWhenOf, - /// True, if the content of this space was edited. - pub edited: bool, + pub created: WhoAndWhenOf, + /// True, if the content of this space was edited. + pub edited: bool, - /// The current owner of a given space. - pub owner: T::AccountId, + /// The current owner of a given space. + pub owner: T::AccountId, - // The next fields can be updated by the owner: - pub content: Content, - - /// Hidden field is used to recommend to end clients (web and mobile apps) that a particular - /// space and its' posts should not be shown. - pub hidden: bool, + // The next fields can be updated by the owner: + pub content: Content, + /// Hidden field is used to recommend to end clients (web and mobile apps) that a particular + /// space and its' posts should not be shown. + pub hidden: bool, } #[derive(Encode, Decode, Clone, Eq, PartialEq, Default, RuntimeDebug, TypeInfo)] pub struct SpaceUpdate { - pub content: Option, - pub hidden: Option, + pub content: Option, + pub hidden: Option, } impl Space { - pub fn new( - id: SpaceId, - created_by: T::AccountId, - content: Content, - ) -> Self { - Space { - id, - created: new_who_and_when::(created_by.clone()), - edited: false, - owner: created_by, - content, - hidden: false, - } - } - - pub fn is_owner(&self, account: &T::AccountId) -> bool { - self.owner == *account - } - + pub fn new(id: SpaceId, created_by: T::AccountId, content: Content) -> Self { + Space { + id, + created: new_who_and_when::(created_by.clone()), + edited: false, + owner: created_by, + content, + hidden: false, + } + } + + pub fn is_owner(&self, account: &T::AccountId) -> bool { + self.owner == *account + } } diff --git a/pallets/support/src/lib.rs b/pallets/support/src/lib.rs index 915f674..f1c9d27 100644 --- a/pallets/support/src/lib.rs +++ b/pallets/support/src/lib.rs @@ -7,132 +7,128 @@ use frame_support::pallet_prelude::*; // use frame_support::sp_std::{vec::Vec}; use sp_std::{collections::btree_set::BTreeSet, vec, vec::Vec}; - pub type SpaceId = u64; pub type PostId = u64; pub type PositiveExternalityPostId = u64; #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)] pub struct WhoAndWhen { - pub account: AccountId, - pub block: BlockNumber, - pub time: Moment, + pub account: AccountId, + pub block: BlockNumber, + pub time: Moment, } pub type WhoAndWhenOf = WhoAndWhen< - ::AccountId, - ::BlockNumber, - ::Moment, + ::AccountId, + ::BlockNumber, + ::Moment, >; pub fn new_who_and_when( - account: T::AccountId, + account: T::AccountId, ) -> WhoAndWhen where - T: frame_system::Config + pallet_timestamp::Config, + T: frame_system::Config + pallet_timestamp::Config, { - WhoAndWhen { - account, - block: frame_system::Pallet::::block_number(), - time: pallet_timestamp::Pallet::::now(), - } + WhoAndWhen { + account, + block: frame_system::Pallet::::block_number(), + time: pallet_timestamp::Pallet::::now(), + } } #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)] pub enum Content { - /// No content. - None, - /// A raw vector of bytes. - Other(Vec), - /// IPFS CID v0 of content. - IPFS(Vec), + /// No content. + None, + /// A raw vector of bytes. + Other(Vec), + /// IPFS CID v0 of content. + IPFS(Vec), } impl From for Vec { - fn from(content: Content) -> Vec { - match content { - Content::None => vec![], - Content::Other(vec_u8) => vec_u8, - Content::IPFS(vec_u8) => vec_u8, - } - } + fn from(content: Content) -> Vec { + match content { + Content::None => vec![], + Content::Other(vec_u8) => vec_u8, + Content::IPFS(vec_u8) => vec_u8, + } + } } impl Default for Content { - fn default() -> Self { - Self::None - } + fn default() -> Self { + Self::None + } } impl Content { - pub fn is_none(&self) -> bool { - self == &Self::None - } + pub fn is_none(&self) -> bool { + self == &Self::None + } - pub fn is_some(&self) -> bool { - !self.is_none() - } + pub fn is_some(&self) -> bool { + !self.is_none() + } - pub fn is_ipfs(&self) -> bool { - matches!(self, Self::IPFS(_)) - } + pub fn is_ipfs(&self) -> bool { + matches!(self, Self::IPFS(_)) + } } - #[derive(Encode, Decode, RuntimeDebug, strum::IntoStaticStr)] pub enum ContentError { - /// IPFS CID is invalid. - InvalidIpfsCid, - /// `Other` content type is not yet supported. - OtherContentTypeNotSupported, - /// Content type is `None`. - ContentIsEmpty, + /// IPFS CID is invalid. + InvalidIpfsCid, + /// `Other` content type is not yet supported. + OtherContentTypeNotSupported, + /// Content type is `None`. + ContentIsEmpty, } impl From for DispatchError { - fn from(err: ContentError) -> DispatchError { - Self::Other(err.into()) - } + fn from(err: ContentError) -> DispatchError { + Self::Other(err.into()) + } } - - pub fn ensure_content_is_valid(content: Content) -> DispatchResult { - match content { - Content::None => Ok(()), - Content::Other(_) => Err(ContentError::OtherContentTypeNotSupported.into()), - Content::IPFS(ipfs_cid) => { - let len = ipfs_cid.len(); - // IPFS CID v0 is 46 bytes. - // IPFS CID v1 is 59 bytes. - ensure!(len == 46 || len == 59, ContentError::InvalidIpfsCid); - Ok(()) - }, - } + match content { + Content::None => Ok(()), + Content::Other(_) => Err(ContentError::OtherContentTypeNotSupported.into()), + Content::IPFS(ipfs_cid) => { + let len = ipfs_cid.len(); + // IPFS CID v0 is 46 bytes. + // IPFS CID v1 is 59 bytes. + ensure!(len == 46 || len == 59, ContentError::InvalidIpfsCid); + Ok(()) + }, + } } /// Ensure that a given content is not `None`. pub fn ensure_content_is_some(content: &Content) -> DispatchResult { - ensure!(content.is_some(), ContentError::ContentIsEmpty); - Ok(()) + ensure!(content.is_some(), ContentError::ContentIsEmpty); + Ok(()) } pub fn remove_from_vec(vector: &mut Vec, element: F) { - if let Some(index) = vector.iter().position(|x| *x == element) { - vector.swap_remove(index); - } + if let Some(index) = vector.iter().position(|x| *x == element) { + vector.swap_remove(index); + } } pub fn remove_from_bounded_vec(vector: &mut BoundedVec, element: F) { - if let Some(index) = vector.iter().position(|x| *x == element) { - vector.swap_remove(index); - } + if let Some(index) = vector.iter().position(|x| *x == element) { + vector.swap_remove(index); + } } pub fn bool_to_option(value: bool) -> Option { - if value { - Some(value) - } else { - None - } + if value { + Some(value) + } else { + None + } } diff --git a/pallets/tags/src/extras.rs b/pallets/tags/src/extras.rs index 67b2d1f..2a77a0f 100644 --- a/pallets/tags/src/extras.rs +++ b/pallets/tags/src/extras.rs @@ -37,7 +37,6 @@ impl Pallet { let mut users_that_downvoted = down_vote_details.downvote_users; let dv = down_vote_details.downvote.checked_add(1).ok_or("overflow")?; - match users_that_downvoted.binary_search(&who) { Ok(_) => Err(Error::::UserAlreadyDownVoted.into()), Err(index) => { diff --git a/pallets/tags/src/lib.rs b/pallets/tags/src/lib.rs index 15e324e..e7ad6dd 100644 --- a/pallets/tags/src/lib.rs +++ b/pallets/tags/src/lib.rs @@ -19,15 +19,13 @@ pub use weights::*; mod extras; mod types; - use frame_support::sp_std::prelude::*; type DepartmentId = u128; type DownVoteNum = u8; use frame_support::pallet_prelude::{DispatchResult, *}; use frame_system::pallet_prelude::*; -use types::{DownVoteDetails}; - +use types::DownVoteDetails; #[frame_support::pallet] pub mod pallet { @@ -56,7 +54,6 @@ pub mod pallet { // https://docs.substrate.io/main-docs/build/runtime-storage/#declaring-storage-items pub type Something = StorageValue<_, u32>; - /// Department tags #[pallet::storage] #[pallet::getter(fn department_tags)] @@ -66,7 +63,7 @@ pub mod pallet { /// Down vote a tag #[pallet::storage] #[pallet::getter(fn downvote_details_of_tag)] - pub(super) type DownVoteDetailsTags = StorageDoubleMap< + pub(super) type DownVoteDetailsTags = StorageDoubleMap< _, Blake2_128Concat, DepartmentId, @@ -88,7 +85,6 @@ pub mod pallet { pub type DownVoteThreshold = StorageValue<_, DownVoteNum, ValueQuery, DefaultDownVoteThreshold>; - // Pallets use events to inform users when important changes are made. // https://docs.substrate.io/main-docs/build/events-errors/ #[pallet::event] @@ -96,7 +92,10 @@ pub mod pallet { pub enum Event { /// Event documentation should end with an array that provides descriptive names for event /// parameters. [something, who] - SomethingStored { something: u32, who: T::AccountId }, + SomethingStored { + something: u32, + who: T::AccountId, + }, TagInserted(DepartmentId, Vec), // Tag inserted TagRemoved(DepartmentId, Vec), @@ -119,7 +118,7 @@ pub mod pallet { // Dispatchable functions must be annotated with a weight and must return a DispatchResult. #[pallet::call] impl Pallet { - /// Create tag + /// Create tag /// [] Check who belongs to department representative /// [] Limit the length of tag #[pallet::call_index(0)] @@ -148,7 +147,7 @@ pub mod pallet { /// [] Check tags exsts in Tags /// [✓] Check user has not downvoted again /// [✓] Delete tag if it reaches maximum downvote - + #[pallet::call_index(1)] #[pallet::weight(Weight::from_parts(10_000, u64::MAX) + T::DbWeight::get().writes(1))] pub fn donwvote_tag( @@ -157,7 +156,7 @@ pub mod pallet { tag: Vec, ) -> DispatchResult { let who = ensure_signed(origin)?; - Self::ensure_tag_exists(departmentid,tag.clone())?; + Self::ensure_tag_exists(departmentid, tag.clone())?; let dv = Self::ensure_user_not_downvoted_then_downvote(departmentid, who, tag.clone())?; let threshold = DownVoteThreshold::::get(); @@ -167,9 +166,6 @@ pub mod pallet { Ok(()) } - // Remove down vote - - - + // Remove down vote } } diff --git a/pallets/tags/src/tests.rs b/pallets/tags/src/tests.rs index 632c718..2550aaf 100644 --- a/pallets/tags/src/tests.rs +++ b/pallets/tags/src/tests.rs @@ -1,4 +1,4 @@ -use crate::{mock::*, Error, Event, types::DownVoteDetails}; +use crate::{mock::*, types::DownVoteDetails, Error, Event}; use frame_support::{assert_noop, assert_ok}; #[test] @@ -54,7 +54,11 @@ fn downvote_remove_tag() { let down_vote_threshold = TemplateModule::downvote_threshold(); assert_ok!(TemplateModule::add_tag(RuntimeOrigin::signed(1), 1, tag.clone())); for x in 1..down_vote_threshold { - assert_ok!(TemplateModule::donwvote_tag(RuntimeOrigin::signed(x.into()), 1, tag.clone())); + assert_ok!(TemplateModule::donwvote_tag( + RuntimeOrigin::signed(x.into()), + 1, + tag.clone() + )); let downvote_details = TemplateModule::downvote_details_of_tag(1, tag.clone()); assert_eq!(downvote_details.downvote, x); // println!("x={}", x); diff --git a/pallets/tags/src/types.rs b/pallets/tags/src/types.rs index b9a5d0e..19aa0e9 100644 --- a/pallets/tags/src/types.rs +++ b/pallets/tags/src/types.rs @@ -1,16 +1,16 @@ -use frame_support::{pallet_prelude::*}; -use frame_support::sp_std::{vec::Vec}; -use scale_info::TypeInfo; use crate::DownVoteNum; +use frame_support::pallet_prelude::*; +use frame_support::sp_std::vec::Vec; +use scale_info::TypeInfo; #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, RuntimeDebug, TypeInfo)] pub struct DownVoteDetails { - pub downvote: DownVoteNum, - pub downvote_users: Vec, + pub downvote: DownVoteNum, + pub downvote_users: Vec, } impl Default for DownVoteDetails { - fn default() -> Self { - Self {downvote: Default::default(), downvote_users: vec![]} - } -} \ No newline at end of file + fn default() -> Self { + Self { downvote: Default::default(), downvote_users: vec![] } + } +} diff --git a/pallets/ubi/src/extras.rs b/pallets/ubi/src/extras.rs index 8ea4eac..5aae4f5 100644 --- a/pallets/ubi/src/extras.rs +++ b/pallets/ubi/src/extras.rs @@ -1,7 +1,7 @@ use crate::*; impl Pallet { - pub(super) fn u64_to_balance_saturated(input: u64) -> BalanceOf { + pub(super) fn u64_to_balance_saturated(input: u64) -> BalanceOf { input.saturated_into::>() } diff --git a/pallets/ubi/src/lib.rs b/pallets/ubi/src/lib.rs index 50b1871..7843d5f 100644 --- a/pallets/ubi/src/lib.rs +++ b/pallets/ubi/src/lib.rs @@ -97,7 +97,6 @@ pub mod pallet { // Dispatchable functions must be annotated with a weight and must return a DispatchResult. #[pallet::call] impl Pallet { - #[pallet::call_index(0)] #[pallet::weight(Weight::from_parts(10_000, u64::MAX) + T::DbWeight::get().writes(1))] pub fn fun_ubi(origin: OriginFor) -> DispatchResult { diff --git a/pallets/ubi/src/mock.rs b/pallets/ubi/src/mock.rs index 09ac1a5..fd4765a 100644 --- a/pallets/ubi/src/mock.rs +++ b/pallets/ubi/src/mock.rs @@ -50,7 +50,6 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; // New code } - impl shared_storage::Config for Test { type RuntimeEvent = RuntimeEvent; type WeightInfo = (); diff --git a/pallets/ubi/src/tests.rs b/pallets/ubi/src/tests.rs index 00940e5..b47a3ac 100644 --- a/pallets/ubi/src/tests.rs +++ b/pallets/ubi/src/tests.rs @@ -12,7 +12,5 @@ fn it_works_for_default_value() { #[test] fn correct_error_for_none_value() { - new_test_ext().execute_with(|| { - - }); + new_test_ext().execute_with(|| {}); } diff --git a/runtime/node-runtime/Cargo.toml b/runtime/node-runtime/Cargo.toml index 918ff1c..d31e5d9 100644 --- a/runtime/node-runtime/Cargo.toml +++ b/runtime/node-runtime/Cargo.toml @@ -65,6 +65,9 @@ profile-validation-runtime-api = {default-features=false, path="../../pallets/pr positive-externality = {default-features = false, path="../../pallets/positive-externality"} department-funding = {default-features = false, path="../../pallets/department-funding"} project-tips = {default-features = false, path="../../pallets/project-tips"} +positive-externality-runtime-api = {default-features=false, path="../../pallets/positive-externality/positive-externality-runtime-api"} +department-funding-runtime-api = {default-features=false, path="../../pallets/department-funding/department-funding-runtime-api"} +project-tips-runtime-api = {default-features=false, path="../../pallets/project-tips/project-tips-runtime-api"} [build-dependencies] @@ -113,6 +116,9 @@ std = [ "profile-validation/std", # "shared-storage/std", "profile-validation-runtime-api/std", + "positive-externality-runtime-api/std", + "department-funding-runtime-api/std", + "project-tips-runtime-api/std", "positive-externality/std", "shared-storage/std", ] diff --git a/runtime/node-runtime/src/lib.rs b/runtime/node-runtime/src/lib.rs index aa8bd70..b072c32 100644 --- a/runtime/node-runtime/src/lib.rs +++ b/runtime/node-runtime/src/lib.rs @@ -69,6 +69,10 @@ pub type Hash = sp_core::H256; pub type ChallengePostId = u64; +pub type DepartmentRequiredFundId = u64; + +type ProjectId = u64; + /// Opaque types. These are used by the CLI to instantiate machinery that don't need to know /// the specifics of the runtime. They can then be made to be agnostic over specific formats /// of data like extrinsics, allowing for them to continue syncing the network through upgrades @@ -664,6 +668,78 @@ impl_runtime_apis! { } } + impl department_funding_runtime_api::DepartmentFundingApi for Runtime { + + fn get_evidence_period_end_block(department_required_fund_id: DepartmentRequiredFundId) -> Option { + DepartmentFunding::get_evidence_period_end_block(department_required_fund_id) + } + + fn get_staking_period_end_block(department_required_fund_id: DepartmentRequiredFundId) -> Option { + DepartmentFunding::get_staking_period_end_block(department_required_fund_id) + } + fn get_drawing_period_end(department_required_fund_id: DepartmentRequiredFundId) -> (u64, u64, bool) { + DepartmentFunding::get_drawing_period_end(department_required_fund_id) + } + fn get_commit_period_end_block(department_required_fund_id: DepartmentRequiredFundId) -> Option { + DepartmentFunding::get_commit_period_end_block(department_required_fund_id) + } + + fn get_vote_period_end_block(department_required_fund_id: DepartmentRequiredFundId) -> Option { + DepartmentFunding::get_vote_period_end_block(department_required_fund_id) + } + fn selected_as_juror(department_required_fund_id: DepartmentRequiredFundId, who: AccountId) -> bool { + DepartmentFunding::selected_as_juror(department_required_fund_id, who) + } + } + + impl positive_externality_runtime_api::PositiveExternalityApi for Runtime { + + fn get_evidence_period_end_block(user_to_calculate: AccountId) -> Option { + PositiveExternality::get_evidence_period_end_block(user_to_calculate) + } + + fn get_staking_period_end_block(user_to_calculate: AccountId) -> Option { + PositiveExternality::get_staking_period_end_block(user_to_calculate) + } + fn get_drawing_period_end(user_to_calculate: AccountId) -> (u64, u64, bool) { + PositiveExternality::get_drawing_period_end(user_to_calculate) + } + fn get_commit_period_end_block(user_to_calculate: AccountId) -> Option { + PositiveExternality::get_commit_period_end_block(user_to_calculate) + } + + fn get_vote_period_end_block(user_to_calculate: AccountId) -> Option { + PositiveExternality::get_vote_period_end_block(user_to_calculate) + } + fn selected_as_juror(user_to_calculate: AccountId, who: AccountId) -> bool { + PositiveExternality::selected_as_juror(user_to_calculate, who) + } + } + + impl project_tips_runtime_api::ProjectTipsApi for Runtime { + + fn get_evidence_period_end_block(project_id: ProjectId) -> Option { + ProjectTips::get_evidence_period_end_block(project_id) + } + + fn get_staking_period_end_block(project_id: ProjectId) -> Option { + ProjectTips::get_staking_period_end_block(project_id) + } + fn get_drawing_period_end(project_id: ProjectId) -> (u64, u64, bool) { + ProjectTips::get_drawing_period_end(project_id) + } + fn get_commit_period_end_block(project_id: ProjectId) -> Option { + ProjectTips::get_commit_period_end_block(project_id) + } + + fn get_vote_period_end_block(project_id: ProjectId) -> Option { + ProjectTips::get_vote_period_end_block(project_id) + } + fn selected_as_juror(project_id: ProjectId, who: AccountId) -> bool { + ProjectTips::selected_as_juror(project_id, who) + } + } + } #[cfg(test)] diff --git a/traits/shared-storage-link/src/lib.rs b/traits/shared-storage-link/src/lib.rs index 9093d2f..11ea199 100644 --- a/traits/shared-storage-link/src/lib.rs +++ b/traits/shared-storage-link/src/lib.rs @@ -2,12 +2,10 @@ use frame_support::{dispatch::DispatchResult, pallet_prelude::*}; pub trait SharedStorageLink { - type AccountId; fn check_citizen_is_approved_link(address: Self::AccountId) -> DispatchResult; fn get_approved_citizen_count_link() -> u64; - fn set_positive_externality_link(address: Self::AccountId, score: i64)-> DispatchResult; - + fn set_positive_externality_link(address: Self::AccountId, score: i64) -> DispatchResult; } diff --git a/traits/sortition-sum-game-link/src/lib.rs b/traits/sortition-sum-game-link/src/lib.rs index 63b7567..5e0c4be 100644 --- a/traits/sortition-sum-game-link/src/lib.rs +++ b/traits/sortition-sum-game-link/src/lib.rs @@ -10,6 +10,9 @@ pub trait SortitionSumGameLink { key: Self::SumTreeName, citizen_id: Self::AccountId, ) -> Result, DispatchError>; - fn draw_link(key: Self::SumTreeName, draw_number: u64) -> Result; + fn draw_link( + key: Self::SumTreeName, + draw_number: u64, + ) -> Result; fn remove_tree_link(key: Self::SumTreeName) -> DispatchResult; }