-
Notifications
You must be signed in to change notification settings - Fork 110
/
lib.rs
executable file
·2314 lines (1881 loc) · 76.9 KB
/
lib.rs
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::type_complexity)]
#[cfg(feature = "std")]
pub use serde::{Deserialize, Serialize};
use codec::{Codec, Decode, Encode};
pub use frame_support::dispatch::DispatchResult;
use frame_support::traits::{Currency, ExistenceRequirement};
use frame_support::weights::Weight;
use frame_support::{
decl_error, decl_event, decl_module, decl_storage, ensure, traits::Get, Parameter,
};
use frame_system::ensure_signed;
use sp_arithmetic::traits::{BaseArithmetic, One};
pub use sp_io::storage::clear_prefix;
use sp_runtime::traits::{AccountIdConversion, MaybeSerialize, Member};
use sp_runtime::{ModuleId, SaturatedConversion};
use sp_std::collections::btree_map::BTreeMap;
use sp_std::collections::btree_set::BTreeSet;
use sp_std::fmt::Debug;
use sp_std::prelude::*;
use common::membership::MemberOriginValidator;
use common::working_group::WorkingGroupAuthenticator;
mod mock;
mod tests;
mod benchmarking;
/// Type for keeping track of number of posts in a thread
pub type NumberOfPosts = u64;
/// Moderator ID alias for the actor of the system.
pub type ModeratorId<T> = common::ActorId<T>;
/// Forum user ID alias for the member of the system.
pub type ForumUserId<T> = common::MemberId<T>;
type WeightInfoForum<T> = <T as Trait>::WeightInfo;
/// Balance alias for `balances` module.
pub type BalanceOf<T> = <T as balances::Trait>::Balance;
/// Alias for the thread
pub type ThreadOf<T> = Thread<
ForumUserId<T>,
<T as Trait>::CategoryId,
<T as pallet_timestamp::Trait>::Moment,
<T as frame_system::Trait>::Hash,
BalanceOf<T>,
>;
/// Type alias for `ExtendedPostIdObject`
pub type ExtendedPostId<T> =
ExtendedPostIdObject<<T as Trait>::CategoryId, <T as Trait>::ThreadId, <T as Trait>::PostId>;
/// Extended post id representation
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct ExtendedPostIdObject<CategoryId, ThreadId, PostId> {
pub category_id: CategoryId,
pub thread_id: ThreadId,
pub post_id: PostId,
}
type Balances<T> = balances::Module<T>;
/// pallet_forum WeightInfo.
/// Note: This was auto generated through the benchmark CLI using the `--weight-trait` flag
pub trait WeightInfo {
fn create_category(i: u32, j: u32, k: u32) -> Weight;
fn update_category_membership_of_moderator_new() -> Weight;
fn update_category_membership_of_moderator_old() -> Weight;
fn update_category_archival_status_lead(i: u32) -> Weight;
fn update_category_archival_status_moderator(i: u32) -> Weight;
fn update_category_title_lead(i: u32, j: u32) -> Weight;
fn update_category_title_moderator(i: u32, j: u32) -> Weight;
fn update_category_description_lead(i: u32, j: u32) -> Weight;
fn update_category_description_moderator(i: u32, j: u32) -> Weight;
fn delete_category_lead(i: u32) -> Weight;
fn delete_category_moderator(i: u32) -> Weight;
fn create_thread(j: u32, k: u32, i: u32) -> Weight;
fn edit_thread_metadata(i: u32, j: u32) -> Weight;
fn delete_thread(i: u32) -> Weight;
fn move_thread_to_category_lead(i: u32) -> Weight;
fn move_thread_to_category_moderator(i: u32) -> Weight;
fn vote_on_poll(i: u32, j: u32) -> Weight;
fn moderate_thread_lead(i: u32, k: u32) -> Weight;
fn moderate_thread_moderator(i: u32, k: u32) -> Weight;
fn add_post(i: u32, j: u32) -> Weight;
fn react_post(i: u32) -> Weight;
fn edit_post_text(i: u32, j: u32) -> Weight;
fn moderate_post_lead(i: u32, j: u32) -> Weight;
fn moderate_post_moderator(i: u32, j: u32) -> Weight;
fn delete_posts(i: u32, j: u32, k: u32) -> Weight;
fn set_stickied_threads_lead(i: u32, j: u32) -> Weight;
fn set_stickied_threads_moderator(i: u32, j: u32) -> Weight;
}
pub trait Trait:
frame_system::Trait
+ pallet_timestamp::Trait
+ common::membership::MembershipTypes
+ balances::Trait
{
type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>;
type CategoryId: Parameter
+ Member
+ BaseArithmetic
+ Codec
+ Default
+ Copy
+ MaybeSerialize
+ PartialEq
+ From<u64>
+ Into<u64>;
type ThreadId: Parameter
+ Member
+ BaseArithmetic
+ Codec
+ Default
+ Copy
+ MaybeSerialize
+ PartialEq
+ From<u64>
+ Into<u64>;
type PostId: Parameter
+ Member
+ BaseArithmetic
+ Codec
+ Default
+ Copy
+ MaybeSerialize
+ PartialEq
+ From<u64>
+ Into<u64>;
type PostReactionId: Parameter
+ Member
+ BaseArithmetic
+ Codec
+ Default
+ Copy
+ MaybeSerialize
+ PartialEq
+ From<u64>
+ Into<u64>;
/// Base deposit for any thread (note: thread creation also needs a `PostDeposit` since
/// creating a thread means also creating a post)
type ThreadDeposit: Get<Self::Balance>;
/// Deposit needed to create a post
type PostDeposit: Get<Self::Balance>;
/// Maximum depth for nested categories
type MaxCategoryDepth: Get<u64>;
/// Maximum number of blocks before a post can be erased by anyone
type PostLifeTime: Get<Self::BlockNumber>;
/// Type defining the limits for different Storage items in the forum pallet
type MapLimits: StorageLimits;
/// The forum module Id, used to derive the account Id to hold the thread bounty
type ModuleId: Get<ModuleId>;
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
/// Working group pallet integration.
type WorkingGroup: common::working_group::WorkingGroupAuthenticator<Self>;
/// Validates member id and origin combination
type MemberOriginValidator: MemberOriginValidator<
Self::Origin,
common::MemberId<Self>,
Self::AccountId,
>;
fn calculate_hash(text: &[u8]) -> Self::Hash;
}
/// Upper bounds for storage maps and double maps. Needed to prevent potential block exhaustion during deletion, etc.
/// MaxSubcategories, and MaxCategories should be reasonably small because when the category is deleted
/// all of it's subcategories with their threads and posts will be iterated over and deleted.
pub trait StorageLimits {
/// Maximum direct subcategories in a category
type MaxSubcategories: Get<u64>;
/// Maximum moderator count for a single category
type MaxModeratorsForCategory: Get<u64>;
/// Maximum total of all existing categories
type MaxCategories: Get<u64>;
/// Maximum number of poll alternatives
type MaxPollAlternativesNumber: Get<u64>;
}
/// Represents all poll alternative text hashes and vote count for each one
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
pub struct PollAlternative<Hash> {
/// hash of alternative description
pub alternative_text_hash: Hash,
/// Vote count for the alternative
pub vote_count: u32,
}
/// Represents a poll input
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
pub struct PollInput<Timestamp> {
/// description
pub description: Vec<u8>,
/// timestamp of poll end
pub end_time: Timestamp,
/// Alternative polls description
pub poll_alternatives: Vec<Vec<u8>>,
}
/// Represents a poll
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
pub struct Poll<Timestamp, Hash> {
/// hash of description
pub description_hash: Hash,
/// timestamp of poll end
pub end_time: Timestamp,
/// Alternative description and count
pub poll_alternatives: Vec<PollAlternative<Hash>>,
}
/// Represents a thread post
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct Post<ForumUserId, ThreadId, Hash, Balance, BlockNumber> {
/// Id of thread to which this post corresponds.
pub thread_id: ThreadId,
/// Hash of current text
pub text_hash: Hash,
/// Author of post.
pub author_id: ForumUserId,
/// Cleanup pay off
pub cleanup_pay_off: Balance,
/// When it was created or last edited
pub last_edited: BlockNumber,
}
/// Represents a thread
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Default, Clone, PartialEq, Debug, Eq)]
pub struct Thread<ForumUserId, CategoryId, Moment, Hash, Balance> {
/// Category in which this thread lives
pub category_id: CategoryId,
/// Author of post.
pub author_id: ForumUserId,
/// poll description.
pub poll: Option<Poll<Moment, Hash>>,
/// Pay off by deleting
pub cleanup_pay_off: Balance,
/// Number of posts in the thread
pub number_of_posts: NumberOfPosts,
}
/// Represents a category
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Default, Clone, PartialEq, Eq, Debug)]
pub struct Category<CategoryId, ThreadId, Hash> {
/// Title
pub title_hash: Hash,
/// Description
pub description_hash: Hash,
/// Whether category is archived.
pub archived: bool,
/// Number of subcategories, needed for emptiness checks when trying to delete category
pub num_direct_subcategories: u32,
// Number of threads in category, needed for emptiness checks when trying to delete category
pub num_direct_threads: u32,
pub num_direct_moderators: u32,
/// Parent category, if child of another category, otherwise this category is a root category
pub parent_category_id: Option<CategoryId>,
/// Sticky threads list
pub sticky_thread_ids: Vec<ThreadId>,
}
#[derive(Encode, Decode, Clone, PartialEq, Eq)]
pub enum PrivilegedActor<T: Trait> {
Lead,
Moderator(ModeratorId<T>),
}
impl<T: Trait> core::fmt::Debug for PrivilegedActor<T> {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
PrivilegedActor::Lead => write!(formatter, "PrivilegedActor {{ Lead }}"),
PrivilegedActor::Moderator(moderator_id) => {
write!(formatter, "PrivilegedActor {{ {:?} }}", moderator_id)
}
}
}
}
/// Represents a sequence of categories which have child-parent relatioonship
/// where last element is final ancestor, or root, in the context of the category tree.
type CategoryTreePath<CategoryId, ThreadId, Hash> =
Vec<(CategoryId, Category<CategoryId, ThreadId, Hash>)>;
type CategoryTreePathArg<CategoryId, ThreadId, Hash> =
[(CategoryId, Category<CategoryId, ThreadId, Hash>)];
decl_error! {
/// Forum predefined errors
pub enum Error for Module<T: Trait> {
/// Origin doesn't correspond to any lead account
OriginNotForumLead,
/// Forum user id not match its account.
ForumUserIdNotMatchAccount,
/// Moderator id not match its account.
ModeratorIdNotMatchAccount,
// Errors about thread.
/// Thread not authored by the given user.
AccountDoesNotMatchThreadAuthor,
/// Thread does not exist
ThreadDoesNotExist,
/// Moderator can't moderate category containing thread.
ModeratorModerateOriginCategory,
/// Moderator can't moderate destination category.
ModeratorModerateDestinationCategory,
/// Origin is the same as the destination.
ThreadMoveInvalid,
/// Thread not being updated.
ThreadNotBeingUpdated,
/// Not enough balance to create thread
InsufficientBalanceForThreadCreation,
// Errors about post.
/// Post does not exist.
PostDoesNotExist,
/// Account does not match post author.
AccountDoesNotMatchPostAuthor,
/// Not enough balance to post
InsufficientBalanceForPost,
// Errors about category.
/// Category not being updated.
CategoryNotBeingUpdated,
/// Ancestor category immutable, i.e. deleted or archived
AncestorCategoryImmutable,
/// Maximum valid category depth exceeded.
MaxValidCategoryDepthExceeded,
/// Category does not exist.
CategoryDoesNotExist,
/// Provided moderator is not given category moderator
CategoryModeratorDoesNotExist,
/// Category still contains some threads.
CategoryNotEmptyThreads,
/// Category still contains some subcategories.
CategoryNotEmptyCategories,
/// No permissions to delete category.
ModeratorCantDeleteCategory,
/// No permissions to update category.
ModeratorCantUpdateCategory,
/// Duplicates for the stickied thread id collection.
StickiedThreadIdsDuplicates,
// Errors about poll.
/// Poll items number too short.
PollAlternativesTooShort,
/// Poll not exist.
PollNotExist,
/// Poll date setting is wrong.
PollTimeSetting,
/// Poll data committed is wrong.
PollData,
/// Poll data committed after poll expired.
PollCommitExpired,
/// Forum user has already voted.
AlreadyVotedOnPoll,
// Error data migration
/// data migration not done yet.
DataMigrationNotDone,
// Error for limited size
/// Maximum size of storage map exceeded
MapSizeLimit,
/// Category path len should be greater than zero
PathLengthShouldBeGreaterThanZero,
}
}
decl_storage! {
trait Store for Module<T: Trait> as Forum_1_1 {
/// Map category identifier to corresponding category.
pub CategoryById get(fn category_by_id) config(): map hasher(blake2_128_concat) T::CategoryId => Category<T::CategoryId, T::ThreadId, T::Hash>;
/// Category identifier value to be used for the next Category created.
pub NextCategoryId get(fn next_category_id) config(): T::CategoryId;
/// Counter for all existing categories.
pub CategoryCounter get(fn category_counter) config(): T::CategoryId;
/// Map thread identifier to corresponding thread.
pub ThreadById get(fn thread_by_id) config(): double_map hasher(blake2_128_concat)
T::CategoryId, hasher(blake2_128_concat) T::ThreadId => ThreadOf<T>;
/// Thread identifier value to be used for next Thread in threadById.
pub NextThreadId get(fn next_thread_id) config(): T::ThreadId;
/// Post identifier value to be used for for next post created.
pub NextPostId get(fn next_post_id) config(): T::PostId;
/// Moderator set for each Category
pub CategoryByModerator get(fn category_by_moderator) config(): double_map
hasher(blake2_128_concat) T::CategoryId, hasher(blake2_128_concat) ModeratorId<T> => ();
/// If data migration is done, set as configible for unit test purpose
pub DataMigrationDone get(fn data_migration_done) config(): bool;
/// Unique thread poll voters. This private double map prevents double voting.
PollVotes get(fn poll_votes_by_thread_id_by_forum_user_id): double_map
hasher(blake2_128_concat) T::ThreadId,
hasher(blake2_128_concat) ForumUserId<T> => bool;
/// Map post identifier to corresponding post.
pub PostById get(fn post_by_id) config(): double_map hasher(blake2_128_concat) T::ThreadId,
hasher(blake2_128_concat) T::PostId =>
Post<
ForumUserId<T>,
T::ThreadId,
T::Hash,
BalanceOf<T>,
T::BlockNumber
>;
}
}
decl_event!(
pub enum Event<T>
where
<T as Trait>::CategoryId,
ModeratorId = ModeratorId<T>,
<T as Trait>::ThreadId,
<T as Trait>::PostId,
<T as frame_system::Trait>::Hash,
ForumUserId = ForumUserId<T>,
<T as Trait>::PostReactionId,
PrivilegedActor = PrivilegedActor<T>,
ExtendedPostId = ExtendedPostId<T>,
PollInput = PollInput<<T as pallet_timestamp::Trait>::Moment>,
{
/// A category was introduced
CategoryCreated(CategoryId, Option<CategoryId>, Vec<u8>, Vec<u8>),
/// An arhical status of category with given id was updated.
/// The second argument reflects the new archival status of the category.
CategoryArchivalStatusUpdated(CategoryId, bool, PrivilegedActor),
/// A title of category with given id was updated.
/// The second argument reflects the new title hash of the category.
CategoryTitleUpdated(CategoryId, Hash, PrivilegedActor),
/// A discription of category with given id was updated.
/// The second argument reflects the new description hash of the category.
CategoryDescriptionUpdated(CategoryId, Hash, PrivilegedActor),
/// A category was deleted
CategoryDeleted(CategoryId, PrivilegedActor),
/// A thread with given id was created.
/// A third argument reflects the initial post id of the thread.
ThreadCreated(CategoryId, ThreadId, PostId, ForumUserId, Vec<u8>, Vec<u8>, Option<PollInput>),
/// A thread with given id was moderated.
ThreadModerated(ThreadId, Vec<u8>, PrivilegedActor, CategoryId),
/// A thread with given id was updated.
/// The second argument reflects the new archival status of the thread.
ThreadUpdated(ThreadId, bool, PrivilegedActor, CategoryId),
/// A thread metadata given id was updated.
ThreadMetadataUpdated(ThreadId, ForumUserId, CategoryId, Vec<u8>),
/// A thread was deleted.
ThreadDeleted(ThreadId, ForumUserId, CategoryId, bool),
/// A thread was moved to new category
ThreadMoved(ThreadId, CategoryId, PrivilegedActor, CategoryId),
/// Post with given id was created.
PostAdded(PostId, ForumUserId, CategoryId, ThreadId, Vec<u8>, bool),
/// Post with givne id was moderated.
PostModerated(PostId, Vec<u8>, PrivilegedActor, CategoryId, ThreadId),
/// Post with givne id was deleted.
PostDeleted(Vec<u8>, ForumUserId, BTreeMap<ExtendedPostId, bool>),
/// Post with given id had its text updated.
/// The second argument reflects the number of total edits when the text update occurs.
PostTextUpdated(PostId, ForumUserId, CategoryId, ThreadId, Vec<u8>),
/// Thumb up post
PostReacted(ForumUserId, PostId, PostReactionId, CategoryId, ThreadId),
/// Vote on poll
VoteOnPoll(ThreadId, u32, ForumUserId, CategoryId),
/// Sticky thread updated for category
CategoryStickyThreadUpdate(CategoryId, Vec<ThreadId>, PrivilegedActor),
/// An moderator ability to moderate a category and its subcategories updated
CategoryMembershipOfModeratorUpdated(ModeratorId, CategoryId, bool),
}
);
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
/// Predefined errors
type Error = Error<T>;
fn deposit_event() = default;
/// Exports const
/// Deposit needed to create a post
const PostDeposit: BalanceOf<T> = T::PostDeposit::get();
/// Deposit needed to create a thread
const ThreadDeposit: BalanceOf<T> = T::ThreadDeposit::get();
/// Enable a moderator can moderate a category and its sub categories.
///
/// <weight>
///
/// ## Weight
/// `O (1)`
/// - DB:
/// - O(1) doesn't depend on the state or parameters
/// # </weight>
#[weight = WeightInfoForum::<T>::update_category_membership_of_moderator_new()
.max(WeightInfoForum::<T>::update_category_membership_of_moderator_old())]
fn update_category_membership_of_moderator(origin, moderator_id: ModeratorId<T>, category_id: T::CategoryId, new_value: bool) -> DispatchResult {
// Ensure data migration is done
Self::ensure_data_migration_done()?;
clear_prefix(b"Forum ForumUserById");
let account_id = ensure_signed(origin)?;
Self::ensure_can_update_category_membership_of_moderator(account_id, &category_id, &moderator_id, new_value)?;
//
// == MUTATION SAFE ==
//
if new_value {
<CategoryByModerator<T>>::insert(category_id, moderator_id, ());
<CategoryById<T>>::mutate(category_id, |category| category.num_direct_moderators += 1);
} else {
<CategoryByModerator<T>>::remove(category_id, moderator_id);
<CategoryById<T>>::mutate(category_id, |category| category.num_direct_moderators -= 1);
}
// Generate event
Self::deposit_event(RawEvent::CategoryMembershipOfModeratorUpdated(moderator_id, category_id, new_value));
Ok(())
}
/// Add a new category.
///
/// <weight>
///
/// ## Weight
/// `O (W + V + X)` where:
/// - `W` is the category depth
/// - `V` is the length of the category title.
/// - `X` is the length of the category description.
/// - DB:
/// - O(W)
/// # </weight>
#[weight = WeightInfoForum::<T>::create_category(
T::MaxCategoryDepth::get() as u32,
title.len().saturated_into(),
description.len().saturated_into()
)]
fn create_category(origin, parent_category_id: Option<T::CategoryId>, title: Vec<u8>, description: Vec<u8>) -> DispatchResult {
// Ensure data migration is done
Self::ensure_data_migration_done()?;
let account_id = ensure_signed(origin)?;
Self::ensure_can_create_category(account_id, &parent_category_id)?;
//
// == MUTATION SAFE ==
//
// Get next category id
let next_category_id = <NextCategoryId<T>>::get();
// Create new category
let new_category = Category {
title_hash: T::calculate_hash(title.as_slice()),
description_hash: T::calculate_hash(description.as_slice()),
archived: false,
num_direct_subcategories: 0,
num_direct_threads: 0,
num_direct_moderators: 0,
parent_category_id,
sticky_thread_ids: vec![],
};
// Insert category in map
<CategoryById<T>>::mutate(next_category_id, |value| *value = new_category);
// Update other next category id
<NextCategoryId<T>>::mutate(|value| *value += One::one());
// Update total category count
<CategoryCounter<T>>::mutate(|value| *value += One::one());
// If not root, increase parent's subcategories counter
if let Some(tmp_parent_category_id) = parent_category_id {
<CategoryById<T>>::mutate(tmp_parent_category_id, |c| {
c.num_direct_subcategories += 1;
});
}
// Generate event
Self::deposit_event(RawEvent::CategoryCreated(
next_category_id,
parent_category_id,
title,
description
));
Ok(())
}
/// Update archival status
///
/// <weight>
///
/// ## Weight
/// `O (W)` where:
/// - `W` is the category depth
/// - DB:
/// - O(W)
/// # </weight>
#[weight = WeightInfoForum::<T>::update_category_archival_status_lead(
T::MaxCategoryDepth::get() as u32,
).max(WeightInfoForum::<T>::update_category_archival_status_moderator(
T::MaxCategoryDepth::get() as u32,
))]
fn update_category_archival_status(origin, actor: PrivilegedActor<T>, category_id: T::CategoryId, new_archival_status: bool) -> DispatchResult {
// Ensure data migration is done
Self::ensure_data_migration_done()?;
let account_id = ensure_signed(origin)?;
// Ensure actor can update category
let category = Self::ensure_can_moderate_category(&account_id, &actor, &category_id)?;
// No change, invalid transaction
if new_archival_status == category.archived {
return Err(Error::<T>::CategoryNotBeingUpdated.into())
}
//
// == MUTATION SAFE ==
//
// Mutate category, and set possible new change parameters
<CategoryById<T>>::mutate(category_id, |c| c.archived = new_archival_status);
// Generate event
Self::deposit_event(
RawEvent::CategoryArchivalStatusUpdated(category_id, new_archival_status, actor)
);
Ok(())
}
/// Update category title
///
/// <weight>
///
/// ## Weight
/// `O (W + V)` where:
/// - `W` is the category depth
/// - `V` is the length of the category title.
/// - DB:
/// - O(W)
/// # </weight>
#[weight = WeightInfoForum::<T>::update_category_title_lead(
T::MaxCategoryDepth::get() as u32,
title.len().saturated_into(),
).max(WeightInfoForum::<T>::update_category_title_moderator(
T::MaxCategoryDepth::get() as u32,
title.len().saturated_into(),
))]
fn update_category_title(origin, actor: PrivilegedActor<T>, category_id: T::CategoryId, title: Vec<u8>) -> DispatchResult {
// Ensure data migration is done
Self::ensure_data_migration_done()?;
let account_id = ensure_signed(origin)?;
// Ensure actor can update category
let category = Self::ensure_can_moderate_category(&account_id, &actor, &category_id)?;
let title_hash = T::calculate_hash(title.as_slice());
// No change, invalid transaction
if title_hash == category.title_hash {
return Err(Error::<T>::CategoryNotBeingUpdated.into())
}
//
// == MUTATION SAFE ==
//
// Mutate category, and set possible new change parameters
<CategoryById<T>>::mutate(category_id, |c| c.title_hash = title_hash);
// Generate event
Self::deposit_event(
RawEvent::CategoryTitleUpdated(category_id, title_hash, actor)
);
Ok(())
}
/// Update category description
///
/// <weight>
///
/// ## Weight
/// `O (W)` where:
/// - `W` is the category depth
/// - `V` is the length of the category description.
/// - DB:
/// - O(W)
/// # </weight>
#[weight = WeightInfoForum::<T>::update_category_description_lead(
T::MaxCategoryDepth::get() as u32,
description.len().saturated_into(),
).max(WeightInfoForum::<T>::update_category_description_moderator(
T::MaxCategoryDepth::get() as u32,
description.len().saturated_into(),
))]
fn update_category_description(origin, actor: PrivilegedActor<T>, category_id: T::CategoryId, description: Vec<u8>) -> DispatchResult {
// Ensure data migration is done
Self::ensure_data_migration_done()?;
let account_id = ensure_signed(origin)?;
// Ensure actor can update category
let category = Self::ensure_can_moderate_category(&account_id, &actor, &category_id)?;
let description_hash = T::calculate_hash(description.as_slice());
// No change, invalid transaction
if description_hash == category.description_hash {
return Err(Error::<T>::CategoryNotBeingUpdated.into())
}
//
// == MUTATION SAFE ==
//
// Mutate category, and set possible new change parameters
<CategoryById<T>>::mutate(category_id, |c| c.description_hash = description_hash);
// Generate event
Self::deposit_event(
RawEvent::CategoryDescriptionUpdated(category_id, description_hash, actor)
);
Ok(())
}
/// Delete category
///
/// <weight>
///
/// ## Weight
/// `O (W)` where:
/// - `W` is the category depth
/// - DB:
/// - O(W)
/// # </weight>
#[weight = WeightInfoForum::<T>::delete_category_lead(
T::MaxCategoryDepth::get() as u32,
).max(WeightInfoForum::<T>::delete_category_moderator(
T::MaxCategoryDepth::get() as u32,
))]
fn delete_category(origin, actor: PrivilegedActor<T>, category_id: T::CategoryId) -> DispatchResult {
// Ensure data migration is done
Self::ensure_data_migration_done()?;
let account_id = ensure_signed(origin)?;
let category = Self::ensure_can_delete_category(account_id, &actor, &category_id)?;
//
// == MUTATION SAFE ==
//
// Delete category
<CategoryById<T>>::remove(category_id);
if let Some(parent_category_id) = category.parent_category_id {
<CategoryById<T>>::mutate(parent_category_id, |tmp_category| tmp_category.num_direct_subcategories -= 1);
}
// Update total category count
<CategoryCounter<T>>::mutate(|value| *value -= One::one());
// Store the event
Self::deposit_event(RawEvent::CategoryDeleted(category_id, actor));
Ok(())
}
/// Create new thread in category with poll
///
/// <weight>
///
/// ## Weight
/// `O (W + V + X + Y)` where:
/// - `W` is the category depth
/// - `V` is the length of the thread title.
/// - `X` is the length of the thread text.
/// - `Y` is the number of poll alternatives.
/// - DB:
/// - O(W)
/// # </weight>
#[weight = WeightInfoForum::<T>::create_thread(
metadata.len().saturated_into(),
text.len().saturated_into(),
T::MaxCategoryDepth::get() as u32,
)]
fn create_thread(
origin,
forum_user_id: ForumUserId<T>,
category_id: T::CategoryId,
metadata: Vec<u8>,
text: Vec<u8>,
poll_input: Option<PollInput<T::Moment>>,
) -> DispatchResult {
// Ensure data migration is done
Self::ensure_data_migration_done()?;
let account_id = ensure_signed(origin)?;
Self::ensure_can_create_thread(&account_id, &forum_user_id, &category_id)?;
// Ensure poll is valid
if let Some(ref data) = poll_input {
// Check all poll alternatives
Self::ensure_poll_alternatives_length_is_valid(&data.poll_alternatives)?;
// Check poll self information
Self::ensure_poll_input_is_valid(data)?;
}
//
// == MUTATION SAFE ==
//
// Create and add new thread
let new_thread_id = <NextThreadId<T>>::get();
// Reserve cleanup pay off in the thread account plus the cost of creating the
// initial thread
Self::transfer_to_state_cleanup_treasury_account(
T::ThreadDeposit::get() + T::PostDeposit::get(),
new_thread_id,
&account_id
)?;
// Hash poll description and poll alternatives description
let poll = poll_input.clone().map(Self::from_poll_input);
// Build a new thread
let new_thread = Thread {
category_id,
author_id: forum_user_id,
poll,
cleanup_pay_off: T::ThreadDeposit::get(),
number_of_posts: 0,
};
// Store thread
<ThreadById<T>>::mutate(category_id, new_thread_id, |value| {
*value = new_thread.clone()
});
// Add inital post to thread
let initial_post_id = Self::add_new_post(
new_thread_id,
category_id,
&text,
forum_user_id,
true,
);
// Update next thread id
<NextThreadId<T>>::mutate(|n| *n += One::one());
// Update category's thread counter
<CategoryById<T>>::mutate(category_id, |c| c.num_direct_threads += 1);
// Generate event
Self::deposit_event(
RawEvent::ThreadCreated(
category_id,
new_thread_id,
initial_post_id,
forum_user_id,
metadata,
text,
poll_input,
)
);
Ok(())
}
/// Edit thread metadata
///
/// <weight>
///
/// ## Weight
/// `O (W + V)` where:
/// - `W` is the category depth
/// - `V` is the length of the thread metadata.