forked from Joystream/joystream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
1695 lines (1418 loc) · 59.8 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
//! # Working group pallet
//! Working group pallet for the Joystream platform.
//! Contains abstract working group workflow.
//!
//! Exact working group (eg.: forum working group) should create an instance of the Working group module.
//!
//! ## Supported extrinsics
//!
//! - [add_opening](./struct.Module.html#method.add_opening) - Add an opening for a regular worker/lead role.
//! - [apply_on_opening](./struct.Module.html#method.apply_on_opening) - Apply on a regular worker/lead opening.
//! - [fill_opening](./struct.Module.html#method.fill_opening) - Fill opening for regular worker/lead role.
//! - [update_role_account](./struct.Module.html#method.update_role_account) - Update the role account of the regular worker/lead.
//! - [leave_role](./struct.Module.html#method.leave_role) - Leave the role by the active regular worker/lead.
//! - [terminate_role](./struct.Module.html#method.terminate_role) - Terminate the regular worker/lead role.
//! - [slash_stake](./struct.Module.html#method.slash_stake) - Slashes the regular worker/lead stake.
//! - [decrease_stake](./struct.Module.html#method.decrease_stake) - Decreases the regular worker/lead stake and returns the remainder to the worker _role_account_.
//! - [increase_stake](./struct.Module.html#method.increase_stake) - Increases the regular worker/lead stake.
//! - [cancel_opening](./struct.Module.html#method.cancel_opening) - Cancel opening for a regular worker/lead.
//! - [withdraw_application](./struct.Module.html#method.withdraw_application) - Withdraw the regular worker/lead application.
//! - [set_budget](./struct.Module.html#method.set_budget) - Sets the working group budget.
//! - [update_reward_account](./struct.Module.html#method.update_reward_account) - Update the reward account of the regular worker/lead.
//! - [update_reward_amount](./struct.Module.html#method.update_reward_amount) - Update the reward amount of the regular worker/lead.
//! - [set_status_text](./struct.Module.html#method.set_status_text) - Sets the working group status.
//! - [spend_from_budget](./struct.Module.html#method.spend_from_budget) - Spend tokens from the group budget.
//! - [fund_working_group_budget](./struct.Module.html#method.fund_working_group_budget) - Fund the group budget by a member.
// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::unused_unit)]
#![cfg_attr(
not(any(test, feature = "runtime-benchmarks")),
deny(clippy::panic),
deny(clippy::panic_in_result_fn),
deny(clippy::unwrap_used),
deny(clippy::expect_used),
deny(clippy::indexing_slicing),
deny(clippy::integer_arithmetic),
deny(clippy::match_on_vec_items),
deny(clippy::unreachable)
)]
#[cfg(not(any(test, feature = "runtime-benchmarks")))]
#[allow(unused_imports)]
#[macro_use]
extern crate common;
// Do not delete! Cannot be uncommented by default, because of Parity decl_module! issue.
//#![warn(missing_docs)]
// TODO after Olympia-master (Sumer) merge:
// - change module comment
// - benchmark new extrinsics
// - fix `ensure_worker_role_storage_text_is_valid` incorrect cast
pub mod benchmarking;
mod checks;
mod errors;
#[cfg(test)]
mod tests;
mod types;
pub mod weights;
pub use weights::WeightInfo;
use frame_support::traits::{Currency, Get, LockIdentifier};
use frame_support::weights::Weight;
use frame_support::IterableStorageMap;
use frame_support::{decl_event, decl_module, decl_storage, ensure, StorageValue};
use frame_system::{ensure_root, ensure_signed};
use sp_arithmetic::traits::{One, Zero};
use sp_runtime::traits::{Hash, SaturatedConversion, Saturating};
use sp_std::borrow::ToOwned;
use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};
use sp_std::vec::Vec;
pub use errors::Error;
pub use types::*;
use types::{ApplicationInfo, WorkerInfo};
use common::costs::burn_from_usable;
use common::membership::MemberOriginValidator;
use common::to_kb;
use common::{MemberId, StakingAccountValidator};
use frame_support::dispatch::DispatchResult;
use staking_handler::StakingHandler;
type Balances<T> = balances::Pallet<T>;
type WeightInfoWorkingGroup<T, I> = <T as Config<I>>::WeightInfo;
/// The _Group_ main _Config_
pub trait Config<I: Instance = DefaultInstance>:
frame_system::Config + balances::Config + common::membership::MembershipTypes
{
/// _Administration_ event type.
type Event: From<Event<Self, I>> + Into<<Self as frame_system::Config>::Event>;
/// Defines max workers number in the group.
type MaxWorkerNumberLimit: Get<u32>;
/// Stakes and balance locks handler.
type StakingHandler: StakingHandler<
Self::AccountId,
BalanceOf<Self>,
MemberId<Self>,
LockIdentifier,
>;
/// Validates staking account ownership for a member.
type StakingAccountValidator: common::StakingAccountValidator<Self>;
/// Validates member id and origin combination.
type MemberOriginValidator: MemberOriginValidator<Self::Origin, MemberId<Self>, Self::AccountId>;
/// Defines min unstaking period in the group.
type MinUnstakingPeriodLimit: Get<Self::BlockNumber>;
/// Defines the period every worker gets paid in blocks.
type RewardPeriod: Get<u32>;
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
/// Minimum stake required for applying into an opening.
type MinimumApplicationStake: Get<Self::Balance>;
/// Stake needed to create an opening
type LeaderOpeningStake: Get<Self::Balance>;
}
decl_event!(
/// _Group_ events
pub enum Event<T, I = DefaultInstance>
where
OpeningId = OpeningId,
ApplicationId = ApplicationId,
ApplicationIdToWorkerIdMap = BTreeMap<ApplicationId, WorkerId<T>>,
WorkerId = WorkerId<T>,
<T as frame_system::Config>::AccountId,
Balance = BalanceOf<T>,
OpeningType = OpeningType,
StakePolicy = StakePolicy<<T as frame_system::Config>::BlockNumber, BalanceOf<T>>,
ApplyOnOpeningParameters = ApplyOnOpeningParameters<T>,
MemberId = MemberId<T>,
Hash = <T as frame_system::Config>::Hash
{
/// Emits on adding new job opening.
/// Params:
/// - Opening id
/// - Description
/// - Opening Type(Lead or Worker)
/// - Stake Policy for the opening
/// - Reward per block
OpeningAdded(OpeningId, Vec<u8>, OpeningType, StakePolicy, Option<Balance>),
/// Emits on adding the application for the worker opening.
/// Params:
/// - Opening parameteres
/// - Application id
AppliedOnOpening(ApplyOnOpeningParameters, ApplicationId),
/// Emits on filling the job opening.
/// Params:
/// - Worker opening id
/// - Worker application id to the worker id dictionary
/// - Applicationd ids used to fill the opening
OpeningFilled(OpeningId, ApplicationIdToWorkerIdMap, BTreeSet<ApplicationId>),
/// Emits on setting the group leader.
/// Params:
/// - Group worker id.
LeaderSet(WorkerId),
/// Emits on updating the role account of the worker.
/// Params:
/// - Id of the worker.
/// - Role account id of the worker.
WorkerRoleAccountUpdated(WorkerId, AccountId),
/// Emits on un-setting the leader.
LeaderUnset(),
/// Emits on exiting the worker.
/// Params:
/// - worker id.
/// - Rationale.
WorkerExited(WorkerId),
/// Emits when worker started leaving their role.
/// Params:
/// - Worker id.
/// - Rationale.
WorkerStartedLeaving(WorkerId, Option<Vec<u8>>),
/// Emits on terminating the worker.
/// Params:
/// - worker id.
/// - Penalty.
/// - Rationale.
TerminatedWorker(WorkerId, Option<Balance>, Option<Vec<u8>>),
/// Emits on terminating the leader.
/// Params:
/// - leader worker id.
/// - Penalty.
/// - Rationale.
TerminatedLeader(WorkerId, Option<Balance>, Option<Vec<u8>>),
/// Emits on slashing the regular worker/lead stake.
/// Params:
/// - regular worker/lead id.
/// - actual slashed balance.
/// - Requested slashed balance.
/// - Rationale.
StakeSlashed(WorkerId, Balance, Balance, Option<Vec<u8>>),
/// Emits on decreasing the regular worker/lead stake.
/// Params:
/// - regular worker/lead id.
/// - stake delta amount
StakeDecreased(WorkerId, Balance),
/// Emits on increasing the regular worker/lead stake.
/// Params:
/// - regular worker/lead id.
/// - stake delta amount
StakeIncreased(WorkerId, Balance),
/// Emits on withdrawing the application for the regular worker/lead opening.
/// Params:
/// - Job application id
ApplicationWithdrawn(ApplicationId),
/// Emits on canceling the job opening.
/// Params:
/// - Opening id
OpeningCanceled(OpeningId),
/// Emits on setting the budget for the working group.
/// Params:
/// - new budget
BudgetSet(Balance),
/// Emits on updating the reward account of the worker.
/// Params:
/// - Id of the worker.
/// - Reward account id of the worker.
WorkerRewardAccountUpdated(WorkerId, AccountId),
/// Emits on updating the reward amount of the worker.
/// Params:
/// - Id of the worker.
/// - Reward per block
WorkerRewardAmountUpdated(WorkerId, Option<Balance>),
/// Emits on updating the status text of the working group.
/// Params:
/// - status text hash
/// - status text
StatusTextChanged(Hash, Option<Vec<u8>>),
/// Emits on budget from the working group being spent
/// Params:
/// - Receiver Account Id.
/// - Balance spent.
/// - Rationale.
BudgetSpending(AccountId, Balance, Option<Vec<u8>>),
/// Emits on paying the reward.
/// Params:
/// - Id of the worker.
/// - Receiver Account Id.
/// - Reward
/// - Payment type (missed reward or regular one)
RewardPaid(WorkerId, AccountId, Balance, RewardPaymentType),
/// Emits on reaching new missed reward.
/// Params:
/// - Worker ID.
/// - Missed reward (optional). None means 'no missed reward'.
NewMissedRewardLevelReached(WorkerId, Option<Balance>),
/// Fund the working group budget.
/// Params:
/// - Member ID
/// - Amount of balance
/// - Rationale
WorkingGroupBudgetFunded(MemberId, Balance, Vec<u8>),
/// Emits on Lead making a remark message
/// Params:
/// - message
LeadRemarked(Vec<u8>),
/// Emits on Lead making a remark message
/// Params:
/// - worker
/// - message
WorkerRemarked(WorkerId, Vec<u8>),
}
);
decl_storage! { generate_storage_info
trait Store for Module<T: Config<I>, I: Instance=DefaultInstance> as WorkingGroup {
/// Next identifier value for new job opening.
pub NextOpeningId get(fn next_opening_id): OpeningId;
/// Maps identifier to job opening.
pub OpeningById get(fn opening_by_id): map hasher(blake2_128_concat)
OpeningId => OpeningOf<T>;
/// Count of active workers.
pub ActiveWorkerCount get(fn active_worker_count): u32;
/// Maps identifier to worker application on opening.
pub ApplicationById get(fn application_by_id) : map hasher(blake2_128_concat)
ApplicationId => Option<Application<T>>;
/// Next identifier value for new worker application.
pub NextApplicationId get(fn next_application_id) : ApplicationId;
/// Next identifier for a new worker.
pub NextWorkerId get(fn next_worker_id) : WorkerId<T>;
/// Maps identifier to corresponding worker.
pub WorkerById get(fn worker_by_id) : map hasher(blake2_128_concat)
WorkerId<T> => Option<Worker<T>>;
/// Current group lead.
pub CurrentLead get(fn current_lead) : Option<WorkerId<T>>;
/// Budget for the working group.
pub Budget get(fn budget) : BalanceOf<T>;
/// Status text hash.
pub StatusTextHash get(fn status_text_hash) : T::Hash;
}
}
decl_module! {
/// _Working group_ substrate module.
pub struct Module<T: Config<I>, I: Instance=DefaultInstance> for enum Call where origin: T::Origin {
/// Default deposit_event() handler
fn deposit_event() = default;
/// Predefined errors
type Error = Error<T, I>;
/// Exports const
/// Max simultaneous active worker number.
const MaxWorkerNumberLimit: u32 = T::MaxWorkerNumberLimit::get();
/// Defines min unstaking period in the group.
const MinUnstakingPeriodLimit: T::BlockNumber = T::MinUnstakingPeriodLimit::get();
/// Minimum stake required for applying into an opening.
const MinimumApplicationStake: T::Balance = T::MinimumApplicationStake::get();
/// Stake needed to create an opening.
const LeaderOpeningStake: T::Balance = T::LeaderOpeningStake::get();
/// Defines the period every worker gets paid in blocks.
const RewardPeriod: u32 = T::RewardPeriod::get();
/// Staking handler lock id.
const StakingHandlerLockId: LockIdentifier = T::StakingHandler::lock_id();
/// # <weight>
///
/// ## Weight
/// `O (W)` where:
/// - `W` is the number of workers currently present in the `working_group`
/// - DB:
/// - O(W)
/// # </weight>
fn on_initialize() -> Weight {
let leaving_workers = Self::get_workers_with_finished_unstaking_period();
let mut biggest_number_of_processed_workers = leaving_workers.len();
leaving_workers.iter().for_each(|wi| {
Self::remove_worker(
&wi.worker_id,
&wi.worker,
RawEvent::WorkerExited(wi.worker_id)
);
});
if Self::is_reward_block() {
// We count the number of workers that will be processed to not be so pessimistic
// when calculating the weight for this function
let mut count_number_of_workers = 0;
WorkerById::<T, I>::iter().for_each(|(worker_id, worker)| {
Self::reward_worker(&worker_id, &worker);
count_number_of_workers = count_number_of_workers.saturating_add(1);
});
biggest_number_of_processed_workers = biggest_number_of_processed_workers.max(count_number_of_workers);
}
Self::calculate_weight_on_initialize(biggest_number_of_processed_workers.saturated_into())
}
/// Add a job opening for a regular worker/lead role.
/// Require signed leader origin or the root (to add opening for the leader position).
///
/// # <weight>
///
/// ## Weight
/// `O (D)` where:
/// - `D` is the size of `description` in kilobytes
/// - DB:
/// - O(1) doesn't depend on the state or parameters
/// # </weight>
#[weight = WeightInfoWorkingGroup::<T, I>::add_opening(to_kb(description.len().saturated_into()))]
pub fn add_opening(
origin,
description: Vec<u8>,
opening_type: OpeningType,
stake_policy: StakePolicy<T::BlockNumber, BalanceOf<T>>,
reward_per_block: Option<BalanceOf<T>>
){
checks::ensure_origin_for_opening_type::<T, I>(origin.clone(), opening_type)?;
checks::ensure_valid_stake_policy::<T, I>(&stake_policy)?;
checks::ensure_valid_reward_per_block::<T, I>(&reward_per_block)?;
checks::ensure_stake_for_opening_type::<T, I>(origin, opening_type)?;
let new_opening_id = NextOpeningId::<I>::get();
let updated_next_opening_id = new_opening_id
.checked_add(1)
.ok_or(Error::<T, I>::ArithmeticError)?;
//
// == MUTATION SAFE ==
//
let mut creation_stake = BalanceOf::<T>::zero();
if opening_type == OpeningType::Regular {
// Lead must be set for ensure_origin_for_openig_type in the
// case of regular.
let lead = crate::Module::<T, I>::worker_by_id(checks::ensure_lead_is_set::<T, I>()?).ok_or(Error::<T, I>::WorkerDoesNotExist)?;
let current_stake = T::StakingHandler::current_stake(&lead.staking_account_id);
creation_stake = T::LeaderOpeningStake::get();
T::StakingHandler::set_stake(
&lead.staking_account_id,
creation_stake.saturating_add(current_stake)
)?;
}
let hashed_description = T::Hashing::hash(&description);
// Create and add worker opening.
let new_opening = Opening{
opening_type,
created: Self::current_block(),
description_hash: hashed_description,
stake_policy: stake_policy.clone(),
reward_per_block,
creation_stake,
};
OpeningById::<T, I>::insert(new_opening_id, new_opening);
// Update NextOpeningId
NextOpeningId::<I>::mutate(|id| *id = updated_next_opening_id);
Self::deposit_event(RawEvent::OpeningAdded(
new_opening_id,
description,
opening_type,
stake_policy,
reward_per_block,
));
}
/// Apply on a worker opening.
///
/// # <weight>
///
/// ## Weight
/// `O (D)` where:
/// - `D` is the size of `p.description` in kilobytes
/// - DB:
/// - O(1) doesn't depend on the state or parameters
/// # </weight>
#[weight = WeightInfoWorkingGroup::<T, I>::apply_on_opening(
to_kb(p.description.len().saturated_into())
)]
pub fn apply_on_opening(origin, p : ApplyOnOpeningParameters<T>) {
// Ensure the origin of a member with given id.
T::MemberOriginValidator::ensure_member_controller_account_origin(origin, p.member_id)?;
// Ensure job opening exists.
let opening = checks::ensure_opening_exists::<T, I>(p.opening_id)?;
// Ensure that proposed stake is enough for the opening.
checks::ensure_application_stake_match_opening::<T, I>(&opening, &p.stake_parameters)?;
// Checks external conditions for staking.
ensure!(
T::StakingAccountValidator::is_member_staking_account(
&p.member_id,
&p.stake_parameters.staking_account_id
),
Error::<T, I>::InvalidStakingAccountForMember
);
ensure!(
T::StakingHandler::is_account_free_of_conflicting_stakes(
&p.stake_parameters.staking_account_id
),
Error::<T, I>::ConflictStakesOnAccount
);
ensure!(
T::StakingHandler::is_enough_balance_for_stake(
&p.stake_parameters.staking_account_id,
p.stake_parameters.stake
),
Error::<T, I>::InsufficientBalanceToCoverStake
);
// Get id of new worker/lead application
let new_application_id = NextApplicationId::<I>::get();
let updated_next_application_id = new_application_id
.checked_add(1)
.ok_or(Error::<T, I>::ArithmeticError)?;
//
// == MUTATION SAFE ==
//
T::StakingHandler::lock(&p.stake_parameters.staking_account_id, p.stake_parameters.stake);
let hashed_description = T::Hashing::hash(&p.description);
// Make regular/lead application.
let application = Application::<T>::new(
&p.role_account_id,
&p.reward_account_id,
&p.stake_parameters.staking_account_id,
&p.member_id,
p.opening_id,
hashed_description,
);
// Store an application.
ApplicationById::<T, I>::insert(new_application_id, application);
// Update the next application identifier value.
NextApplicationId::<I>::mutate(|id| *id = updated_next_application_id);
// Trigger the event.
Self::deposit_event(RawEvent::AppliedOnOpening(p, new_application_id));
}
/// Fill opening for the regular/lead position.
/// Require signed leader origin or the root (to fill opening for the leader position).
/// # <weight>
///
/// ## Weight
/// `O (A)` where:
/// - `A` is the length of `successful_application_ids`
/// - DB:
/// - O(A)
/// # </weight>
#[weight =
WeightInfoWorkingGroup::<T, I>::fill_opening_worker(
successful_application_ids.len().saturated_into()
)
.max(WeightInfoWorkingGroup::<T, I>::fill_opening_lead())
]
pub fn fill_opening(
origin,
opening_id: OpeningId,
successful_application_ids: BTreeSet<ApplicationId>,
) {
// Ensure job opening exists.
let opening = checks::ensure_opening_exists::<T, I>(opening_id)?;
checks::ensure_origin_for_opening_type::<T, I>(origin, opening.opening_type)?;
// Ensure we're not exceeding the maximum worker number.
let potential_worker_number = Self::active_worker_count()
.checked_add(successful_application_ids.len() as u32)
.ok_or(Error::<T, I>::ArithmeticError)?;
ensure!(
potential_worker_number <= T::MaxWorkerNumberLimit::get(),
Error::<T, I>::MaxActiveWorkerNumberExceeded
);
// Cannot hire a lead when another leader exists.
if matches!(opening.opening_type, OpeningType::Leader) {
ensure!(
!<CurrentLead<T,I>>::exists(),
Error::<T, I>::CannotHireLeaderWhenLeaderExists
);
}
let checked_applications_info =
checks::ensure_succesful_applications_exist::<T, I>(&successful_application_ids)?;
// Check that all applications are for the intended opening
ensure!(
checked_applications_info.iter()
.all(|info| info.application.opening_id == opening_id),
Error::<T, I>::ApplicationsNotForOpening
);
// Check for a single application for a leader.
if matches!(opening.opening_type, OpeningType::Leader) {
ensure!(
successful_application_ids.len() == 1,
Error::<T, I>::CannotHireMultipleLeaders
);
}
//
// == MUTATION SAFE ==
//
if opening.opening_type == OpeningType::Regular {
// Lead must be set for ensure_origin_for_openig_type in the
// case of regular.
let lead = crate::Module::<T, I>::worker_by_id(checks::ensure_lead_is_set::<T, I>()?).ok_or(Error::<T, I>::WorkerDoesNotExist)?;
let current_stake = T::StakingHandler::current_stake(&lead.staking_account_id);
T::StakingHandler::set_stake(
&lead.staking_account_id,
current_stake.saturating_sub(opening.creation_stake)
)?;
}
// Process successful applications
let application_id_to_worker_id = Self::fulfill_successful_applications(
&opening,
checked_applications_info
);
// Remove the opening.
<OpeningById::<T, I>>::remove(opening_id);
// Trigger event
Self::deposit_event(RawEvent::OpeningFilled(
opening_id,
application_id_to_worker_id,
successful_application_ids
));
}
/// Update the associated role account of the active regular worker/lead.
///
/// # <weight>
///
/// ## Weight
/// `O (1)`
/// - DB:
/// - O(1) doesn't depend on the state or parameters
/// # </weight>
#[weight = WeightInfoWorkingGroup::<T, I>::update_role_account()]
pub fn update_role_account(
origin,
worker_id: WorkerId<T>,
new_role_account_id: T::AccountId
) {
// Ensuring worker actually exists
let worker = checks::ensure_worker_exists::<T, I>(&worker_id)?;
// Ensure the origin of a member with given id.
T::MemberOriginValidator::ensure_member_controller_account_origin(origin, worker.member_id)?;
// Ensure the worker is active.
ensure!(!worker.is_leaving(), Error::<T, I>::WorkerIsLeaving);
//
// == MUTATION SAFE ==
//
// Update role account
WorkerById::<T, I>::insert(worker_id, Worker::<T> {
role_account_id: new_role_account_id.clone(),
..worker
});
// Trigger event
Self::deposit_event(RawEvent::WorkerRoleAccountUpdated(worker_id, new_role_account_id));
}
/// Leave the role by the active worker.
/// # <weight>
///
/// ## Weight
/// `O (R)` where:
/// - `R` is the size of `rationale` in kilobytes
/// - DB:
/// - O(1) doesn't depend on the state or parameters
/// # </weight>
#[weight = Module::<T, I>::leave_role_weight(rationale)]
pub fn leave_role(
origin,
worker_id: WorkerId<T>,
rationale: Option<Vec<u8>>
) {
// Ensure there is a signer which matches role account of worker corresponding to provided id.
let worker = checks::ensure_worker_signed::<T, I>(origin, &worker_id)?;
// Ensure the worker is active.
ensure!(!worker.is_leaving(), Error::<T, I>::WorkerIsLeaving);
//
// == MUTATION SAFE ==
//
WorkerById::<T, I>::insert(worker_id, Worker::<T> {
started_leaving_at: Some(Self::current_block()),
..worker
});
// Trigger event
Self::deposit_event(RawEvent::WorkerStartedLeaving(worker_id, rationale));
}
/// Terminate the active worker by the lead.
/// Requires signed leader origin or the root (to terminate the leader role).
/// # <weight>
///
/// ## Weight
/// `O (P)` where:
/// - `P` is the size `penalty.slashing_text` in kilobytes
/// - DB:
/// - O(1) doesn't depend on the state or parameters
/// # </weight>
#[weight = Module::<T, I>::terminate_role_weight(rationale)]
pub fn terminate_role(
origin,
worker_id: WorkerId<T>,
penalty: Option<BalanceOf<T>>,
rationale: Option<Vec<u8>>,
) {
// Ensure lead is set or it is the council terminating the leader.
let is_sudo = checks::ensure_origin_for_worker_operation::<T,I>(origin, worker_id)?;
// Ensuring worker actually exists.
let worker = checks::ensure_worker_exists::<T,I>(&worker_id)?;
//
// == MUTATION SAFE ==
//
if let Some(penalty) = penalty {
Self::slash(worker_id, &worker.staking_account_id, penalty, rationale.clone());
}
// Trigger the event
let event = if is_sudo {
RawEvent::TerminatedLeader(worker_id, penalty, rationale)
} else {
RawEvent::TerminatedWorker(worker_id, penalty, rationale)
};
Self::remove_worker(&worker_id, &worker, event);
}
/// Slashes the regular worker stake, demands a leader origin. No limits, no actions on zero stake.
/// If slashing balance greater than the existing stake - stake is slashed to zero.
/// Requires signed leader origin or the root (to slash the leader stake).
/// # <weight>
///
/// ## Weight
/// `O (P)` where:
/// - `P` is the size of `penality.slashing_text` in kilobytes
/// - DB:
/// - O(1) doesn't depend on the state or parameters
/// # </weight>
#[weight = Module::<T, I>::slash_stake_weight(rationale)]
pub fn slash_stake(
origin,
worker_id: WorkerId<T>,
penalty: BalanceOf<T>,
rationale: Option<Vec<u8>>
) {
// Ensure lead is set or it is the council slashing the leader.
checks::ensure_origin_for_worker_operation::<T,I>(origin, worker_id)?;
// Ensuring worker actually exists.
let worker = checks::ensure_worker_exists::<T,I>(&worker_id)?;
ensure!(
penalty != <BalanceOf<T>>::zero(),
Error::<T, I>::StakeBalanceCannotBeZero
);
//
// == MUTATION SAFE ==
//
Self::slash(worker_id, &worker.staking_account_id, penalty, rationale)
}
/// Decreases the regular worker/lead stake and returns the remainder to the
/// worker staking_account_id. Can be decreased to zero, no actions on zero stake.
/// Accepts the stake amount to decrease.
/// Requires signed leader origin or the root (to decrease the leader stake).
///
/// # <weight>
///
/// ## Weight
/// `O (1)`
/// - DB:
/// - O(1) doesn't depend on the state or parameters
/// # </weight>
#[weight = WeightInfoWorkingGroup::<T, I>::decrease_stake()]
pub fn decrease_stake(origin, worker_id: WorkerId<T>, stake_balance_delta: BalanceOf<T>) {
// Ensure lead is set or it is the council decreasing the leader's stake.
checks::ensure_origin_for_worker_operation::<T,I>(origin, worker_id)?;
let worker = checks::ensure_worker_exists::<T,I>(&worker_id)?;
// Ensure the worker is active.
ensure!(!worker.is_leaving(), Error::<T, I>::WorkerIsLeaving);
// Ensure non-zero stake delta.
ensure!(
stake_balance_delta != <BalanceOf<T>>::zero(),
Error::<T, I>::StakeBalanceCannotBeZero
);
// Ensure enough stake to decrease.
let current_stake = T::StakingHandler::current_stake(&worker.staking_account_id);
ensure!(
current_stake > stake_balance_delta,
Error::<T, I>::CannotDecreaseStakeDeltaGreaterThanStake
);
//
// == MUTATION SAFE ==
//
let current_stake = T::StakingHandler::current_stake(&worker.staking_account_id);
// Cannot possibly overflow because of the already performed check.
let new_stake = current_stake.saturating_sub(stake_balance_delta);
// This external module call both checks and mutates the state.
T::StakingHandler::set_stake(&worker.staking_account_id, new_stake)?;
Self::deposit_event(RawEvent::StakeDecreased(worker_id, stake_balance_delta));
}
/// Increases the regular worker/lead stake, demands a worker origin.
/// Locks tokens from the worker staking_account_id equal to new stake. No limits on the stake.
///
/// # <weight>
///
/// ## Weight
/// `O (1)`
/// - DB:
/// - O(1) doesn't depend on the state or parameters
/// # </weight>
#[weight = WeightInfoWorkingGroup::<T, I>::increase_stake()]
pub fn increase_stake(origin, worker_id: WorkerId<T>, stake_balance_delta: BalanceOf<T>) {
// Checks worker origin and worker existence.
let worker = checks::ensure_worker_signed::<T, I>(origin, &worker_id)?;
// Ensure the worker is active.
ensure!(!worker.is_leaving(), Error::<T, I>::WorkerIsLeaving);
ensure!(
stake_balance_delta != <BalanceOf<T>>::zero(),
Error::<T, I>::StakeBalanceCannotBeZero
);
ensure!(
T::StakingHandler::is_enough_balance_for_stake(
&worker.staking_account_id,
stake_balance_delta
),
Error::<T, I>::InsufficientBalanceToCoverStake
);
//
// == MUTATION SAFE ==
//
let current_stake = T::StakingHandler::current_stake(&worker.staking_account_id);
let new_stake = current_stake.saturating_add(stake_balance_delta);
// This external module call both checks and mutates the state.
T::StakingHandler::set_stake(&worker.staking_account_id, new_stake)?;
Self::deposit_event(RawEvent::StakeIncreased(worker_id, stake_balance_delta));
}
/// Withdraw the worker application. Can be done by the worker only.
///
/// # <weight>
///
/// ## Weight
/// `O (1)`
/// - DB:
/// - O(1) doesn't depend on the state or parameters
/// # </weight>
#[weight = WeightInfoWorkingGroup::<T, I>::withdraw_application()]
pub fn withdraw_application(
origin,
application_id: ApplicationId
) {
// Ensuring worker application actually exists
let application_info = checks::ensure_application_exists::<T, I>(&application_id)?;
// Ensure that it is signed
let signer_account = ensure_signed(origin)?;
// Ensure that signer is applicant role account
ensure!(
signer_account == application_info.application.role_account_id,
Error::<T, I>::OriginIsNotApplicant
);
//
// == MUTATION SAFE ==
//
T::StakingHandler::unlock(&application_info.application.staking_account_id);
// Remove an application.
<ApplicationById<T, I>>::remove(application_info.application_id);
// Trigger event
Self::deposit_event(RawEvent::ApplicationWithdrawn(application_id));
}
/// Cancel an opening for the regular worker/lead position.
/// Require signed leader origin or the root (to cancel opening for the leader position).
///
/// # <weight>
///
/// ## Weight
/// `O (1)`
/// - DB:
/// - O(1) doesn't depend on the state or parameters
/// # </weight>
#[weight = WeightInfoWorkingGroup::<T, I>::cancel_opening()]
pub fn cancel_opening(
origin,
opening_id: OpeningId,
) {
// Ensure job opening exists.
let opening = checks::ensure_opening_exists::<T, I>(opening_id)?;
checks::ensure_origin_for_opening_type::<T, I>(origin, opening.opening_type)?;
//
// == MUTATION SAFE ==
//
// Remove opening stake
if opening.opening_type == OpeningType::Regular {
// Lead must be set for ensure_origin_for_openig_type in the
// case of regular.
let lead = crate::Module::<T, I>::worker_by_id(checks::ensure_lead_is_set::<T, I>()?).ok_or(Error::<T, I>::WorkerDoesNotExist)?;
let current_stake = T::StakingHandler::current_stake(&lead.staking_account_id);
T::StakingHandler::set_stake(
&lead.staking_account_id,
current_stake.saturating_sub(opening.creation_stake)
)?;
}
// Remove the opening.
<OpeningById::<T, I>>::remove(opening_id);
// Trigger event
Self::deposit_event(RawEvent::OpeningCanceled(opening_id));
}
/// Sets a new budget for the working group.
/// Requires root origin.
///
/// # <weight>
///
/// ## Weight
/// `O (1)`
/// - DB:
/// - O(1) doesn't depend on the state or parameters
/// # </weight>
#[weight = WeightInfoWorkingGroup::<T, I>::set_budget()]
pub fn set_budget(
origin,
new_budget: BalanceOf<T>,
) {
ensure_root(origin)?;
//