forked from JoshOrndorff/substrate-node-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
377 lines (295 loc) · 12.5 KB
/
lib.rs
File metadata and controls
377 lines (295 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
// This file is part of Substrate.
// Copyright (C) 2022 UNIVERSALDOT FOUNDATION.
// 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.
//! # Profile Pallet
//!
//! ## Version: 0.7.0
//!
//! - [`Config`]
//! - [`Pallet`]
//!
//! ## Overview
//!
//! The Profile Pallet creates a user profile per AccountID.
//! The Profile is used to enrich the AccountID information with user specific
//! metadata such as personal interests, name, reputation, etc.
//!
//! ## Interface
//!
//! ### Public Functions
//!
//! - `create_profile` - Function used to create a new user profile.
//! Requirements:
//! 1. Each account can create a single Profile.
//! 2. Profiles are mandatory for creating Tasks.
//! Inputs:
//! - username: BoundedVec,
//! - interests: BoundedVec,
//! - available_hours_per_week: u8,
//! - additional_information
//!
//! - `update_profile` - Function used to update an already existing user profile.
//! Inputs:
//! - username: BoundedVec,
//! - interests: BoundedVec,
//! - available_hours_per_week: u8,
//! - additional_information
//!
//! - `remove_profile` - Function used to delete an existing user profile.
//! Inputs:
//! No Inputs
//!
//! Storage Items:
//! Profiles: Stores profile Information
//! ProfileCount: Counts the total number of Profiles
//! CompletedTasks: Stores the completed Tasks history for a Profile
//!
//! ## Related Modules
//!
#![cfg_attr(not(feature = "std"), no_std)]
pub use pallet::*;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
pub mod weights;
#[frame_support::pallet]
pub mod pallet {
use frame_support::{dispatch::DispatchResult, storage::bounded_vec::BoundedVec, pallet_prelude::*};
use frame_system::pallet_prelude::*;
use frame_support::sp_runtime::traits::Hash;
use frame_support::traits::Currency;
use scale_info::TypeInfo;
use crate::weights::WeightInfo;
use pallet_reputation::{
traits::ReputationHandler,
Pallet as ReputationPallet,
Rating
};
// Account, Balance are used in Profile Struct
type AccountOf<T> = <T as frame_system::Config>::AccountId;
type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
// Struct for holding Profile information.
#[derive(Clone, Encode, Decode, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(T))]
pub struct Profile<T: Config> {
pub owner: AccountOf<T>,
pub name: BoundedVec<u8, T::MaxUsernameLen>,
pub interests: BoundedVec<u8, T::MaxInterestsLen>,
pub balance: Option<BalanceOf<T>>,
pub available_hours_per_week: u8,
pub additional_information: Option<BoundedVec<u8, T::MaxAdditionalInformationLen>>,
}
/// Configure the pallet by specifying the parameters and types on which it depends.
#[pallet::config]
pub trait Config: frame_system::Config + pallet_reputation::Config {
/// Because this pallet emits events, it depends on the runtime's definition of an event.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
/// The Currency handler for the Profile pallet.
type Currency: Currency<Self::AccountId>;
/// WeightInfo provider.
type WeightInfo: WeightInfo;
/// A bound on name field of Profile struct.
#[pallet::constant]
type MaxUsernameLen: Get<u32> + MaxEncodedLen + TypeInfo;
/// A bound on interests field of Profile struct.
#[pallet::constant]
type MaxInterestsLen: Get<u32> + MaxEncodedLen + TypeInfo;
/// A bound on additional information for Profile struct.
#[pallet::constant]
type MaxAdditionalInformationLen: Get<u32> + MaxEncodedLen + TypeInfo;
/// A bound on number of completed tasks for Profile.
#[pallet::constant]
type MaxCompletedTasksLen: Get<u32> + MaxEncodedLen + TypeInfo;
}
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::storage]
#[pallet::getter(fn profile_count)]
/// Storage Value that counts the total number of Profiles
pub(super) type ProfileCount<T: Config> = StorageValue<_, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn profiles)]
/// Stores a Profile unique properties in a StorageMap.
pub(super) type Profiles<T: Config> = StorageMap<_, Twox64Concat, T::AccountId, Profile<T>>;
#[pallet::storage]
#[pallet::getter(fn completed_tasks)]
/// Stores list of completed tasks for a profile.
pub(super) type CompletedTasks<T: Config> = StorageMap<_, Twox64Concat, T::AccountId, BoundedVec<T::Hash, T::MaxCompletedTasksLen> >;
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Profile was successfully created.
ProfileCreated { who: T::AccountId },
/// Profile was successfully deleted.
ProfileDeleted { who: T::AccountId },
/// Profile was successfully updated.
ProfileUpdated { who: T::AccountId },
/// A task completed by profile
TaskCompletedByProfile { who: T::AccountId, task: T::Hash },
/// A task archived from completed tasks storage.
TaskArchivedFromProfileStorage { who: T::AccountId, task: T::Hash }
}
// Errors inform users that something went wrong.
#[pallet::error]
pub enum Error<T> {
/// Reached maximum number of profiles.
ProfileCountOverflow,
/// One Account can only create a single profile.
ProfileAlreadyCreated,
/// This Account has not yet created a profile.
NoProfileCreated,
/// Completed task storage reached its bound.
CompletedTasksStorageFull,
}
// Dispatchable functions allows users to interact with the pallet and invoke state changes.
// These functions materialize as "extrinsics", which are often compared to transactions.
// Dispatchable functions must be annotated with a weight and must return a DispatchResult.
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Dispatchable call that enables every new actor to create personal profile in storage.
#[pallet::weight(<T as Config>::WeightInfo::create_profile(0,0))]
pub fn create_profile(origin: OriginFor<T>, username: BoundedVec<u8, T::MaxUsernameLen>, interests: BoundedVec<u8, T::MaxInterestsLen>, available_hours_per_week: u8,
additional_information : Option<BoundedVec<u8, T::MaxAdditionalInformationLen>>) -> DispatchResult {
// Check that the extrinsic was signed and get the signer.
let account = ensure_signed(origin)?;
// Call helper function to generate Profile Struct
let _profile_id = Self::generate_profile(&account, username, interests,
available_hours_per_week, additional_information)?;
// Emit an event.
Self::deposit_event(Event::ProfileCreated{ who:account });
Ok(())
}
/// Dispatchable call that ensures user can update existing personal profile in storage.
#[pallet::weight(<T as Config>::WeightInfo::update_profile(0))]
pub fn update_profile(origin: OriginFor<T>, username: BoundedVec<u8, T::MaxUsernameLen>, interests: BoundedVec<u8, T::MaxInterestsLen>, available_hours_per_week: u8,
additional_information : Option<BoundedVec<u8, T::MaxAdditionalInformationLen>>) -> DispatchResult {
// Check that the extrinsic was signed and get the signer.
let account = ensure_signed(origin)?;
// Since Each account can have one profile, we call into generate profile again
let _profile_id = Self::change_profile(&account, username, interests,
available_hours_per_week, additional_information)?;
// Emit an event.
Self::deposit_event(Event::ProfileUpdated{ who: account });
Ok(())
}
/// Dispatchable call that enables every new actor to delete profile from storage.
#[pallet::weight(<T as Config>::WeightInfo::remove_profile(0))]
pub fn remove_profile(origin: OriginFor<T>) -> DispatchResult {
// Check that the extrinsic was signed and get the signer.
let account = ensure_signed(origin)?;
// Call helper function to delete profile
Self::delete_profile(&account)?;
// Emit an event.
Self::deposit_event(Event::ProfileDeleted{ who : account});
Ok(())
}
}
// ** Helper internal functions ** //
impl<T:Config> Pallet<T> {
// Generates initial Profile.
pub fn generate_profile(owner: &T::AccountId, name: BoundedVec<u8, T::MaxUsernameLen>, interests: BoundedVec<u8, T::MaxInterestsLen>, available_hours_per_week: u8, additional_information: Option<BoundedVec<u8, T::MaxAdditionalInformationLen>>) -> Result<T::Hash, DispatchError> {
// Check if profile already exists for owner
ensure!(!Profiles::<T>::contains_key(&owner), Error::<T>::ProfileAlreadyCreated);
// Get current balance of owner
let balance = T::Currency::free_balance(owner);
// Populate Profile struct
let profile = Profile::<T> {
owner: owner.clone(),
name,
interests,
balance: Some(balance),
available_hours_per_week,
additional_information,
};
// Get hash of profile
let profile_id = T::Hashing::hash_of(&profile);
// Insert profile into HashMap
<Profiles<T>>::insert(owner, profile);
// Initialize completed tasks list with default value.
<CompletedTasks<T>>::insert(owner, BoundedVec::default());
ReputationPallet::<T>::create_reputation_record(owner);
// Increase profile count
let new_count = Self::profile_count().checked_add(1).ok_or(<Error<T>>::ProfileCountOverflow)?;
<ProfileCount<T>>::put(new_count);
Ok(profile_id)
}
// Changes existing profile
pub fn change_profile(owner: &T::AccountId, new_username: BoundedVec<u8, T::MaxUsernameLen>, new_interests: BoundedVec<u8, T::MaxInterestsLen>, new_available_hours_per_week: u8, new_additional_information: Option<BoundedVec<u8, T::MaxAdditionalInformationLen>>) -> Result<T::Hash, DispatchError> {
// Ensure that only owner can update profile
let mut profile = Self::profiles(owner).ok_or(<Error<T>>::NoProfileCreated)?;
// Change interests of owner
profile.change_interests(new_interests);
profile.change_username(new_username);
profile.change_available_hours_per_week(new_available_hours_per_week);
profile.change_additional_information(new_additional_information);
// Get hash of profile
let profile_id = T::Hashing::hash_of(&profile);
// Insert profile into HashMap
<Profiles<T>>::insert(owner, profile);
// Return hash of profileID
Ok(profile_id)
}
// Public function that deletes a user profile
pub fn delete_profile(owner: &T::AccountId) -> Result<(), DispatchError> {
// Ensure that only creator of profile can delete it
Self::profiles(owner).ok_or(<Error<T>>::NoProfileCreated)?;
// Remove profile from storage
<Profiles<T>>::remove(owner);
ReputationPallet::<T>::remove_reputation_record(owner.clone());
// Reduce profile count
let new_count = Self::profile_count().saturating_sub(1);
<ProfileCount<T>>::put(new_count);
Ok(())
}
// Public function that check if user has a profile
pub fn has_profile(owner: &T::AccountId) -> Result<bool, DispatchError> {
// Check if an account has a profile
Self::profiles(owner).ok_or(<Error<T>>::NoProfileCreated)?;
Ok(true)
}
pub fn add_task_to_completed_tasks(owner: &T::AccountId, task: T::Hash) -> Result<(),
DispatchError> {
<CompletedTasks<T>>::mutate(owner, |completed_tasks| -> Result<(), DispatchError> {
if let Some(ct) = completed_tasks {
ct.try_push(task).map_err(|_|
// TODO: Instead of throwing an error, we have to clear up older history.
Error::<T>::CompletedTasksStorageFull.into())
} else {
Ok(())
}
})
}
}
// Change the reputation on a Profile (TODO MVP2: Improve reputation functions)
impl<T:Config> Profile<T> {
pub fn change_interests(&mut self, new_interests: BoundedVec<u8, T::MaxInterestsLen>) {
self.interests = new_interests;
}
pub fn change_username(&mut self, new_username: BoundedVec<u8, T::MaxUsernameLen>) {
self.name = new_username;
}
pub fn change_available_hours_per_week(&mut self, new_available_hours_per_week: u8) {
self.available_hours_per_week = new_available_hours_per_week;
}
pub fn change_additional_information(&mut self, new_additional_information: Option<BoundedVec<u8,
T::MaxAdditionalInformationLen>>) {
self.additional_information = new_additional_information;
}
}
}