forked from poa-box/POP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskManager.sol
More file actions
1034 lines (904 loc) · 38.6 KB
/
TaskManager.sol
File metadata and controls
1034 lines (904 loc) · 38.6 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
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
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.20;
/*──────── OpenZeppelin Upgradeables ────────*/
import {Initializable} from "@openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol";
import {ContextUpgradeable} from "@openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/*────────── Internal Libraries ──────────*/
import {TaskPerm} from "./libs/TaskPerm.sol";
import {BudgetLib} from "./libs/BudgetLib.sol";
import {ValidationLib} from "./libs/ValidationLib.sol";
/*────────── External Hats interface ──────────*/
import {IHats} from "lib/hats-protocol/src/Interfaces/IHats.sol";
import {HatManager} from "./libs/HatManager.sol";
/*────────── External Interfaces ──────────*/
interface IParticipationToken is IERC20 {
function mint(address, uint256) external;
}
/*────────────────────── Contract ───────────────────────*/
contract TaskManager is Initializable, ContextUpgradeable {
using SafeERC20 for IERC20;
using BudgetLib for BudgetLib.Budget;
using ValidationLib for address;
using ValidationLib for bytes;
/*──────── Errors ───────*/
error NotFound();
error BadStatus();
error NotCreator();
error NotClaimer();
error NotExecutor();
error NotDeployer();
error Unauthorized();
error NotApplicant();
error AlreadyApplied();
error RequiresApplication();
error NoApplicationRequired();
error InvalidIndex();
error SelfReviewNotAllowed();
error ArrayLengthMismatch();
error EmptyBatch();
/*──────── Constants ─────*/
bytes4 public constant MODULE_ID = 0x54534b32; // "TSK2"
/*──────── Enums ─────*/
enum HatType {
CREATOR
}
enum ConfigKey {
EXECUTOR,
CREATOR_HAT_ALLOWED,
ROLE_PERM,
PROJECT_ROLE_PERM,
BOUNTY_CAP,
PROJECT_MANAGER,
PROJECT_CAP
}
/*──────── Data Types ────*/
enum Status {
UNCLAIMED,
CLAIMED,
SUBMITTED,
COMPLETED,
CANCELLED
}
struct Task {
bytes32 projectId; // slot 1: full 32 bytes
uint96 payout; // slot 2: 12 bytes (supports up to 7e28, well over 1e24 cap), voting token payout
address claimer; // slot 2: 20 bytes (total 32 bytes in slot 2)
uint96 bountyPayout; // slot 3: 12 bytes, additional payout in bounty currency
bool requiresApplication; // slot 3: 1 byte
Status status; // slot 3: 1 byte (enum fits in 1 byte)
address bountyToken; // slot 4: 20 bytes (optimized packing: small fields grouped together)
}
struct Project {
mapping(address => bool) managers; // slot 0: mapping (full slot)
uint128 cap; // slot 1: 16 bytes — PT cap (0 = unlimited, minted tokens)
uint128 spent; // slot 1: 16 bytes — PT committed spend
bool exists; // slot 2: 1 byte (separate slot for cleaner access)
// Bounty budgets use BudgetLib semantics: cap 0 = DISABLED, UNLIMITED = no limit
mapping(address => BudgetLib.Budget) bountyBudgets; // per-token ERC-20 budget
}
/*──────── Bootstrap Config Structs ───────*/
struct BootstrapProjectConfig {
bytes title;
bytes32 metadataHash;
uint256 cap;
address[] managers;
uint256[] createHats;
uint256[] claimHats;
uint256[] reviewHats;
uint256[] assignHats;
address[] bountyTokens;
uint256[] bountyCaps;
}
struct BootstrapTaskConfig {
uint8 projectIndex; // References project in same batch (0 for first project)
uint256 payout;
bytes title;
bytes32 metadataHash;
address bountyToken;
uint256 bountyPayout;
bool requiresApplication;
}
struct CreateTaskInput {
uint256 payout;
bytes title;
bytes32 metadataHash;
address bountyToken;
uint256 bountyPayout;
bool requiresApplication;
}
/*──────── Storage (ERC-7201) ───────*/
struct Layout {
mapping(bytes32 => Project) _projects;
mapping(uint256 => Task) _tasks;
IHats hats;
IParticipationToken token;
uint256[] creatorHatIds; // enumeration array for creator hats
uint48 nextTaskId;
uint48 nextProjectId;
address executor; // 20 bytes + 2*6 bytes = 32 bytes (one slot)
mapping(uint256 => uint8) rolePermGlobal; // hat ID => permission mask
mapping(bytes32 => mapping(uint256 => uint8)) rolePermProj; // project => hat ID => permission mask
uint256[] permissionHatIds; // enumeration array for hats with permissions
mapping(uint256 => address[]) taskApplicants; // task ID => array of applicants
mapping(uint256 => mapping(address => bytes32)) taskApplications; // task ID => applicant => application hash
address deployer; // OrgDeployer address for bootstrap operations
mapping(uint256 => uint256) projectPermHatRefCount; // hat ID => number of projects with non-zero project mask
}
bytes32 private constant _STORAGE_SLOT = keccak256("poa.taskmanager.storage");
function _layout() private pure returns (Layout storage s) {
bytes32 slot = _STORAGE_SLOT;
assembly {
s.slot := slot
}
}
/*──────── Events ───────*/
event HatSet(HatType hatType, uint256 hat, bool allowed);
event ProjectCreated(bytes32 indexed id, bytes title, bytes32 metadataHash, uint256 cap);
event ProjectCapUpdated(bytes32 indexed id, uint256 oldCap, uint256 newCap);
event ProjectManagerUpdated(bytes32 indexed id, address indexed manager, bool isManager);
event ProjectDeleted(bytes32 indexed id);
event ProjectRolePermSet(bytes32 indexed id, uint256 indexed hatId, uint8 mask);
event BountyCapSet(bytes32 indexed projectId, address indexed token, uint256 oldCap, uint256 newCap);
event TaskCreated(
uint256 indexed id,
bytes32 indexed project,
uint256 payout,
address bountyToken,
uint256 bountyPayout,
bool requiresApplication,
bytes title,
bytes32 metadataHash
);
event TaskUpdated(
uint256 indexed id, uint256 payout, address bountyToken, uint256 bountyPayout, bytes title, bytes32 metadataHash
);
event TaskSubmitted(uint256 indexed id, bytes32 submissionHash);
event TaskClaimed(uint256 indexed id, address indexed claimer);
event TaskAssigned(uint256 indexed id, address indexed assignee, address indexed assigner);
event TaskCompleted(uint256 indexed id, address indexed completer);
event TaskCancelled(uint256 indexed id, address indexed canceller);
event TaskRejected(uint256 indexed id, address indexed rejector, bytes32 rejectionHash);
event TaskApplicationSubmitted(uint256 indexed id, address indexed applicant, bytes32 applicationHash);
event TaskApplicationApproved(uint256 indexed id, address indexed applicant, address indexed approver);
event ExecutorUpdated(address newExecutor);
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/*──────── Initialiser ───────*/
function initialize(
address tokenAddress,
address hatsAddress,
uint256[] calldata creatorHats,
address executorAddress,
address deployerAddress
) external initializer {
tokenAddress.requireNonZeroAddress();
hatsAddress.requireNonZeroAddress();
executorAddress.requireNonZeroAddress();
__Context_init();
Layout storage l = _layout();
l.token = IParticipationToken(tokenAddress);
l.hats = IHats(hatsAddress);
l.executor = executorAddress;
l.deployer = deployerAddress; // Can be address(0) if bootstrap not needed
// Initialize creator hat arrays using HatManager
for (uint256 i; i < creatorHats.length;) {
HatManager.setHatInArray(l.creatorHatIds, creatorHats[i], true);
emit HatSet(HatType.CREATOR, creatorHats[i], true);
unchecked {
++i;
}
}
emit ExecutorUpdated(executorAddress);
}
/*──────── Internal Check Functions ─────*/
function _requireCreator() internal view {
Layout storage l = _layout();
address s = _msgSender();
if (!_hasCreatorHat(s) && s != l.executor) revert NotCreator();
}
function _requireProjectExists(bytes32 pid) internal view {
if (!_layout()._projects[pid].exists) revert NotFound();
}
function _requireExecutor() internal view {
if (_msgSender() != _layout().executor) revert NotExecutor();
}
function _requireCanCreate(bytes32 pid) internal view {
_checkPerm(pid, TaskPerm.CREATE);
}
function _requireCanClaim(uint256 tid) internal view {
_checkPerm(_layout()._tasks[tid].projectId, TaskPerm.CLAIM);
}
function _requireCanAssign(bytes32 pid) internal view {
_checkPerm(pid, TaskPerm.ASSIGN);
}
/*──────── Project Logic ─────*/
/**
* @notice Create a new project
* @dev Uses BootstrapProjectConfig struct to avoid stack-too-deep with 10+ calldata arrays.
* The caller (msg.sender) is automatically added as a project manager.
* @param p Project configuration (title, metadataHash, cap, managers, hat arrays, bounty budgets)
*/
function createProject(BootstrapProjectConfig calldata p) external returns (bytes32 projectId) {
_requireCreator();
projectId = _createProjectCore(
p.title,
p.metadataHash,
p.cap,
p.managers,
p.createHats,
p.claimHats,
p.reviewHats,
p.assignHats,
_msgSender()
);
_initBountyBudgets(projectId, p.bountyTokens, p.bountyCaps);
}
function _createProjectCore(
bytes calldata title,
bytes32 metadataHash,
uint256 cap,
address[] calldata managers,
uint256[] calldata createHats,
uint256[] calldata claimHats,
uint256[] calldata reviewHats,
uint256[] calldata assignHats,
address defaultManager
) internal returns (bytes32 projectId) {
ValidationLib.requireValidTitle(title);
ValidationLib.requireValidCapAmount(cap);
Layout storage l = _layout();
projectId = bytes32(uint256(l.nextProjectId++));
Project storage p = l._projects[projectId];
p.cap = uint128(cap);
p.exists = true;
emit ProjectCreated(projectId, title, metadataHash, cap);
/* managers */
if (defaultManager != address(0)) {
p.managers[defaultManager] = true;
emit ProjectManagerUpdated(projectId, defaultManager, true);
}
for (uint256 i; i < managers.length;) {
managers[i].requireNonZeroAddress();
p.managers[managers[i]] = true;
emit ProjectManagerUpdated(projectId, managers[i], true);
unchecked {
++i;
}
}
/* hat-permission matrix */
_setBatchHatPerm(projectId, createHats, TaskPerm.CREATE);
_setBatchHatPerm(projectId, claimHats, TaskPerm.CLAIM);
_setBatchHatPerm(projectId, reviewHats, TaskPerm.REVIEW);
_setBatchHatPerm(projectId, assignHats, TaskPerm.ASSIGN);
}
function _initBountyBudgets(bytes32 projectId, address[] calldata bountyTokens, uint256[] calldata bountyCaps)
internal
{
if (bountyTokens.length != bountyCaps.length) revert ArrayLengthMismatch();
if (bountyTokens.length == 0) return;
Project storage p = _layout()._projects[projectId];
for (uint256 i; i < bountyTokens.length;) {
bountyTokens[i].requireNonZeroAddress();
ValidationLib.requireValidCapAmount(bountyCaps[i]);
p.bountyBudgets[bountyTokens[i]].cap = uint128(bountyCaps[i]);
emit BountyCapSet(projectId, bountyTokens[i], 0, bountyCaps[i]);
unchecked {
++i;
}
}
}
function deleteProject(bytes32 pid) external {
_requireCreator();
Layout storage l = _layout();
Project storage p = l._projects[pid];
if (!p.exists) revert NotFound();
// Decrement ref counts for hats that had project-specific permissions.
// Iterate a snapshot of permissionHatIds since _syncPermissionHat may modify it.
uint256 len = l.permissionHatIds.length;
uint256[] memory snapshot = new uint256[](len);
for (uint256 i; i < len;) {
snapshot[i] = l.permissionHatIds[i];
unchecked {
++i;
}
}
for (uint256 i; i < len;) {
uint256 hatId = snapshot[i];
if (l.rolePermProj[pid][hatId] != 0) {
_updateProjectPermRefCount(l, hatId, l.rolePermProj[pid][hatId], 0);
delete l.rolePermProj[pid][hatId];
_syncPermissionHat(hatId);
}
unchecked {
++i;
}
}
delete l._projects[pid];
emit ProjectDeleted(pid);
}
/**
* @notice Bootstrap initial projects and tasks during org deployment
* @dev Only callable by deployer (OrgDeployer) during bootstrap phase
* @param projects Array of project configurations to create
* @param tasks Array of task configurations (reference projects by index)
* @return projectIds Array of created project IDs
*/
function bootstrapProjectsAndTasks(BootstrapProjectConfig[] calldata projects, BootstrapTaskConfig[] calldata tasks)
external
returns (bytes32[] memory projectIds)
{
Layout storage l = _layout();
if (_msgSender() != l.deployer) revert NotDeployer();
projectIds = new bytes32[](projects.length);
// Create all projects (executor is not auto-added as manager, use managers array)
for (uint256 i; i < projects.length;) {
projectIds[i] = _createProjectCore(
projects[i].title,
projects[i].metadataHash,
projects[i].cap,
projects[i].managers,
projects[i].createHats,
projects[i].claimHats,
projects[i].reviewHats,
projects[i].assignHats,
address(0) // No default manager - use explicit managers array
);
_initBountyBudgets(projectIds[i], projects[i].bountyTokens, projects[i].bountyCaps);
unchecked {
++i;
}
}
// Create all tasks referencing projects by index
for (uint256 i; i < tasks.length;) {
if (tasks[i].projectIndex >= projects.length) revert InvalidIndex();
bytes32 pid = projectIds[tasks[i].projectIndex];
_createTask(
tasks[i].payout,
tasks[i].title,
tasks[i].metadataHash,
pid,
tasks[i].requiresApplication,
tasks[i].bountyToken,
tasks[i].bountyPayout
);
unchecked {
++i;
}
}
}
/**
* @notice Clear the deployer address after bootstrap phase is complete
* @dev Only callable by deployer. Prevents future bootstrap calls for defense-in-depth.
* Should be called by OrgDeployer at the end of org deployment.
*/
function clearDeployer() external {
Layout storage l = _layout();
if (_msgSender() != l.deployer) revert NotDeployer();
l.deployer = address(0);
}
/*──────── Task Logic ───────*/
function createTask(
uint256 payout,
bytes calldata title,
bytes32 metadataHash,
bytes32 pid,
address bountyToken,
uint256 bountyPayout,
bool requiresApplication
) external {
_requireCanCreate(pid);
_createTask(payout, title, metadataHash, pid, requiresApplication, bountyToken, bountyPayout);
}
/**
* @notice Create multiple tasks in a single project in one transaction.
* @dev Permission is checked once for the whole batch; project existence and
* per-task validation still run inside `_createTask`. All-or-nothing:
* any failure reverts the entire call.
* @param pid Project ID all tasks will be created under.
* @param tasks Array of task configurations, in the order they should be created.
* @return taskIds IDs of the newly-created tasks, in the same order as `tasks`.
*/
function createTasksBatch(bytes32 pid, CreateTaskInput[] calldata tasks)
external
returns (uint256[] memory taskIds)
{
if (tasks.length == 0) revert EmptyBatch();
_requireCanCreate(pid);
uint256 len = tasks.length;
taskIds = new uint256[](len);
for (uint256 i; i < len;) {
CreateTaskInput calldata t = tasks[i];
taskIds[i] = _createTask(
t.payout, t.title, t.metadataHash, pid, t.requiresApplication, t.bountyToken, t.bountyPayout
);
unchecked {
++i;
}
}
}
function _createTask(
uint256 payout,
bytes calldata title,
bytes32 metadataHash,
bytes32 pid,
bool requiresApplication,
address bountyToken,
uint256 bountyPayout
) internal returns (uint48 id) {
Layout storage l = _layout();
ValidationLib.requireValidTitle(title);
ValidationLib.requireValidPayout96(payout);
ValidationLib.requireValidBountyConfig(bountyToken, bountyPayout);
Project storage p = l._projects[pid];
if (!p.exists) revert NotFound();
// Update participation token budget (PT cap: 0 = unlimited, since PT is minted)
uint256 newSpent = p.spent + payout;
if (newSpent > type(uint128).max) revert BudgetLib.BudgetExceeded();
if (p.cap != 0 && newSpent > p.cap) revert BudgetLib.BudgetExceeded();
p.spent = uint128(newSpent);
// Check bounty budget (BudgetLib: cap 0 = DISABLED, must be explicitly enabled)
if (bountyToken != address(0) && bountyPayout > 0) {
BudgetLib.Budget storage bb = p.bountyBudgets[bountyToken];
bb.addSpent(bountyPayout);
}
id = l.nextTaskId++;
l._tasks[id] = Task(
pid, uint96(payout), address(0), uint96(bountyPayout), requiresApplication, Status.UNCLAIMED, bountyToken
);
emit TaskCreated(id, pid, payout, bountyToken, bountyPayout, requiresApplication, title, metadataHash);
}
function updateTask(
uint256 id,
uint256 newPayout,
bytes calldata newTitle,
bytes32 newMetadataHash,
address newBountyToken,
uint256 newBountyPayout
) external {
_requireCanCreate(_layout()._tasks[id].projectId);
Layout storage l = _layout();
ValidationLib.requireValidTitle(newTitle);
ValidationLib.requireValidPayout96(newPayout);
ValidationLib.requireValidBountyConfig(newBountyToken, newBountyPayout);
Task storage t = _task(l, id);
if (t.status != Status.UNCLAIMED) revert BadStatus();
Project storage p = l._projects[t.projectId];
// Update participation token budget
// PT cap: 0 = unlimited (minted tokens)
uint256 tentative = p.spent - t.payout + newPayout;
if (p.cap != 0 && tentative > p.cap) revert BudgetLib.BudgetExceeded();
p.spent = uint128(tentative);
// Update bounty budgets
if (t.bountyToken != address(0) && t.bountyPayout > 0) {
BudgetLib.Budget storage oldB = p.bountyBudgets[t.bountyToken];
oldB.subtractSpent(t.bountyPayout);
}
if (newBountyToken != address(0) && newBountyPayout > 0) {
BudgetLib.Budget storage newB = p.bountyBudgets[newBountyToken];
newB.addSpent(newBountyPayout);
}
// Update task
t.payout = uint96(newPayout);
t.bountyToken = newBountyToken;
t.bountyPayout = uint96(newBountyPayout);
emit TaskUpdated(id, newPayout, newBountyToken, newBountyPayout, newTitle, newMetadataHash);
}
function claimTask(uint256 id) external {
_requireCanClaim(id);
Layout storage l = _layout();
Task storage t = _task(l, id);
if (t.status != Status.UNCLAIMED) revert BadStatus();
if (t.requiresApplication) revert RequiresApplication();
t.status = Status.CLAIMED;
t.claimer = _msgSender();
emit TaskClaimed(id, _msgSender());
}
function assignTask(uint256 id, address assignee) external {
_requireCanAssign(_layout()._tasks[id].projectId);
assignee.requireNonZeroAddress();
Layout storage l = _layout();
Task storage t = _task(l, id);
if (t.status != Status.UNCLAIMED) revert BadStatus();
t.status = Status.CLAIMED;
t.claimer = assignee;
emit TaskAssigned(id, assignee, _msgSender());
}
function submitTask(uint256 id, bytes32 submissionHash) external {
Layout storage l = _layout();
Task storage t = _task(l, id);
if (t.status != Status.CLAIMED) revert BadStatus();
if (t.claimer != _msgSender()) revert NotClaimer();
if (submissionHash == bytes32(0)) revert ValidationLib.InvalidString();
t.status = Status.SUBMITTED;
emit TaskSubmitted(id, submissionHash);
}
function completeTask(uint256 id) external {
Layout storage l = _layout();
bytes32 pid = l._tasks[id].projectId;
_checkPerm(pid, TaskPerm.REVIEW);
Task storage t = _task(l, id);
if (t.status != Status.SUBMITTED) revert BadStatus();
// Self-review: if caller is the claimer, require SELF_REVIEW permission or PM/executor
address sender = _msgSender();
if (t.claimer == sender && !_isPM(pid, sender)) {
if (!TaskPerm.has(_permMask(sender, pid), TaskPerm.SELF_REVIEW)) {
revert SelfReviewNotAllowed();
}
}
t.status = Status.COMPLETED;
l.token.mint(t.claimer, uint256(t.payout));
// Transfer bounty token if set
if (t.bountyToken != address(0) && t.bountyPayout > 0) {
IERC20(t.bountyToken).safeTransfer(t.claimer, uint256(t.bountyPayout));
}
emit TaskCompleted(id, _msgSender());
}
function rejectTask(uint256 id, bytes32 rejectionHash) external {
Layout storage l = _layout();
_checkPerm(l._tasks[id].projectId, TaskPerm.REVIEW);
Task storage t = _task(l, id);
if (t.status != Status.SUBMITTED) revert BadStatus();
if (rejectionHash == bytes32(0)) revert ValidationLib.InvalidString();
t.status = Status.CLAIMED;
emit TaskRejected(id, _msgSender(), rejectionHash);
}
function cancelTask(uint256 id) external {
_requireCanCreate(_layout()._tasks[id].projectId);
Layout storage l = _layout();
Task storage t = _task(l, id);
if (t.status != Status.UNCLAIMED) revert BadStatus();
Project storage p = l._projects[t.projectId];
if (p.spent < t.payout) revert BudgetLib.SpentUnderflow();
unchecked {
p.spent -= t.payout;
}
// Roll back bounty budget if applicable
if (t.bountyToken != address(0) && t.bountyPayout > 0) {
BudgetLib.Budget storage bb = p.bountyBudgets[t.bountyToken];
bb.subtractSpent(t.bountyPayout);
}
t.status = Status.CANCELLED;
t.claimer = address(0);
// Clear all applications - zero out the mapping and delete applicants array
delete l.taskApplicants[id];
emit TaskCancelled(id, _msgSender());
}
/*──────── Application System ─────*/
/**
* @dev Submit application for a task with IPFS hash containing submission
* @param id Task ID to apply for
* @param applicationHash IPFS hash of the application/submission
*/
function applyForTask(uint256 id, bytes32 applicationHash) external {
_requireCanClaim(id);
Layout storage l = _layout();
Task storage t = _task(l, id);
if (t.status != Status.UNCLAIMED) revert BadStatus();
ValidationLib.requireValidApplicationHash(applicationHash);
if (!t.requiresApplication) revert NoApplicationRequired();
address applicant = _msgSender();
// Check if user has already applied
if (l.taskApplications[id][applicant] != bytes32(0)) revert AlreadyApplied();
// Add applicant to the list
l.taskApplicants[id].push(applicant);
l.taskApplications[id][applicant] = applicationHash;
emit TaskApplicationSubmitted(id, applicant, applicationHash);
}
/**
* @dev Approve an application, moving task to CLAIMED status
* @param id Task ID
* @param applicant Address of the applicant to approve
*/
function approveApplication(uint256 id, address applicant) external {
_requireCanAssign(_layout()._tasks[id].projectId);
Layout storage l = _layout();
Task storage t = _task(l, id);
if (t.status != Status.UNCLAIMED) revert BadStatus();
if (l.taskApplications[id][applicant] == bytes32(0)) revert NotApplicant();
t.status = Status.CLAIMED;
t.claimer = applicant;
delete l.taskApplicants[id];
emit TaskApplicationApproved(id, applicant, _msgSender());
}
/**
* @dev Creates a task and immediately assigns it to the specified assignee in a single transaction.
* @param payout The payout amount for the task
* @param title Task title (required, raw UTF-8)
* @param metadataHash IPFS CID sha256 digest (optional, bytes32(0) valid)
* @param pid Project ID
* @param assignee Address to assign the task to
* @return taskId The ID of the created task
*/
function createAndAssignTask(
uint256 payout,
bytes calldata title,
bytes32 metadataHash,
bytes32 pid,
address assignee,
address bountyToken,
uint256 bountyPayout,
bool requiresApplication
) external returns (uint256 taskId) {
return _createAndAssignTask(
payout, title, metadataHash, pid, assignee, requiresApplication, bountyToken, bountyPayout
);
}
function _createAndAssignTask(
uint256 payout,
bytes calldata title,
bytes32 metadataHash,
bytes32 pid,
address assignee,
bool requiresApplication,
address bountyToken,
uint256 bountyPayout
) internal returns (uint256 taskId) {
assignee.requireNonZeroAddress();
Layout storage l = _layout();
address sender = _msgSender();
// Check permissions - user must have both CREATE and ASSIGN permissions, or be a project manager
uint8 userPerms = _permMask(sender, pid);
bool hasCreateAndAssign = TaskPerm.has(userPerms, TaskPerm.CREATE) && TaskPerm.has(userPerms, TaskPerm.ASSIGN);
if (!hasCreateAndAssign && !_isPM(pid, sender)) {
revert Unauthorized();
}
// Validation
ValidationLib.requireValidTitle(title);
ValidationLib.requireValidPayout96(payout);
ValidationLib.requireValidBountyConfig(bountyToken, bountyPayout);
Project storage p = l._projects[pid];
if (!p.exists) revert NotFound();
// PT cap: 0 = unlimited (minted tokens)
uint256 newSpent = p.spent + payout;
if (p.cap != 0 && newSpent > p.cap) revert BudgetLib.BudgetExceeded();
p.spent = uint128(newSpent);
// Check bounty budget (BudgetLib: cap 0 = DISABLED, must be explicitly enabled)
if (bountyToken != address(0) && bountyPayout > 0) {
BudgetLib.Budget storage bb = p.bountyBudgets[bountyToken];
bb.addSpent(bountyPayout);
}
// Create and assign task in one go
taskId = l.nextTaskId++;
l._tasks[taskId] =
Task(pid, uint96(payout), assignee, uint96(bountyPayout), requiresApplication, Status.CLAIMED, bountyToken);
// Emit events
emit TaskCreated(taskId, pid, payout, bountyToken, bountyPayout, requiresApplication, title, metadataHash);
emit TaskAssigned(taskId, assignee, sender);
}
/*──────── Config Setter (Optimized) ─────── */
function setConfig(ConfigKey key, bytes calldata value) external {
_requireExecutor();
Layout storage l = _layout();
if (key == ConfigKey.EXECUTOR) {
address newExecutor = abi.decode(value, (address));
newExecutor.requireNonZeroAddress();
l.executor = newExecutor;
emit ExecutorUpdated(newExecutor);
return;
}
if (key == ConfigKey.CREATOR_HAT_ALLOWED) {
(uint256 hat, bool allowed) = abi.decode(value, (uint256, bool));
HatManager.setHatInArray(l.creatorHatIds, hat, allowed);
emit HatSet(HatType.CREATOR, hat, allowed);
return;
}
if (key == ConfigKey.ROLE_PERM) {
(uint256 hatId, uint8 mask) = abi.decode(value, (uint256, uint8));
l.rolePermGlobal[hatId] = mask;
_syncPermissionHat(hatId);
return;
}
// Project-related configs - consolidate common logic
bytes32 pid;
if (key >= ConfigKey.BOUNTY_CAP) {
pid = abi.decode(value, (bytes32));
Project storage p = l._projects[pid];
if (!p.exists) revert NotFound();
if (key == ConfigKey.BOUNTY_CAP) {
(, address token, uint256 newCap) = abi.decode(value, (bytes32, address, uint256));
token.requireNonZeroAddress();
ValidationLib.requireValidCapAmount(newCap);
BudgetLib.Budget storage b = p.bountyBudgets[token];
ValidationLib.requireValidCap(newCap, b.spent);
uint256 oldCap = b.cap;
b.cap = uint128(newCap);
emit BountyCapSet(pid, token, oldCap, newCap);
} else if (key == ConfigKey.PROJECT_MANAGER) {
(, address mgr, bool isManager) = abi.decode(value, (bytes32, address, bool));
mgr.requireNonZeroAddress();
p.managers[mgr] = isManager;
emit ProjectManagerUpdated(pid, mgr, isManager);
} else if (key == ConfigKey.PROJECT_CAP) {
(, uint256 newCap) = abi.decode(value, (bytes32, uint256));
ValidationLib.requireValidCapAmount(newCap);
ValidationLib.requireValidCap(newCap, p.spent);
uint256 old = p.cap;
p.cap = uint128(newCap);
emit ProjectCapUpdated(pid, old, newCap);
}
}
}
function setProjectRolePerm(bytes32 pid, uint256 hatId, uint8 mask) external {
_requireCreator();
_requireProjectExists(pid);
Layout storage l = _layout();
uint8 oldMask = l.rolePermProj[pid][hatId];
l.rolePermProj[pid][hatId] = mask;
_updateProjectPermRefCount(l, hatId, oldMask, mask);
_syncPermissionHat(hatId);
emit ProjectRolePermSet(pid, hatId, mask);
}
/*──────── Internal Perm helpers ─────*/
function _permMask(address user, bytes32 pid) internal view returns (uint8 m) {
Layout storage l = _layout();
uint256 len = l.permissionHatIds.length;
if (len == 0) return 0;
// one call instead of N
address[] memory wearers = new address[](len);
uint256[] memory hats_ = new uint256[](len);
for (uint256 i; i < len;) {
wearers[i] = user;
hats_[i] = l.permissionHatIds[i];
unchecked {
++i;
}
}
uint256[] memory bal = l.hats.balanceOfBatch(wearers, hats_);
for (uint256 i; i < len;) {
if (bal[i] == 0) {
unchecked {
++i;
}
continue; // user doesn't wear it
}
uint256 h = hats_[i];
uint8 mask = l.rolePermProj[pid][h];
m |= mask == 0 ? l.rolePermGlobal[h] : mask; // project overrides global
unchecked {
++i;
}
}
}
function _isPM(bytes32 pid, address who) internal view returns (bool) {
Layout storage l = _layout();
return (who == l.executor) || l._projects[pid].managers[who];
}
function _checkPerm(bytes32 pid, uint8 flag) internal view {
address s = _msgSender();
if (!TaskPerm.has(_permMask(s, pid), flag) && !_isPM(pid, s)) revert Unauthorized();
}
function _setBatchHatPerm(bytes32 pid, uint256[] calldata hatIds, uint8 flag) internal {
Layout storage l = _layout();
for (uint256 i; i < hatIds.length;) {
uint256 hatId = hatIds[i];
uint8 oldMask = l.rolePermProj[pid][hatId];
uint8 newMask = l.rolePermProj[pid][hatId] | flag;
l.rolePermProj[pid][hatId] = newMask;
_updateProjectPermRefCount(l, hatId, oldMask, newMask);
_syncPermissionHat(hatId);
emit ProjectRolePermSet(pid, hatId, newMask);
unchecked {
++i;
}
}
}
/**
* @dev Keep `permissionHatIds` consistent with effective permissions.
* A hat should remain tracked if it has any non-zero global or project mask.
*/
function _syncPermissionHat(uint256 hatId) internal {
Layout storage l = _layout();
bool hasGlobalPerm = l.rolePermGlobal[hatId] != 0;
bool hasProjectPerm = l.projectPermHatRefCount[hatId] != 0;
// Upgrade-safe fallback: if refcount wasn't initialized for existing data,
// rebuild it lazily only when we would otherwise remove the hat.
if (!hasProjectPerm && _hasAnyProjectPermissionLegacy(l, hatId)) {
l.projectPermHatRefCount[hatId] = _rebuildProjectPermRefCount(l, hatId);
hasProjectPerm = l.projectPermHatRefCount[hatId] != 0;
}
HatManager.setHatInArray(l.permissionHatIds, hatId, hasGlobalPerm || hasProjectPerm);
}
function _updateProjectPermRefCount(Layout storage l, uint256 hatId, uint8 oldMask, uint8 newMask) internal {
if (oldMask == 0 && newMask != 0) {
l.projectPermHatRefCount[hatId]++;
} else if (oldMask != 0 && newMask == 0) {
uint256 count = l.projectPermHatRefCount[hatId];
if (count > 0) {
l.projectPermHatRefCount[hatId] = count - 1;
}
}
}
function _hasAnyProjectPermissionLegacy(Layout storage l, uint256 hatId) internal view returns (bool) {
uint48 nextProjectId = l.nextProjectId;
for (uint48 i; i < nextProjectId;) {
bytes32 pid = bytes32(uint256(i));
if (l._projects[pid].exists && l.rolePermProj[pid][hatId] != 0) {
return true;
}
unchecked {
++i;
}
}
return false;
}
function _rebuildProjectPermRefCount(Layout storage l, uint256 hatId) internal view returns (uint256 count) {
uint48 nextProjectId = l.nextProjectId;
for (uint48 i; i < nextProjectId;) {
bytes32 pid = bytes32(uint256(i));
if (l._projects[pid].exists && l.rolePermProj[pid][hatId] != 0) {
count++;
}
unchecked {
++i;
}
}
}
/*──────── Internal Helper Functions ─────────── */
/// @dev Returns true if `user` wears *any* creator hat.
function _hasCreatorHat(address user) internal view returns (bool) {
Layout storage l = _layout();
return HatManager.hasAnyHat(l.hats, l.creatorHatIds, user);
}
/*──────── Utils / View ────*/
function _task(Layout storage l, uint256 id) private view returns (Task storage t) {
if (id >= l.nextTaskId) revert NotFound();
t = l._tasks[id];
}
/*──────── Minimal External Getters for Lens ─────── */
function getLensData(uint8 t, bytes calldata d) external view returns (bytes memory) {
Layout storage l = _layout();
if (t == 1) {
// Task
uint256 id = abi.decode(d, (uint256));
if (id >= l.nextTaskId) revert NotFound();
Task storage task = l._tasks[id];
return abi.encode(
task.projectId,
task.payout,
task.claimer,
task.bountyPayout,
task.requiresApplication,
task.status,
task.bountyToken
);
} else if (t == 2) {
// Project
bytes32 pid = abi.decode(d, (bytes32));