/
Court.sol
921 lines (751 loc) · 36.8 KB
/
Court.sol
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
pragma solidity ^0.4.24; // TODO: pin solc
// Inspired by: Kleros.sol https://github.com/kleros/kleros @ 7281e69
import "./lib/HexSumTree.sol";
import "./lib/ArrayUtils.sol";
import "./standards/arbitration/IArbitrable.sol";
import "./standards/erc900/ERC900.sol";
import { ApproveAndCallFallBack } from "@aragon/apps-shared-minime/contracts/MiniMeToken.sol";
import "@aragon/os/contracts/lib/token/ERC20.sol";
import "@aragon/os/contracts/common/SafeERC20.sol";
import "@aragon/os/contracts/lib/math/SafeMath.sol";
contract Court is ERC900, ApproveAndCallFallBack {
using HexSumTree for HexSumTree.Tree;
using ArrayUtils for address[];
using SafeERC20 for ERC20;
using SafeMath for uint256;
enum AccountState {
NotJuror,
Juror,
PastJuror
}
struct AccountUpdate {
uint64 term;
bool positive; // TODO: optimize gas
uint256 delta;
}
struct Account {
mapping (address => uint256) balances; // token addr -> balance
AccountState state; // whether the account is not a juror, a current juror or a past juror
uint64 fromTerm; // first term in which the juror can be drawn
uint64 toTerm; // last term in which the juror can be drawn
uint256 atStakeTokens; // maximum amount of juror tokens that the juror could be slashed given their drafts
uint256 sumTreeId; // key in the sum tree used for sortition
AccountUpdate update; // next account update
}
struct CourtConfig {
// Fee structure
ERC20 feeToken;
uint16 governanceFeeShare; // ‱ of fees going to the governor (1/10,000)
uint256 jurorFee; // per juror, total dispute fee = jurorFee * jurors drawn
uint256 heartbeatFee; // per dispute, total heartbeat fee = heartbeatFee * disputes/appeals in term
uint256 draftFee; // per dispute
// Dispute config
uint64 commitTerms;
uint64 revealTerms;
uint64 appealTerms;
uint16 penaltyPct;
}
struct Term {
uint64 startTime; // timestamp when the term started
uint64 dependingDrafts; // disputes or appeals pegged to this term for randomness
uint64 courtConfigId; // fee structure for this term (index in courtConfigs array)
uint64 randomnessBN; // block number for entropy
bytes32 randomness; // entropy from randomnessBN block hash
address[] updateQueue; // jurors whose stake needs to be updated
address[] egressQueue; // jurors that will be removed from to the juror tree
}
struct JurorVote {
bytes32 commitment;
uint8 ruling;
address juror;
}
struct AdjudicationRound {
JurorVote[] votes;
mapping (uint8 => uint256) rulingVotes;
uint8 winningRuling;
uint64 draftTerm;
uint64 jurorNumber;
address triggeredBy;
}
enum Ruling {
Missing,
RefusedRuling
// ruling options are dispute specific
}
enum DisputeState {
PreDraft,
Adjudicating,
Executed,
Dismissed
}
struct Dispute {
IArbitrable subject;
uint8 possibleRulings; // number of possible rulings the court can decide on
DisputeState state;
AdjudicationRound[] rounds;
}
enum AdjudicationState {
Invalid,
Commit,
Reveal,
Appealable,
Ended
}
// State constants which are set in the constructor and can't change
ERC20 public jurorToken;
uint64 public termDuration; // recomended value ~1 hour as 256 blocks (available block hash) around an hour to mine
// Global config, configurable by governor
address public governor; // TODO: consider using aOS' ACL
uint256 public jurorMinStake; // TODO: consider adding it to the conf
uint256 public maxAppeals = 5;
CourtConfig[] public courtConfigs;
// Court state
uint64 public term;
uint64 public configChangeTerm;
mapping (address => Account) public accounts;
mapping (uint256 => address) public jurorsByTreeId;
mapping (uint64 => Term) public terms;
HexSumTree.Tree internal sumTree;
Dispute[] public disputes;
string internal constant ERROR_INVALID_ADDR = "COURT_INVALID_ADDR";
string internal constant ERROR_DEPOSIT_FAILED = "COURT_DEPOSIT_FAILED";
string internal constant ERROR_ZERO_TRANSFER = "COURT_ZERO_TRANSFER";
string internal constant ERROR_LOCKED_TOKENS = "COURT_LOCKED_TOKENS";
string internal constant ERROR_ACTIVATED_TOKENS = "COURT_ACTIVATED_TOKENS";
string internal constant ERROR_TOO_MANY_TRANSITIONS = "COURT_TOO_MANY_TRANSITIONS";
string internal constant ERROR_FIRST_TERM_NOT_STARTED = "COURT_FIRST_TERM_NOT_STARTED";
string internal constant ERROR_UNFINISHED_TERM = "COURT_UNFINISHED_TERM";
string internal constant ERROR_PAST_TERM_FEE_CHANGE = "COURT_PAST_TERM_FEE_CHANGE";
string internal constant ERROR_INVALID_ACCOUNT_STATE = "COURT_INVALID_ACCOUNT_STATE";
string internal constant ERROR_TOKENS_BELOW_MIN_STAKE = "COURT_TOKENS_BELOW_MIN_STAKE";
string internal constant ERROR_INVALID_ACTIVATION_TERM = "COURT_INVALID_ACTIVATION_TERM";
string internal constant ERROR_INVALID_DEACTIVATION_TERM = "COURT_INVALID_DEACTIVATION_TERM";
string internal constant ERROR_JUROR_TOKENS_AT_STAKE = "COURT_JUROR_TOKENS_AT_STAKE";
string internal constant ERROR_BALANCE_TOO_LOW = "COURT_BALANCE_TOO_LOW";
string internal constant ERROR_TOKEN_TRANSFER_FAILED = "COURT_TOKEN_TRANSFER_FAILED";
string internal constant ERROR_GOVENANCE_FEE_TOO_HIGH = "COURT_GOVENANCE_FEE_TOO_HIGH";
string internal constant ERROR_ENTITY_CANT_DISMISS = "COURT_ENTITY_CANT_DISMISS";
string internal constant ERROR_CANT_DISMISS_AFTER_DRAFT = "COURT_CANT_DISMISS_AFTER_DRAFT";
string internal constant ERROR_ROUND_ALREADY_DRAFTED = "COURT_ROUND_ALREADY_DRAFTED";
string internal constant ERROR_NOT_DRAFT_TERM = "COURT_NOT_DRAFT_TERM";
string internal constant ERROR_INVALID_DISPUTE_STATE = "COURT_INVALID_DISPUTE_STATE";
string internal constant ERROR_INVALID_ADJUDICATION_ROUND = "COURT_INVALID_ADJUDICATION_ROUND";
string internal constant ERROR_INVALID_ADJUDICATION_STATE = "COURT_INVALID_ADJUDICATION_STATE";
string internal constant ERROR_INVALID_JUROR = "COURT_INVALID_JUROR";
string internal constant ERROR_ALREADY_VOTED = "COURT_ALREADY_VOTED";
string internal constant ERROR_INVALID_VOTE = "COURT_INVALID_VOTE";
string internal constant ERROR_INVALID_RULING_OPTIONS = "COURT_INVALID_RULING_OPTIONS";
string internal constant ERROR_FAILURE_COMMITMENT_CHECK = "COURT_FAILURE_COMMITMENT_CHECK";
string internal constant ERROR_CONFIG_PERIOD_ZERO_TERMS = "COURT_CONFIG_PERIOD_ZERO_TERMS";
string internal constant ERROR_CANT_DISMISS_APPEAL = "COURT_CANT_DISMISS_APPEAL";
uint64 internal constant ZERO_TERM = 0; // invalid term that doesn't accept disputes
uint64 public constant MANUAL_DEACTIVATION = uint64(-1);
uint64 internal constant MODIFIER_ALLOWED_TERM_TRANSITIONS = 1;
bytes4 private constant ARBITRABLE_INTERFACE_ID = 0xabababab; // TODO: interface id
uint16 internal constant PCT_BASE = 10000; // ‱
uint8 public constant MIN_RULING_OPTIONS = 2;
uint8 public constant MAX_RULING_OPTIONS = MIN_RULING_OPTIONS;
event NewTerm(uint64 term, address indexed heartbeatSender);
event NewCourtConfig(uint64 fromTerm, uint64 courtConfigId);
event TokenBalanceChange(address indexed token, address indexed owner, uint256 amount, bool positive);
event JurorActivated(address indexed juror, uint64 fromTerm, uint64 toTerm);
event JurorDeactivated(address indexed juror, uint64 lastTerm);
event JurorDrafted(uint256 indexed disputeId, address indexed juror, uint256 draftId);
event DisputeStateChanged(uint256 indexed disputeId, DisputeState indexed state);
event NewDispute(uint256 indexed disputeId, address indexed subject, uint64 indexed draftTerm, uint64 jurorNumber);
event TokenWithdrawal(address indexed token, address indexed account, uint256 amount);
event VoteCommitted(uint256 indexed disputeId, uint256 indexed roundId, address indexed juror, bytes32 commitment);
event VoteRevealed(uint256 indexed disputeId, uint256 indexed roundId, address indexed juror, uint8 ruling);
event VoteLeaked(uint256 indexed disputeId, uint256 indexed roundId, address indexed juror, address leaker);
event RulingAppealed(uint256 indexed disputeId, uint256 indexed roundId, uint64 indexed draftTerm, uint256 jurorNumber);
modifier only(address _addr) {
require(msg.sender == _addr, ERROR_INVALID_ADDR);
_;
}
modifier ensureTerm {
uint64 requiredTransitions = neededTermTransitions();
require(requiredTransitions <= MODIFIER_ALLOWED_TERM_TRANSITIONS, ERROR_TOO_MANY_TRANSITIONS);
if (requiredTransitions > 0) {
heartbeat(requiredTransitions);
}
_;
}
modifier ensureDrafted(
uint256 _disputeId,
uint256 _roundId,
uint256 _draftId,
address _juror,
AdjudicationState _state
) {
_checkAdjudicationState(_disputeId, _roundId, _state);
require(_getJurorVote(_disputeId, _roundId, _draftId).juror == _juror, ERROR_INVALID_JUROR);
_;
}
/** @dev Constructor.
* @param _termDuration Duration in seconds per term (recommended 1 hour)
* @param _jurorToken The address of the juror work token contract.
* @param _feeToken The address of the token contract that is used to pay for fees.
* @param _jurorFee The amount of _feeToken that is paid per juror per dispute
* @param _heartbeatFee The amount of _feeToken per dispute to cover maintenance costs.
* @param _draftFee The amount of _feeToken per juror to cover the drafting cost.
* @param _governanceFeeShare Share in ‱ of fees that are paid to the governor.
* @param _governor Address of the governor contract.
* @param _firstTermStartTime Timestamp in seconds when the court will open (to give time for juror onboarding)
* @param _jurorMinStake Minimum amount of juror tokens that can be activated
* @param _commitTerms Number of terms that the vote commit period lasts in an adjudication round
* @param _revealTerms Number of terms that the vote reveal period lasts in an adjudication round
* @param _appealTerms Number of terms during which a court ruling can be appealed
* @param _penaltyPct ‱ of jurorMinStake that can be slashed (1/10,000)
*/
constructor(
uint64 _termDuration,
ERC20 _jurorToken,
ERC20 _feeToken,
uint256 _jurorFee,
uint256 _heartbeatFee,
uint256 _draftFee,
uint16 _governanceFeeShare,
address _governor,
uint64 _firstTermStartTime,
uint256 _jurorMinStake,
uint64 _commitTerms,
uint64 _revealTerms,
uint64 _appealTerms,
uint16 _penaltyPct
) public {
termDuration = _termDuration;
jurorToken = _jurorToken;
jurorMinStake = _jurorMinStake;
governor = _governor;
courtConfigs.length = 1; // leave index 0 empty
_setCourtConfig(
ZERO_TERM,
_feeToken,
_jurorFee,
_heartbeatFee,
_draftFee,
_governanceFeeShare,
_commitTerms,
_revealTerms,
_appealTerms,
_penaltyPct
);
terms[ZERO_TERM].startTime = _firstTermStartTime - _termDuration;
sumTree.init();
assert(sumTree.insert(0) == 0); // first tree item is an empty juror
}
function heartbeat(uint64 _termTransitions) public {
require(canTransitionTerm(), ERROR_UNFINISHED_TERM);
uint64 prevTermId = term;
Term storage prevTerm = terms[prevTermId];
Term storage nextTerm = terms[prevTermId + 1];
address heartbeatSender = msg.sender;
// Set fee structure for term
if (nextTerm.courtConfigId == 0) {
nextTerm.courtConfigId = prevTerm.courtConfigId;
} else {
configChangeTerm = ZERO_TERM; // fee structure changed in this term
}
// TODO: skip period if you can
// Set the start time of the term (ensures equally long terms, regardless of heartbeats)
nextTerm.startTime = prevTerm.startTime + termDuration;
nextTerm.randomnessBN = blockNumber() + 1; // randomness source set to next block (unknown when heartbeat happens)
_processJurorQueues(prevTermId, nextTerm);
CourtConfig storage courtConfig = courtConfigs[nextTerm.courtConfigId];
uint256 totalFee = nextTerm.dependingDrafts * courtConfig.heartbeatFee;
if (totalFee > 0) {
_payFees(courtConfig.feeToken, heartbeatSender, totalFee, courtConfig.governanceFeeShare);
}
term += 1;
emit NewTerm(term, heartbeatSender);
if (_termTransitions > 0 && canTransitionTerm()) {
heartbeat(_termTransitions - 1);
}
}
function createDispute(IArbitrable _subject, uint8 _possibleRulings, uint64 _jurorNumber, uint64 _draftTerm)
external
ensureTerm
returns (uint256)
{
// TODO: Limit the min amount of terms before drafting (to allow for evidence submission)
// TODO: Limit the max amount of terms into the future that a dispute can be drafted
// TODO: Limit the max number of initial jurors
// TODO: ERC165 check that _subject conforms to the Arbitrable interface
// TODO: Consider requiring that only the contract being arbitred can create a dispute
require(_possibleRulings >= MIN_RULING_OPTIONS && _possibleRulings <= MAX_RULING_OPTIONS, ERROR_INVALID_RULING_OPTIONS);
uint256 disputeId = disputes.length;
disputes.length = disputeId + 1;
Dispute storage dispute = disputes[disputeId];
dispute.subject = _subject;
dispute.possibleRulings = _possibleRulings;
_newAdjudicationRound(dispute, _jurorNumber, _draftTerm);
emit NewDispute(disputeId, _subject, _draftTerm, _jurorNumber);
return disputeId;
}
function dismissDispute(uint256 _disputeId)
external
ensureTerm
{
Dispute storage dispute = disputes[_disputeId];
uint256 roundId = dispute.rounds.length - 1;
AdjudicationRound storage round = dispute.rounds[roundId];
require(round.triggeredBy == msg.sender, ERROR_ENTITY_CANT_DISMISS);
require(dispute.state == DisputeState.PreDraft && round.draftTerm > term, ERROR_CANT_DISMISS_AFTER_DRAFT);
require(roundId == 0, ERROR_CANT_DISMISS_APPEAL);
dispute.state = DisputeState.Dismissed;
terms[round.draftTerm].dependingDrafts -= 1;
// refund fees
(ERC20 feeToken, uint256 feeAmount, uint16 governanceFeeShare) = feeForJurorDraft(round.draftTerm, round.jurorNumber);
_payFees(feeToken, round.triggeredBy, feeAmount, governanceFeeShare);
emit DisputeStateChanged(_disputeId, dispute.state);
}
function draftAdjudicationRound(uint256 _disputeId)
public
ensureTerm
{
Dispute storage dispute = disputes[_disputeId];
AdjudicationRound storage round = dispute.rounds[dispute.rounds.length - 1];
Term storage draftTerm = terms[term];
CourtConfig storage config = courtConfigs[draftTerm.courtConfigId]; // safe to use directly as it is the current term
// TODO: Work on recovery if draft doesn't occur in the term it was supposed to
// it should be scheduled for a future draft and require to pay the heartbeat fee for the term
require(round.draftTerm == term, ERROR_NOT_DRAFT_TERM);
require(dispute.state == DisputeState.PreDraft, ERROR_ROUND_ALREADY_DRAFTED);
if (draftTerm.randomness == bytes32(0)) {
// the blockhash could be 0 if the first dispute draft happens 256 blocks after the term starts
draftTerm.randomness = block.blockhash(draftTerm.randomnessBN);
}
uint256 maxPenalty = _pct4(jurorMinStake, config.penaltyPct);
uint256 jurorNumber = round.jurorNumber;
uint256 skippedJurors = 0;
round.votes.length = jurorNumber;
for (uint256 i = 0; i < jurorNumber; i++) {
(uint256 jurorKey, uint256 stake) = treeSearch(draftTerm.randomness, _disputeId, i + skippedJurors);
address juror = jurorsByTreeId[jurorKey];
// Account storage jurorAccount = accounts[juror]; // Hitting stack too deep
uint256 newAtStake = accounts[juror].atStakeTokens + maxPenalty;
if (stake >= newAtStake) {
accounts[juror].atStakeTokens += newAtStake;
} else {
// SECURITY: This has a chance of bricking the round depending on the state of the court
skippedJurors++;
i--;
continue;
}
round.votes[i].juror = juror;
emit JurorDrafted(_disputeId, juror, i);
}
dispute.state = DisputeState.Adjudicating;
_payFees(config.feeToken, msg.sender, config.draftFee * jurorNumber, config.governanceFeeShare);
emit DisputeStateChanged(_disputeId, dispute.state);
}
function commitVote(
uint256 _disputeId,
uint256 _roundId,
uint256 _draftId,
bytes32 _commitment
)
external
ensureTerm
ensureDrafted(_disputeId, _roundId, _draftId, msg.sender, AdjudicationState.Commit)
{
JurorVote storage vote = _getJurorVote(_disputeId, _roundId, _draftId);
require(vote.commitment == bytes32(0) && vote.ruling == uint8(Ruling.Missing), ERROR_ALREADY_VOTED);
vote.commitment = _commitment;
emit VoteCommitted(_disputeId, _roundId, msg.sender, _commitment);
}
function leakVote(
uint256 _disputeId,
uint256 _roundId,
uint256 _draftId,
address _juror,
uint8 _leakedRuling,
bytes32 _salt
)
external
ensureTerm
ensureDrafted(_disputeId, _roundId, _draftId, _juror, AdjudicationState.Commit)
{
checkVote(_disputeId, _roundId, _draftId, _leakedRuling, _salt);
uint8 ruling = uint8(Ruling.RefusedRuling);
JurorVote storage vote = _getJurorVote(_disputeId, _roundId, _draftId);
vote.ruling = ruling;
// TODO: slash juror
updateTally(_disputeId, _roundId, ruling);
emit VoteLeaked(_disputeId, _roundId, _juror, msg.sender);
emit VoteRevealed(_disputeId, _roundId, _juror, ruling);
}
function revealVote(
uint256 _disputeId,
uint256 _roundId,
uint256 _draftId,
uint8 _ruling,
bytes32 _salt
)
external
ensureTerm
ensureDrafted(_disputeId, _roundId, _draftId, msg.sender, AdjudicationState.Reveal)
{
checkVote(_disputeId, _roundId, _draftId, _ruling, _salt);
Dispute storage dispute = disputes[_disputeId];
JurorVote storage vote = _getJurorVote(_disputeId, _roundId, _draftId);
require(_ruling > uint8(Ruling.Missing) && _ruling <= dispute.possibleRulings + 1, ERROR_INVALID_VOTE);
vote.ruling = _ruling;
updateTally(_disputeId, _roundId, _ruling);
emit VoteRevealed(_disputeId, _roundId, msg.sender, _ruling);
}
function appealRuling(uint256 _disputeId, uint256 _roundId) external ensureTerm {
_checkAdjudicationState(_disputeId, _roundId, AdjudicationState.Appealable);
Dispute storage dispute = disputes[_disputeId];
AdjudicationRound storage currentRound = dispute.rounds[_roundId];
uint64 appealJurorNumber = 2 * currentRound.jurorNumber + 1; // J' = 2J + 1
uint64 appealDraftTerm = term + 1; // Appeals are drafted in the next term
uint256 roundId = _newAdjudicationRound(dispute, appealJurorNumber, appealDraftTerm);
emit RulingAppealed(_disputeId, roundId, appealDraftTerm, appealJurorNumber);
}
function _newAdjudicationRound(Dispute storage dispute, uint64 _jurorNumber, uint64 _draftTerm) internal returns (uint256 roundId) {
(ERC20 feeToken, uint256 feeAmount,) = feeForJurorDraft(_draftTerm, _jurorNumber);
if (feeAmount > 0) {
require(feeToken.safeTransferFrom(msg.sender, this, feeAmount), ERROR_DEPOSIT_FAILED);
}
dispute.state = DisputeState.PreDraft;
roundId = dispute.rounds.length;
dispute.rounds.length = roundId + 1;
AdjudicationRound storage round = dispute.rounds[roundId];
round.draftTerm = _draftTerm;
round.jurorNumber = _jurorNumber;
round.triggeredBy = msg.sender;
terms[_draftTerm].dependingDrafts += 1;
}
function updateTally(uint256 _disputeId, uint256 _roundId, uint8 _ruling) internal {
AdjudicationRound storage round = disputes[_disputeId].rounds[_roundId];
uint256 rulingVotes = round.rulingVotes[_ruling] + 1;
round.rulingVotes[_ruling] = rulingVotes;
uint8 winningRuling = round.winningRuling;
uint256 winningSupport = round.rulingVotes[winningRuling];
// If it passes the currently winning option
// Or if there is a tie, the lowest ruling option is set as the winning ruling
if (rulingVotes > winningSupport || (rulingVotes == winningSupport && _ruling < winningRuling)) {
round.winningRuling = _ruling;
}
}
function checkVote(uint256 _disputeId, uint256 _roundId, uint256 _draftId, uint8 _ruling, bytes32 _salt) internal {
JurorVote storage jurorVote = _getJurorVote(_disputeId, _roundId, _draftId);
require(jurorVote.commitment == encryptVote(_ruling, _salt), ERROR_FAILURE_COMMITMENT_CHECK);
require(jurorVote.ruling == uint8(Ruling.Missing), ERROR_ALREADY_VOTED);
}
function getWinningRuling(uint256 _disputeId) public view returns (uint8 ruling, uint256 rulingVotes) {
Dispute storage dispute = disputes[_disputeId];
AdjudicationRound storage round = dispute.rounds[dispute.rounds.length - 1];
ruling = round.winningRuling;
rulingVotes = round.rulingVotes[ruling];
}
function _checkAdjudicationState(uint256 _disputeId, uint256 _roundId, AdjudicationState _state) internal {
Dispute storage dispute = disputes[_disputeId];
DisputeState disputeState = dispute.state;
if (disputeState == DisputeState.PreDraft) {
draftAdjudicationRound(_disputeId);
}
require(disputeState == DisputeState.Adjudicating, ERROR_INVALID_DISPUTE_STATE);
require(_roundId == dispute.rounds.length - 1, ERROR_INVALID_ADJUDICATION_ROUND);
require(adjudicationStateAtTerm(_disputeId, _roundId, term) == _state, ERROR_INVALID_ADJUDICATION_STATE);
}
function adjudicationStateAtTerm(uint256 _disputeId, uint256 _roundId, uint64 _term) internal returns (AdjudicationState) {
Dispute storage dispute = disputes[_disputeId];
AdjudicationRound storage round = disputes[_disputeId].rounds[_roundId];
uint64 draftTerm = round.draftTerm;
uint64 configId = terms[draftTerm].courtConfigId;
CourtConfig storage config = courtConfigs[uint256(configId)];
uint64 revealStart = draftTerm + config.commitTerms;
uint64 appealStart = revealStart + config.revealTerms;
uint64 appealEnd = appealStart + config.appealTerms;
if (_term < draftTerm) {
return AdjudicationState.Invalid;
} else if (_term < revealStart) {
return AdjudicationState.Commit;
} else if (_term < appealStart) {
return AdjudicationState.Reveal;
} else if (_term < appealEnd) {
return AdjudicationState.Appealable;
} else {
return AdjudicationState.Ended;
}
}
function getJurorVote(uint256 _disputeId, uint256 _roundId, uint256 _draftId) public view returns (address juror, uint8 ruling) {
JurorVote storage jurorVote = _getJurorVote(_disputeId, _roundId, _draftId);
return (jurorVote.juror, jurorVote.ruling);
}
function _getJurorVote(uint256 _disputeId, uint256 _roundId, uint256 _draftId) internal view returns (JurorVote storage) {
return disputes[_disputeId].rounds[_roundId].votes[_draftId];
}
function encryptVote(uint8 _ruling, bytes32 _salt) public view returns (bytes32) {
return keccak256(abi.encodePacked(_ruling, _salt));
}
function treeSearch(bytes32 _termRandomness, uint256 _disputeId, uint256 _iteration) internal view returns (uint256 key, uint256 value) {
bytes32 seed = keccak256(abi.encodePacked(_termRandomness, _disputeId, _iteration));
// TODO: optimize by caching tree.totalSum(), and perform a `tree.unsafeSortition(seed % totalSum)` (unimplemented)
return sumTree.randomSortition(uint256(seed));
}
/**
* @dev Assumes term is up to date
*/
function feeForJurorDraft(uint64 _draftTerm, uint64 _jurorNumber) public view returns (ERC20 feeToken, uint256 feeAmount, uint16 governanceFeeShare) {
CourtConfig storage fees = courtConfigForTerm(_draftTerm);
feeToken = fees.feeToken;
governanceFeeShare = fees.governanceFeeShare;
feeAmount = fees.heartbeatFee + _jurorNumber * (fees.jurorFee + fees.draftFee);
}
function courtConfigForTerm(uint64 _term) internal view returns (CourtConfig storage) {
uint64 feeTerm;
if (_term <= term) {
feeTerm = _term; // for past terms, use the fee structure of the specific term
} else if (configChangeTerm <= _term) {
feeTerm = configChangeTerm; // if fees are changing before the draft, use the incoming fee schedule
} else {
feeTerm = term; // if no changes are scheduled, use the current term fee schedule (which CANNOT change for this term)
}
uint256 courtConfigId = uint256(terms[feeTerm].courtConfigId);
return courtConfigs[courtConfigId];
}
function _payFees(ERC20 _feeToken, address _to, uint256 _amount, uint16 _governanceFeeShare) internal {
if (_amount == 0) {
return;
}
uint256 governanceFee = _pct4(_amount, _governanceFeeShare);
_assignTokens(_feeToken, _to, _amount - governanceFee);
if (governanceFee == 0) {
return;
}
_assignTokens(_feeToken, governor, governanceFee);
}
// TODO: should we charge heartbeat fees to jurors?
function activate(uint64 _fromTerm, uint64 _toTerm) external ensureTerm {
address jurorAddress = msg.sender;
Account storage account = accounts[jurorAddress];
uint256 balance = account.balances[jurorToken];
require(_fromTerm > term, ERROR_INVALID_ACTIVATION_TERM);
require(_toTerm > _fromTerm, ERROR_INVALID_DEACTIVATION_TERM);
require(account.state == AccountState.NotJuror, ERROR_INVALID_ACCOUNT_STATE);
require(balance >= jurorMinStake, ERROR_TOKENS_BELOW_MIN_STAKE);
uint256 sumTreeId = account.sumTreeId;
if (sumTreeId == 0) {
sumTreeId = sumTree.insert(0);
accounts[jurorAddress].sumTreeId = sumTreeId;
jurorsByTreeId[sumTreeId] = jurorAddress;
}
if (term == ZERO_TERM && _fromTerm == ZERO_TERM + 1) {
// allow direct juror onboardings before term 1 starts (no disputes depend on term 0)
sumTree.update(sumTreeId, balance, true);
} else {
// TODO: check queue size limit
account.update = AccountUpdate({ delta: balance, positive: true, term: _fromTerm });
terms[_fromTerm].updateQueue.push(jurorAddress);
}
if (_toTerm != MANUAL_DEACTIVATION) {
// TODO: check queue size limit
terms[_toTerm].egressQueue.push(jurorAddress);
}
account.fromTerm = _fromTerm;
account.toTerm = _toTerm;
account.state = AccountState.Juror;
account.balances[jurorToken] = 0; // tokens are either pending the update or in the tree
emit JurorActivated(jurorAddress, _fromTerm, _toTerm);
}
// TODO: activate more tokens
// this can't called if the juror is deactivated on the schedule specified when calling activate
// can be called many times to modify the deactivation date
function deactivate(uint64 _lastTerm) external ensureTerm {
address jurorAddress = msg.sender;
Account storage account = accounts[jurorAddress];
require(account.state == AccountState.Juror, ERROR_INVALID_ACCOUNT_STATE);
require(_lastTerm > term, ERROR_INVALID_DEACTIVATION_TERM);
// Juror didn't actually become activated
if (term < account.fromTerm && term != ZERO_TERM) {
terms[account.fromTerm].updateQueue.deleteItem(jurorAddress);
assert(account.update.positive); // If the juror didn't activate, its update can only be positive
account.balances[jurorToken] += account.update.delta;
delete account.update;
}
if (account.toTerm != MANUAL_DEACTIVATION) {
terms[account.toTerm].egressQueue.deleteItem(jurorAddress);
}
terms[_lastTerm].egressQueue.push(jurorAddress);
account.toTerm = _lastTerm;
emit JurorDeactivated(jurorAddress, _lastTerm);
}
function canTransitionTerm() public view returns (bool) {
return neededTermTransitions() >= 1;
}
function neededTermTransitions() public view returns (uint64) {
return (time() - terms[term].startTime) / termDuration;
}
// ERC900
function stake(uint256 _amount, bytes) external {
_stake(msg.sender, msg.sender, _amount);
}
function stakeFor(address _to, uint256 _amount, bytes) external {
_stake(msg.sender, _to, _amount);
}
/** @dev Callback of approveAndCall - transfer jurorTokens of a juror in the contract. Should be called by the jurorToken contract. TRUSTED.
* @param _from The address making the transfer.
* @param _amount Amount of tokens to transfer to Kleros (in basic units).
*/
function receiveApproval(address _from, uint256 _amount, address token, bytes)
public
only(token)
{
if (token == address(jurorToken)) {
_stake(_from, _from, _amount);
}
}
function unstake(uint256 _amount, bytes) external {
return withdraw(jurorToken, _amount);
}
function totalStakedFor(address _addr) public view returns (uint256) {
Account storage account = accounts[_addr];
uint256 sumTreeId = account.sumTreeId;
uint256 activeTokens = sumTreeId > 0 ? sumTree.getItem(sumTreeId) : 0;
AccountUpdate storage update = account.update;
uint256 pendingTokens = update.positive ? update.delta : -update.delta;
return account.balances[jurorToken] + activeTokens + pendingTokens;
}
function totalStaked() external view returns (uint256) {
return jurorToken.balanceOf(this);
}
function token() external view returns (address) {
return address(jurorToken);
}
function supportsHistory() external pure returns (bool) {
return false;
}
/**
* @param _token Token to withdraw
* @param _amount The amount to withdraw.
*/
function withdraw(ERC20 _token, uint256 _amount) public ensureTerm {
require(_amount > 0, ERROR_ZERO_TRANSFER);
address addr = msg.sender;
Account storage account = accounts[addr];
uint256 balance = account.balances[_token];
require(balance >= _amount, ERROR_BALANCE_TOO_LOW);
if (_token == jurorToken) {
if (account.state == AccountState.Juror) {
require(_amount <= unlockedBalanceOf(addr), ERROR_JUROR_TOKENS_AT_STAKE);
account.state = AccountState.PastJuror;
}
emit Unstaked(addr, _amount, totalStakedFor(addr), "");
}
account.balances[_token] -= _amount;
require(_token.safeTransfer(addr, _amount), ERROR_TOKEN_TRANSFER_FAILED);
emit TokenWithdrawal(_token, addr, _amount);
}
function unlockedBalanceOf(address _addr) public view returns (uint256) {
Account storage account = accounts[_addr];
return account.balances[jurorToken].sub(account.atStakeTokens);
}
function _processJurorQueues(uint64 _prevTermId, Term storage _incomingTerm) internal {
// Always process egress before updates
// If a juror update is scheduled for the same term, it will get settled processing its exit
_processEgressQueue(_incomingTerm, _prevTermId);
_processUpdateQueue(_incomingTerm);
}
function _processEgressQueue(Term storage _incomingTerm, uint64 _prevTermId) internal {
uint256 length = _incomingTerm.egressQueue.length;
for (uint256 i = 0; i < length; i++) {
address juror = _incomingTerm.egressQueue[i];
Account storage account = accounts[juror];
uint256 sumTreeId = account.sumTreeId;
uint256 treeBalance = sumTree.getItem(sumTreeId);
// Juror has their update in this term or in the future
// settle immediately and remove from updates queue
AccountUpdate storage futureUpdate = account.update;
if (futureUpdate.term >= _prevTermId) {
if (futureUpdate.positive) {
treeBalance = treeBalance + futureUpdate.delta;
} else {
treeBalance = treeBalance - futureUpdate.delta;
}
terms[futureUpdate.term].updateQueue.deleteItem(juror);
}
sumTree.set(sumTreeId, 0);
account.balances[jurorToken] += treeBalance;
account.state = AccountState.PastJuror;
delete account.update;
delete account.sumTreeId;
}
if (length > 0) {
delete _incomingTerm.egressQueue;
}
}
function _processUpdateQueue(Term storage _incomingTerm) internal {
uint256 length = _incomingTerm.updateQueue.length;
for (uint256 i = 0; i < length; i++) {
Account storage account = accounts[_incomingTerm.updateQueue[i]];
AccountUpdate storage update = account.update;
if (update.delta > 0) {
sumTree.update(account.sumTreeId, update.delta, update.positive);
delete account.update;
}
}
if (length > 0) {
delete _incomingTerm.updateQueue;
}
}
function _stake(address _from, address _to, uint256 _amount) internal {
require(_amount > 0, ERROR_ZERO_TRANSFER);
require(jurorToken.safeTransferFrom(_from, this, _amount), ERROR_DEPOSIT_FAILED);
accounts[_to].balances[jurorToken] += _amount;
emit Staked(_to, _amount, totalStakedFor(_to), "");
}
function _assignTokens(ERC20 _token, address _to, uint256 _amount) internal {
accounts[_to].balances[_token] += _amount;
emit TokenBalanceChange(_token, _to, _amount, true);
}
function _setCourtConfig(
uint64 _fromTerm,
ERC20 _feeToken,
uint256 _jurorFee,
uint256 _heartbeatFee,
uint256 _draftFee,
uint16 _governanceFeeShare,
uint64 _commitTerms,
uint64 _revealTerms,
uint64 _appealTerms,
uint16 _penaltyPct
) internal {
// TODO: Require config changes happening at least X terms in the future
// Where X is the amount of terms in the future a dispute can be scheduled to be drafted at
require(configChangeTerm > term || term == ZERO_TERM, ERROR_PAST_TERM_FEE_CHANGE);
require(_governanceFeeShare <= PCT_BASE, ERROR_GOVENANCE_FEE_TOO_HIGH);
require(_commitTerms > 0, ERROR_CONFIG_PERIOD_ZERO_TERMS);
require(_revealTerms > 0, ERROR_CONFIG_PERIOD_ZERO_TERMS);
require(_appealTerms > 0, ERROR_CONFIG_PERIOD_ZERO_TERMS);
if (configChangeTerm != ZERO_TERM) {
terms[configChangeTerm].courtConfigId = 0; // reset previously set fee structure change
}
CourtConfig memory courtConfig = CourtConfig({
feeToken: _feeToken,
governanceFeeShare: _governanceFeeShare,
jurorFee: _jurorFee,
heartbeatFee: _heartbeatFee,
draftFee: _draftFee,
commitTerms: _commitTerms,
revealTerms: _revealTerms,
appealTerms: _appealTerms,
penaltyPct: _penaltyPct
});
uint64 courtConfigId = uint64(courtConfigs.push(courtConfig) - 1);
terms[configChangeTerm].courtConfigId = courtConfigId;
configChangeTerm = _fromTerm;
emit NewCourtConfig(_fromTerm, courtConfigId);
}
function time() internal view returns (uint64) {
return uint64(block.timestamp);
}
function blockNumber() internal view returns (uint64) {
return uint64(block.number);
}
function _pct4(uint256 _number, uint16 _pct) internal pure returns (uint256) {
return _number * uint256(_pct) / uint256(PCT_BASE);
}
}