Skip to content

Commit

Permalink
Re-factored the code
Browse files Browse the repository at this point in the history
  • Loading branch information
ndkazu committed Jan 1, 2025
1 parent 57f751d commit b639990
Show file tree
Hide file tree
Showing 5 changed files with 219 additions and 27 deletions.
30 changes: 7 additions & 23 deletions substrate/frame/opf/src/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,6 @@ impl<T: Config> Pallet<T> {
Ok(())
}

// Helper function for project registration
pub fn register_new(project_id: ProjectId<T>) -> DispatchResult {
let mut bounded: BoundedVec<ProjectId<T>, T::MaxProjects> =
WhiteListedProjectAccounts::<T>::get();
let vec = bounded.clone().to_vec();
ensure!(!vec.contains(&project_id), Error::<T>::SubmittedProjectId);
let _ = bounded.try_push(project_id).map_err(|_| Error::<T>::MaximumProjectsNumber);
WhiteListedProjectAccounts::<T>::put(bounded);
Ok(())
}

// Voting Period checks
pub fn period_check() -> DispatchResult {
// Get current voting round & check if we are in voting period or not
Expand All @@ -72,13 +61,9 @@ impl<T: Config> Pallet<T> {
}

pub fn unlist_project(project_id: ProjectId<T>) -> DispatchResult {
let mut bounded: BoundedVec<ProjectId<T>, T::MaxProjects> =
WhiteListedProjectAccounts::<T>::get();
let vec = bounded.clone().to_vec();
ensure!(vec.contains(&project_id), Error::<T>::NoProjectAvailable);
WhiteListedProjectAccounts::<T>::mutate(|value| {
let mut val = value.clone();
val.retain(|x| *x != project_id);
val.retain(|x| x.project_id != project_id);
*value = val;
});

Expand All @@ -101,8 +86,9 @@ impl<T: Config> Pallet<T> {
// for each project, calculate the percentage of votes, the amount to be distributed,
// and then populate the storage Projects
for project in projects {
if ProjectFunds::<T>::contains_key(&project) {
let funds = ProjectFunds::<T>::get(&project);
let project_id = &project.project_id;
if ProjectFunds::<T>::contains_key(project_id) {
let funds = ProjectFunds::<T>::get(project_id);
let project_positive_reward = funds[0];
let project_negative_reward = funds[1];

Expand All @@ -116,7 +102,7 @@ impl<T: Config> Pallet<T> {

// Send calculated reward for reward distribution
let project_info = ProjectInfo {
project_id: project.clone(),
project_id: project.project_id.clone(),
submission_block: when,
amount: final_amount,
};
Expand All @@ -125,15 +111,15 @@ impl<T: Config> Pallet<T> {
let _ = SpendInfo::<T>::new(&project_info);

Self::deposit_event(Event::<T>::ProjectFundingAccepted {
project_id: project,
project_id: project.project_id,
when,
round_number,
amount: project_info.amount,
})
} else {
Self::deposit_event(Event::<T>::ProjectFundingRejected {
when,
project_id: project,
project_id: project.project_id,
})
}
}
Expand Down Expand Up @@ -177,8 +163,6 @@ impl<T: Config> Pallet<T> {

// Create a new round.
let _new_round = VotingRoundInfo::<T>::new();
// Clear WhiteListedProjectAccounts storage
WhiteListedProjectAccounts::<T>::kill();
// Clear ProjectFunds storage
ProjectFunds::<T>::drain();
// Emmit events
Expand Down
11 changes: 7 additions & 4 deletions substrate/frame/opf/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,11 @@ pub mod pallet {
/// List of Whitelisted Project registered
#[pallet::storage]
pub type WhiteListedProjectAccounts<T: Config> =
StorageValue<_, BoundedVec<ProjectId<T>, T::MaxProjects>, ValueQuery>;
StorageValue<_, BoundedVec<ProjectInfo<T>, T::MaxProjects>, ValueQuery>;

/// Whitelisted Projects registration counter
#[pallet::storage]
pub type WhiteListedProjectCounter<T: Config> = StorageValue<_, u32, ValueQuery>;

/// Returns (positive_funds,negative_funds) of Whitelisted Project accounts
#[pallet::storage]
Expand Down Expand Up @@ -226,7 +230,6 @@ pub mod pallet {

#[pallet::call]
impl<T: Config> Pallet<T> {

/// OPF Projects registration
///
/// ## Dispatch Origin
Expand All @@ -251,7 +254,7 @@ pub mod pallet {
pub fn register_project(origin: OriginFor<T>, project_id: ProjectId<T>) -> DispatchResult {
let _caller = ensure_signed(origin)?;
let when = T::BlockNumberProvider::current_block_number();
Self::register_new(project_id.clone())?;
ProjectInfo::<T>::new(project_id.clone());
Self::deposit_event(Event::Projectlisted { when, project_id });
Ok(())
}
Expand Down Expand Up @@ -316,7 +319,7 @@ pub mod pallet {
/// ### Errors
/// - [`Error::<T>::InexistentSpend`]:Spend or Spend index does not exists
/// - [`Error::<T>::NoValidAccount`]: No valid Account_id found
/// - [`Error::<T>::NotClaimingPeriod`]: Still not in claiming period
/// - [`Not Claiming Period`]: Still not in claiming period
///
/// ## Events
/// Emits [`Event::<T>::RewardClaimed`] if successful for a positive approval.
Expand Down
137 changes: 137 additions & 0 deletions substrate/frame/opf/src/mock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Test environment for OPF pallet.
use crate as pallet_opf;
pub use frame_support::{
derive_impl, parameter_types,
traits::{ConstU32, EqualPrivilegeOnly, OnFinalize, OnInitialize},
weights::Weight,
PalletId,
};
pub use sp_runtime::{
traits::{AccountIdConversion, IdentityLookup},
BuildStorage,
};

pub use frame_system::EnsureRoot;
pub type Block = frame_system::mocking::MockBlock<Test>;
pub type Balance = u64;
pub type AccountId = u64;

// Configure a mock runtime to test the pallet.
frame_support::construct_runtime!(
pub struct Test {
System: frame_system,
Balances: pallet_balances,
Preimage: pallet_preimage,
Scheduler: pallet_scheduler,
Opf: pallet_opf,
}
);

parameter_types! {
pub MaxWeight: Weight = Weight::from_parts(2_000_000_000_000, u64::MAX);
}

#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for Test {
type AccountId = AccountId;
type AccountData = pallet_balances::AccountData<Balance>;
type Block = Block;
type Lookup = IdentityLookup<Self::AccountId>;
}

impl pallet_preimage::Config for Test {
type RuntimeEvent = RuntimeEvent;
type WeightInfo = ();
type Currency = Balances;
type ManagerOrigin = EnsureRoot<u64>;
type Consideration = ();
}
impl pallet_scheduler::Config for Test {
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
type PalletsOrigin = OriginCaller;
type RuntimeCall = RuntimeCall;
type MaximumWeight = MaxWeight;
type ScheduleOrigin = EnsureRoot<u64>;
type MaxScheduledPerBlock = ConstU32<100>;
type WeightInfo = ();
type OriginPrivilegeCmp = EqualPrivilegeOnly;
type Preimages = Preimage;
}

#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
impl pallet_balances::Config for Test {
type AccountStore = System;
}

parameter_types! {
pub const PotId: PalletId = PalletId(*b"py/potid");
pub const MaxProjects:u32 = 50;
pub const TemporaryRewards: Balance = 100_000;
pub const VoteLockingPeriod:u32 = 10;
pub const VotingPeriod:u32 = 30;
}
impl pallet_opf::Config for Test {
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type NativeBalance = Balances;
type PotId = PotId;
type MaxProjects = MaxProjects;
type VotingPeriod = VotingPeriod;
type ClaimingPeriod = VotingPeriod;
type VoteValidityPeriod = VotingPeriod;
type BlockNumberProvider = System;
type TemporaryRewards = TemporaryRewards;
type Preimages = Preimage;
type Scheduler = Scheduler;
type WeightInfo = ();
}

//Define some accounts and use them
pub const ALICE: AccountId = 10;
pub const BOB: AccountId = 11;
pub const DAVE: AccountId = 12;
pub const EVE: AccountId = 13;
pub const BSX: Balance = 100_000_000_000;

pub fn expect_events(e: Vec<RuntimeEvent>) {
e.into_iter().for_each(frame_system::Pallet::<Test>::assert_has_event);
}

pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
let pot_account = PotId::get().into_account_truncating();

pallet_balances::GenesisConfig::<Test> {
balances: vec![
(ALICE, 200_000 * BSX),
(BOB, 200_000 * BSX),
(DAVE, 150_000 * BSX),
(EVE, 150_000 * BSX),
(pot_account, 150_000_000 * BSX),
],
}
.assimilate_storage(&mut t)
.unwrap();

let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
55 changes: 55 additions & 0 deletions substrate/frame/opf/src/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Tests for OPF pallet.
pub use super::*;
use crate::mock::*;
use frame_support::{assert_noop, assert_ok, traits::OnIdle};

pub fn next_block() {
System::set_block_number(
<Test as Config>::BlockNumberProvider::current_block_number() + 1,
);
AllPalletsWithSystem::on_initialize(
<Test as Config>::BlockNumberProvider::current_block_number(),
);
AllPalletsWithSystem::on_idle(
<Test as Config>::BlockNumberProvider::current_block_number(),
Weight::MAX,
);
}

pub fn run_to_block(n: BlockNumberFor<Test>) {
while <Test as Config>::BlockNumberProvider::current_block_number() < n {
if <Test as Config>::BlockNumberProvider::current_block_number() > 1 {
AllPalletsWithSystem::on_finalize(
<Test as Config>::BlockNumberProvider::current_block_number(),
);
}
next_block();
}
}

#[test]
fn project_registration_works(){
new_test_ext().execute_with(|| {



})
}
13 changes: 13 additions & 0 deletions substrate/frame/opf/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,19 @@ pub struct ProjectInfo<T: Config> {
pub amount: BalanceOf<T>,
}

impl<T: Config> ProjectInfo<T> {
pub fn new(project_id: ProjectId<T>) {
let submission_block = T::BlockNumberProvider::current_block_number();
let amount = Zero::zero();
let project_info = ProjectInfo { project_id, submission_block, amount };
WhiteListedProjectAccounts::<T>::mutate(|project| {
let _ = project
.try_push(project_info.clone())
.map_err(|_| Error::<T>::MaximumProjectsNumber);
});
}
}

#[derive(Encode, Decode, Clone, PartialEq, MaxEncodedLen, RuntimeDebug, TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct VoteInfo<T: Config> {
Expand Down

0 comments on commit b639990

Please sign in to comment.