-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathTaskManager.sol
More file actions
1374 lines (1234 loc) · 58.5 KB
/
TaskManager.sol
File metadata and controls
1374 lines (1234 loc) · 58.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
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 ───────*/
/// @notice Project or task ID does not exist (or task id beyond `nextTaskId`).
error NotFound();
/// @notice Task status forbids this transition (e.g. completing an unclaimed task).
error BadStatus();
/// @notice Caller does not wear any creator hat and is not the executor.
error NotCreator();
/// @notice Caller is not the task's current claimer.
error NotClaimer();
/// @notice Caller is not the configured executor.
error NotExecutor();
/// @notice Caller is not the bootstrap deployer (or bootstrap phase is over).
error NotDeployer();
/// @notice Caller lacks the hat-derived permission and is not a project manager.
error Unauthorized();
/// @notice Address has not applied to this task.
error NotApplicant();
/// @notice Applicant has already submitted an application for this task.
error AlreadyApplied();
/// @notice Task is application-only; caller used the direct-claim path.
error RequiresApplication();
/// @notice Task does not accept applications; caller used the application path.
error NoApplicationRequired();
/// @notice Bootstrap task referenced a project index outside the project array.
error InvalidIndex();
/// @notice Claimer attempted to complete their own task without SELF_REVIEW permission.
error SelfReviewNotAllowed();
/// @notice Parallel calldata arrays have mismatched lengths.
error ArrayLengthMismatch();
/// @notice Batch input array is empty.
error EmptyBatch();
/// @notice Caller is neither the executor nor a wearer of any organizer hat.
error NotOrganizer();
/// @notice CAS guard: caller-supplied current folders root does not match storage.
/// @param expected Root the caller believed was current.
/// @param actual Root that is actually current on-chain.
error FoldersRootStale(bytes32 expected, bytes32 actual);
/*──────── 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,
ORGANIZER_HAT_ALLOWED
}
/*──────── 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
// ─── Folders (v3) ───
// Folder tree (names, parents, ordering, project assignments) lives off-chain in IPFS.
// Only the root hash is on-chain; reorganization = swap the hash via setFolders.
bytes32 foldersRoot;
uint256[] organizerHatIds; // hats authorized to reorganize the folder tree
}
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 ───────*/
/// @notice A role hat of `hatType` was added or removed from its enumeration array.
event HatSet(HatType hatType, uint256 hat, bool allowed);
/// @notice A project was created. `metadataHash` is an IPFS CID — not stored on-chain.
event ProjectCreated(bytes32 indexed id, bytes title, bytes32 metadataHash, uint256 cap);
/// @notice The participation-token cap on a project changed.
event ProjectCapUpdated(bytes32 indexed id, uint256 oldCap, uint256 newCap);
/// @notice A project manager was added or removed.
event ProjectManagerUpdated(bytes32 indexed id, address indexed manager, bool isManager);
/// @notice A project and all of its hat-permission overrides were deleted.
event ProjectDeleted(bytes32 indexed id);
/// @notice A hat's project-specific permission mask was updated.
event ProjectRolePermSet(bytes32 indexed id, uint256 indexed hatId, uint8 mask);
/// @notice A hat's GLOBAL permission mask changed via `setConfig(ROLE_PERM, ...)`.
/// @dev Mirrors `ProjectRolePermSet` minus the project id. Indexers track which
/// hats have which `TaskPerm` bits at the org level; `setProjectRolePerm`
/// handles the per-project override.
event RolePermSet(uint256 indexed hatId, uint8 mask);
/// @notice A per-project bounty-token cap changed.
event BountyCapSet(bytes32 indexed projectId, address indexed token, uint256 oldCap, uint256 newCap);
/// @notice The IPFS root for this org's folder tree changed.
/// @dev Subgraph consumers resolve the JSON off-chain at `newRoot`. `oldRoot` lets indexers chain revisions.
event FoldersUpdated(bytes32 indexed newRoot, bytes32 indexed oldRoot, address indexed sender);
/// @notice A hat was added to or removed from the organizer-hat array.
event OrganizerHatAllowed(uint256 indexed hatId, bool allowed);
/// @notice A new task was created under `project`.
event TaskCreated(
uint256 indexed id,
bytes32 indexed project,
uint256 payout,
address bountyToken,
uint256 bountyPayout,
bool requiresApplication,
bytes title,
bytes32 metadataHash
);
/// @notice An unclaimed task's mutable fields were updated.
event TaskUpdated(
uint256 indexed id, uint256 payout, address bountyToken, uint256 bountyPayout, bytes title, bytes32 metadataHash
);
/// @notice A claimer submitted work for review.
event TaskSubmitted(uint256 indexed id, bytes32 submissionHash);
/// @notice A task was claimed by `claimer`.
event TaskClaimed(uint256 indexed id, address indexed claimer);
/// @notice A task was assigned to `assignee` by `assigner` (bypasses claim flow).
event TaskAssigned(uint256 indexed id, address indexed assignee, address indexed assigner);
/// @notice A task was marked completed and payouts/bounties were dispatched.
event TaskCompleted(uint256 indexed id, address indexed completer);
/// @notice A task was cancelled and its budget reservations rolled back.
event TaskCancelled(uint256 indexed id, address indexed canceller);
/// @notice A submitted task was rejected and reverted to CLAIMED for resubmission.
event TaskRejected(uint256 indexed id, address indexed rejector, bytes32 rejectionHash);
/// @notice An applicant submitted an application for a task that requires one.
event TaskApplicationSubmitted(uint256 indexed id, address indexed applicant, bytes32 applicationHash);
/// @notice An application was approved and the task moved to CLAIMED for `applicant`.
event TaskApplicationApproved(uint256 indexed id, address indexed applicant, address indexed approver);
/// @notice The executor address was set or changed.
event ExecutorUpdated(address newExecutor);
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/*──────── Initialiser ───────*/
/**
* @notice One-time proxy initializer. Wires the org's PT, Hats, executor, and
* (optional) bootstrap deployer; seeds the creator-hat array.
* @param tokenAddress Participation token (must implement `mint`).
* @param hatsAddress Hats Protocol contract.
* @param creatorHats Initial hat IDs allowed to create projects.
* @param executorAddress Executor address (DAO execution layer).
* @param deployerAddress OrgDeployer address for `bootstrapProjectsAndTasks`; may be zero.
*/
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 ─────*/
/// @dev Caller must wear a creator hat or be the executor; reverts NotCreator otherwise.
function _requireCreator() internal view {
Layout storage l = _layout();
address s = _msgSender();
if (!_hasCreatorHat(s) && s != l.executor) revert NotCreator();
}
/// @dev Reverts NotFound if the project does not exist.
function _requireProjectExists(bytes32 pid) internal view {
if (!_layout()._projects[pid].exists) revert NotFound();
}
/// @dev Reverts NotExecutor if the caller is not the configured executor.
function _requireExecutor() internal view {
if (_msgSender() != _layout().executor) revert NotExecutor();
}
/// @dev Caller must be the executor or wear any hat in `organizerHatIds`; reverts NotOrganizer otherwise.
function _requireOrganizer() internal view {
Layout storage l = _layout();
address s = _msgSender();
if (s == l.executor) return;
if (!HatManager.hasAnyHat(l.hats, l.organizerHatIds, s)) revert NotOrganizer();
}
/// @dev Caller must hold CREATE permission on `pid` (or be a project manager / executor).
function _requireCanCreate(bytes32 pid) internal view {
_checkPerm(pid, TaskPerm.CREATE);
}
/// @dev Caller must hold CLAIM permission on the task's project.
function _requireCanClaim(uint256 tid) internal view {
_checkPerm(_layout()._tasks[tid].projectId, TaskPerm.CLAIM);
}
/// @dev Caller must hold ASSIGN permission on `pid`.
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;
}
}
}
/**
* @notice Delete a project and clear every hat's project-specific permission entries.
* @dev Permission: creator hat or executor. Does not reclaim spent participation tokens
* already minted by completed tasks; only erases project state and per-hat overrides.
* @param pid Project ID to delete.
*/
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);
}
/**
* @notice Bulk-grant org-wide `rolePermGlobal` masks during the bootstrap window.
* @dev Deployer-only escape hatch, identical access pattern to {bootstrapProjectsAndTasks}.
* Reverts {NotDeployer} once {clearDeployer} has been called. Effects per pair:
* - Writes `rolePermGlobal[hatId] = mask` (last write wins for duplicate hat IDs).
* - Calls `_syncPermissionHat(hatId)` so the enumeration array stays consistent
* (a `mask == 0` write removes the hat unless it still has any project-specific mask).
* - Emits {RolePermSet} per hat — the same event `setConfig(ROLE_PERM, ...)` emits, so
* subgraph consumers index these grants exactly the same way as runtime grants.
* Empty `hatIds` is a no-op (does not revert) — lets the caller pass zero grants without
* branching at the call site.
* @param hatIds Hat IDs to grant masks to.
* @param masks TaskPerm bitmasks (bitwise-OR of {TaskPerm} constants). Length must match `hatIds`.
*/
function bootstrapGlobalPerms(uint256[] calldata hatIds, uint8[] calldata masks) external {
Layout storage l = _layout();
if (_msgSender() != l.deployer) revert NotDeployer();
if (hatIds.length != masks.length) revert ArrayLengthMismatch();
for (uint256 i; i < hatIds.length;) {
uint256 hatId = hatIds[i];
uint8 mask = masks[i];
l.rolePermGlobal[hatId] = mask;
_syncPermissionHat(hatId);
emit RolePermSet(hatId, mask);
unchecked {
++i;
}
}
}
/*──────── Task Logic ───────*/
/**
* @notice Create a task under `pid` with the given payout and optional bounty.
* @dev Permission: CREATE on `pid` (hat-derived) or project manager / executor.
* @param payout Participation-token payout amount.
* @param title Raw UTF-8 title (validated for length).
* @param metadataHash IPFS CID; emitted in `TaskCreated`, not stored.
* @param pid Project ID this task belongs to.
* @param bountyToken ERC-20 bounty token; `address(0)` for no bounty.
* @param bountyPayout Bounty amount in `bountyToken` units.
* @param requiresApplication If true, claimants must submit an application first.
*/
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);
}
/**
* @notice Update a task's payout, title, metadata, and bounty fields.
* @dev Status gate: COMPLETED / CANCELLED always revert `BadStatus` — terminal states are
* immutable to avoid accounting drift (payouts have already been minted or refunded).
*
* Permission gate (any non-terminal status):
* - Executor or project manager: always allowed.
* - Hat with `TaskPerm.EDIT_FULL`: allowed in any non-terminal status.
* - Hat with `TaskPerm.CREATE`: allowed only while the task is `UNCLAIMED`
* (preserves the original pre-claim editing path).
*
* Post-claim edits silently change the claimer's payout / bounty expectation —
* the subgraph picks up the new values via the existing `TaskUpdated` event.
* Swapping `newBountyToken` to a token whose `bountyBudgets[token].cap` is zero
* (DISABLED) reverts via `BudgetLib.addSpent`; enable the new token's budget first
* with `setConfig(BOUNTY_CAP, ...)`.
*
* Re-runs validation on the new values and adjusts both PT and bounty budgets.
* @param id Task ID.
* @param newPayout New participation-token payout.
* @param newTitle New title.
* @param newMetadataHash New IPFS CID (emitted; not stored).
* @param newBountyToken New bounty token (or `address(0)` to clear).
* @param newBountyPayout New bounty amount.
*/
function updateTask(
uint256 id,
uint256 newPayout,
bytes calldata newTitle,
bytes32 newMetadataHash,
address newBountyToken,
uint256 newBountyPayout
) external {
Layout storage l = _layout();
Task storage t = _task(l, id);
if (t.status == Status.COMPLETED || t.status == Status.CANCELLED) revert BadStatus();
bytes32 pid = t.projectId;
address s = _msgSender();
if (s != l.executor && !_isPM(pid, s)) {
uint8 mask = _permMask(s, pid);
bool canEditFull = TaskPerm.has(mask, TaskPerm.EDIT_FULL);
bool canEditUnclaimed = t.status == Status.UNCLAIMED && TaskPerm.has(mask, TaskPerm.CREATE);
if (!canEditFull && !canEditUnclaimed) revert Unauthorized();
}
ValidationLib.requireValidTitle(newTitle);
ValidationLib.requireValidPayout96(newPayout);
ValidationLib.requireValidBountyConfig(newBountyToken, newBountyPayout);
Project storage p = l._projects[pid];
// 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);
}
/**
* @notice Update only a non-terminal task's title and metadata hash; payout and bounty fields
* are preserved verbatim.
* @dev Status gate matches {updateTask}: COMPLETED / CANCELLED revert `BadStatus`.
*
* Permission gate (any non-terminal status):
* - Executor or project manager: always allowed.
* - Hat with `TaskPerm.EDIT_META` or `TaskPerm.EDIT_FULL`: allowed in any non-terminal status.
* - Hat with `TaskPerm.CREATE`: allowed only while the task is `UNCLAIMED`
* (parity with the pre-claim editing path on {updateTask}).
*
* No budget side effects — the on-chain payout / bountyToken / bountyPayout fields are
* re-emitted unchanged so subgraph consumers can index the metadata update via the
* existing `TaskUpdated` event.
* @param id Task ID.
* @param newTitle New title.
* @param newMetadataHash New IPFS CID (emitted; not stored).
*/
function updateTaskMetadata(uint256 id, bytes calldata newTitle, bytes32 newMetadataHash) external {
Layout storage l = _layout();
Task storage t = _task(l, id);
if (t.status == Status.COMPLETED || t.status == Status.CANCELLED) revert BadStatus();
bytes32 pid = t.projectId;
address s = _msgSender();
if (s != l.executor && !_isPM(pid, s)) {
uint8 mask = _permMask(s, pid);
bool canEditMeta = TaskPerm.has(mask, TaskPerm.EDIT_META) || TaskPerm.has(mask, TaskPerm.EDIT_FULL);
bool canEditUnclaimed = t.status == Status.UNCLAIMED && TaskPerm.has(mask, TaskPerm.CREATE);
if (!canEditMeta && !canEditUnclaimed) revert Unauthorized();
}
ValidationLib.requireValidTitle(newTitle);
emit TaskUpdated(id, t.payout, t.bountyToken, t.bountyPayout, newTitle, newMetadataHash);
}
/**
* @notice Claim an UNCLAIMED task that does not require an application.
* @dev Permission: CLAIM on the task's project. Reverts RequiresApplication for
* application-only tasks (use `applyForTask`).
* @param id Task ID.
*/
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());
}
/**
* @notice Force-assign an UNCLAIMED task to `assignee`, bypassing the claim flow.
* @dev Permission: ASSIGN on the task's project. Task must be UNCLAIMED.
* @param id Task ID.
* @param assignee Address to record as the claimer.
*/
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());
}
/**
* @notice Claimer submits their finished work for review.
* @dev Caller must be the task's current claimer; task must be CLAIMED.
* `submissionHash` must be non-zero (typically an IPFS CID).
* @param id Task ID.
* @param submissionHash IPFS CID of the submission payload.
*/
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);
}
/**
* @notice Approve a SUBMITTED task: mint participation tokens to the claimer and
* transfer the bounty (if any).
* @dev Permission: REVIEW on the project. If the caller is the claimer themself,
* they additionally need SELF_REVIEW unless they are a project manager / executor.
* @param id Task ID.
*/
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());
}
/**
* @notice Reject a SUBMITTED task. Task reverts to CLAIMED so the claimer can resubmit.
* @dev Permission: REVIEW on the project. `rejectionHash` must be non-zero (IPFS CID of feedback).
* @param id Task ID.
* @param rejectionHash IPFS CID of the rejection reasoning.
*/
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);
}
/**
* @notice Cancel an UNCLAIMED task and roll back its PT/bounty budget reservations.
* @dev Permission: CREATE on the task's project. Pending applications are cleared.
* @param id Task ID.
*/
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 ─────*/
/**
* @notice Apply to claim a task that requires applications.
* @dev Permission: CLAIM on the task's project. Reverts AlreadyApplied if the
* caller already submitted an application for this task.
* @param id Task ID to apply for.
* @param applicationHash IPFS CID of the application/submission payload.
*/
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);
}
/**
* @notice Approve a pending application: the task moves to CLAIMED for `applicant`
* and the remaining applicants are dropped.
* @dev Permission: ASSIGN on the task's project.
* @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());
}
/**
* @notice Create a task and assign it to `assignee` in a single transaction.
* @dev Permission: caller must hold both CREATE and ASSIGN on `pid`, or be a project
* manager / executor. The task is created in CLAIMED state with the assignee as claimer.
* @param payout Participation-token payout.
* @param title Raw UTF-8 task title.
* @param metadataHash IPFS CID; emitted, not stored.
* @param pid Project ID.
* @param assignee Address to assign the task to.
* @param bountyToken ERC-20 bounty token (or `address(0)` for none).
* @param bountyPayout Bounty amount in `bountyToken` units.
* @param requiresApplication Recorded on the task even though it's already claimed.
* @return taskId 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);