@reality.eth/contracts 3.0.80 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,990 @@
1
+ // SPDX-License-Identifier: GPL-3.0-only
2
+
3
+ pragma solidity ^0.8.6;
4
+
5
+ contract BalanceHolder {
6
+
7
+ mapping(address => uint256) public balanceOf;
8
+
9
+ event LogWithdraw(
10
+ address indexed user,
11
+ uint256 amount
12
+ );
13
+
14
+ function withdraw()
15
+ public {
16
+ uint256 bal = balanceOf[msg.sender];
17
+ balanceOf[msg.sender] = 0;
18
+ payable(msg.sender).transfer(bal);
19
+ emit LogWithdraw(msg.sender, bal);
20
+ }
21
+
22
+ }
23
+
24
+ contract RealityETH_v3_2 is BalanceHolder {
25
+
26
+ address constant NULL_ADDRESS = address(0);
27
+
28
+ // History hash when no history is created, or history has been cleared
29
+ bytes32 constant NULL_HASH = bytes32(0);
30
+
31
+ // An unitinalized finalize_ts for a question will indicate an unanswered question.
32
+ uint32 constant UNANSWERED = 0;
33
+
34
+ // An unanswered reveal_ts for a commitment will indicate that it does not exist.
35
+ uint256 constant COMMITMENT_NON_EXISTENT = 0;
36
+
37
+ // Commit->reveal timeout is 1/8 of the question timeout (rounded down).
38
+ uint32 constant COMMITMENT_TIMEOUT_RATIO = 8;
39
+
40
+ // Proportion withheld when you claim an earlier bond.
41
+ uint256 constant BOND_CLAIM_FEE_PROPORTION = 40; // One 40th ie 2.5%
42
+
43
+ // Special value representing a question that was answered too soon.
44
+ // bytes32(-2). By convention we use bytes32(-1) for "invalid", although the contract does not handle this.
45
+ bytes32 constant UNRESOLVED_ANSWER = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe;
46
+
47
+ event LogSetQuestionFee(
48
+ address arbitrator,
49
+ uint256 amount
50
+ );
51
+
52
+ event LogNewTemplate(
53
+ uint256 indexed template_id,
54
+ address indexed user,
55
+ string question_text
56
+ );
57
+
58
+ event LogNewQuestion(
59
+ bytes32 indexed question_id,
60
+ address indexed user,
61
+ uint256 template_id,
62
+ string question,
63
+ bytes32 indexed content_hash,
64
+ address arbitrator,
65
+ uint32 timeout,
66
+ uint32 opening_ts,
67
+ uint256 nonce,
68
+ uint256 created
69
+ );
70
+
71
+ event LogMinimumBond(
72
+ bytes32 indexed question_id,
73
+ uint256 min_bond
74
+ );
75
+
76
+ event LogFundAnswerBounty(
77
+ bytes32 indexed question_id,
78
+ uint256 bounty_added,
79
+ uint256 bounty,
80
+ address indexed user
81
+ );
82
+
83
+ event LogNewAnswer(
84
+ bytes32 answer,
85
+ bytes32 indexed question_id,
86
+ bytes32 history_hash,
87
+ address indexed user,
88
+ uint256 bond,
89
+ uint256 ts,
90
+ bool is_commitment
91
+ );
92
+
93
+ event LogAnswerReveal(
94
+ bytes32 indexed question_id,
95
+ address indexed user,
96
+ bytes32 indexed answer_hash,
97
+ bytes32 answer,
98
+ uint256 nonce,
99
+ uint256 bond
100
+ );
101
+
102
+ event LogNotifyOfArbitrationRequest(
103
+ bytes32 indexed question_id,
104
+ address indexed user
105
+ );
106
+
107
+ event LogCancelArbitration(
108
+ bytes32 indexed question_id
109
+ );
110
+
111
+ event LogFinalize(
112
+ bytes32 indexed question_id,
113
+ bytes32 indexed answer
114
+ );
115
+
116
+ event LogClaim(
117
+ bytes32 indexed question_id,
118
+ address indexed user,
119
+ uint256 amount
120
+ );
121
+
122
+ event LogReopenQuestion(
123
+ bytes32 indexed question_id,
124
+ bytes32 indexed reopened_question_id
125
+ );
126
+
127
+ struct Question {
128
+ bytes32 content_hash;
129
+ address arbitrator;
130
+ uint32 opening_ts;
131
+ uint32 timeout;
132
+ uint32 finalize_ts;
133
+ bool is_pending_arbitration;
134
+ uint256 bounty;
135
+ bytes32 best_answer;
136
+ bytes32 history_hash;
137
+ uint256 bond;
138
+ uint256 min_bond;
139
+ }
140
+
141
+ // Stored in a mapping indexed by commitment_id, a hash of commitment hash, question, bond.
142
+ struct Commitment {
143
+ uint32 reveal_ts;
144
+ bool is_revealed;
145
+ bytes32 revealed_answer;
146
+ }
147
+
148
+ // Only used when claiming more bonds than fits into a transaction
149
+ // Stored in a mapping indexed by question_id.
150
+ struct Claim {
151
+ address payee;
152
+ uint256 last_bond;
153
+ uint256 queued_funds;
154
+ }
155
+
156
+ uint256 nextTemplateID = 0;
157
+ mapping(uint256 => uint256) public templates;
158
+ mapping(uint256 => bytes32) public template_hashes;
159
+ mapping(bytes32 => Question) public questions;
160
+ mapping(bytes32 => Claim) public question_claims;
161
+ mapping(bytes32 => Commitment) public commitments;
162
+ mapping(address => uint256) public arbitrator_question_fees;
163
+ mapping(bytes32 => bytes32) public reopened_questions;
164
+ mapping(bytes32 => bool) public reopener_questions;
165
+
166
+
167
+ modifier onlyArbitrator(bytes32 question_id) {
168
+ require(msg.sender == questions[question_id].arbitrator, "msg.sender must be arbitrator");
169
+ _;
170
+ }
171
+
172
+ modifier stateAny() {
173
+ _;
174
+ }
175
+
176
+ modifier stateNotCreated(bytes32 question_id) {
177
+ require(questions[question_id].timeout == 0, "question must not exist");
178
+ _;
179
+ }
180
+
181
+ modifier stateOpen(bytes32 question_id) {
182
+ require(questions[question_id].timeout > 0, "question must exist");
183
+ require(!questions[question_id].is_pending_arbitration, "question must not be pending arbitration");
184
+ uint32 finalize_ts = questions[question_id].finalize_ts;
185
+ require(finalize_ts == UNANSWERED || finalize_ts > uint32(block.timestamp), "finalization deadline must not have passed");
186
+ uint32 opening_ts = questions[question_id].opening_ts;
187
+ require(opening_ts == 0 || opening_ts <= uint32(block.timestamp), "opening date must have passed");
188
+ _;
189
+ }
190
+
191
+ modifier statePendingArbitration(bytes32 question_id) {
192
+ require(questions[question_id].is_pending_arbitration, "question must be pending arbitration");
193
+ _;
194
+ }
195
+
196
+ modifier stateOpenOrPendingArbitration(bytes32 question_id) {
197
+ require(questions[question_id].timeout > 0, "question must exist");
198
+ uint32 finalize_ts = questions[question_id].finalize_ts;
199
+ require(finalize_ts == UNANSWERED || finalize_ts > uint32(block.timestamp), "finalization dealine must not have passed");
200
+ uint32 opening_ts = questions[question_id].opening_ts;
201
+ require(opening_ts == 0 || opening_ts <= uint32(block.timestamp), "opening date must have passed");
202
+ _;
203
+ }
204
+
205
+ modifier stateFinalized(bytes32 question_id) {
206
+ require(isFinalized(question_id), "question must be finalized");
207
+ _;
208
+ }
209
+
210
+ modifier bondMustDoubleAndMatchMinimum(bytes32 question_id) {
211
+ require(msg.value > 0, "bond must be positive");
212
+ uint256 current_bond = questions[question_id].bond;
213
+ if (current_bond == 0) {
214
+ require(msg.value >= (questions[question_id].min_bond), "bond must exceed the minimum");
215
+ } else {
216
+ require(msg.value >= (current_bond * 2), "bond must be double at least previous bond");
217
+ }
218
+ _;
219
+ }
220
+
221
+ modifier previousBondMustNotBeatMaxPrevious(bytes32 question_id, uint256 max_previous) {
222
+ if (max_previous > 0) {
223
+ require(questions[question_id].bond <= max_previous, "bond must exceed max_previous");
224
+ }
225
+ _;
226
+ }
227
+
228
+ /// @notice Constructor, sets up some initial templates
229
+ /// @dev Creates some generalized templates for different question types used in the DApp.
230
+ constructor() {
231
+ createTemplate('{"title": "%s", "type": "bool", "description": "%s", "lang": "%s"}');
232
+ createTemplate('{"title": "%s", "type": "uint", "decimals": 18, "description": "%s", "lang": "%s"}');
233
+ createTemplate('{"title": "%s", "type": "single-select", "outcomes": [%s], "description": "%s", "lang": "%s"}');
234
+ createTemplate('{"title": "%s", "type": "multiple-select", "outcomes": [%s], "description": "%s", "lang": "%s"}');
235
+ createTemplate('{"title": "%s", "type": "datetime", "description": "%s", "lang": "%s"}');
236
+ createTemplate('{"title": "%s", "type": "hash", "description": "%s", "lang": "%s"}');
237
+ }
238
+
239
+ /// @notice Function for arbitrator to set an optional per-question fee.
240
+ /// @dev The per-question fee, charged when a question is asked, is intended as an anti-spam measure.
241
+ /// @param fee The fee to be charged by the arbitrator when a question is asked
242
+ function setQuestionFee(uint256 fee)
243
+ stateAny()
244
+ external {
245
+ arbitrator_question_fees[msg.sender] = fee;
246
+ emit LogSetQuestionFee(msg.sender, fee);
247
+ }
248
+
249
+ /// @notice Create a reusable template, which should be a JSON document.
250
+ /// Placeholders should use gettext() syntax, eg %s.
251
+ /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
252
+ /// @param content The template content
253
+ /// @return The ID of the newly-created template, which is created sequentially.
254
+ function createTemplate(string memory content)
255
+ stateAny()
256
+ public returns (uint256) {
257
+ uint256 id = nextTemplateID;
258
+ templates[id] = block.number;
259
+ template_hashes[id] = keccak256(abi.encodePacked(content));
260
+ emit LogNewTemplate(id, msg.sender, content);
261
+ nextTemplateID = id + 1;
262
+ return id;
263
+ }
264
+
265
+ /// @notice Create a new reusable template and use it to ask a question
266
+ /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
267
+ /// @param content The template content
268
+ /// @param question A string containing the parameters that will be passed into the template to make the question
269
+ /// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
270
+ /// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
271
+ /// @param opening_ts If set, the earliest time it should be possible to answer the question.
272
+ /// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
273
+ /// @return The ID of the newly-created template, which is created sequentially.
274
+ function createTemplateAndAskQuestion(
275
+ string memory content,
276
+ string memory question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce
277
+ )
278
+ // stateNotCreated is enforced by the internal _askQuestion
279
+ public payable returns (bytes32) {
280
+ uint256 template_id = createTemplate(content);
281
+ return askQuestion(template_id, question, arbitrator, timeout, opening_ts, nonce);
282
+ }
283
+
284
+ /// @notice Ask a new question and return the ID
285
+ /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
286
+ /// @param template_id The ID number of the template the question will use
287
+ /// @param question A string containing the parameters that will be passed into the template to make the question
288
+ /// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
289
+ /// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
290
+ /// @param opening_ts If set, the earliest time it should be possible to answer the question.
291
+ /// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
292
+ /// @return The ID of the newly-created question, created deterministically.
293
+ function askQuestion(uint256 template_id, string memory question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce)
294
+ // stateNotCreated is enforced by the internal _askQuestion
295
+ public payable returns (bytes32) {
296
+
297
+ require(templates[template_id] > 0, "template must exist");
298
+
299
+ bytes32 content_hash = keccak256(abi.encodePacked(template_id, opening_ts, question));
300
+ bytes32 question_id = keccak256(abi.encodePacked(content_hash, arbitrator, timeout, uint256(0), address(this), msg.sender, nonce));
301
+
302
+ // We emit this event here because _askQuestion doesn't need to know the unhashed question. Other events are emitted by _askQuestion.
303
+ emit LogNewQuestion(question_id, msg.sender, template_id, question, content_hash, arbitrator, timeout, opening_ts, nonce, block.timestamp);
304
+ _askQuestion(question_id, content_hash, arbitrator, timeout, opening_ts, 0);
305
+
306
+ return question_id;
307
+ }
308
+
309
+ /// @notice Ask a new question and return the ID
310
+ /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
311
+ /// @param template_id The ID number of the template the question will use
312
+ /// @param question A string containing the parameters that will be passed into the template to make the question
313
+ /// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
314
+ /// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
315
+ /// @param opening_ts If set, the earliest time it should be possible to answer the question.
316
+ /// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
317
+ /// @param min_bond The minimum bond that may be used for an answer.
318
+ /// @return The ID of the newly-created question, created deterministically.
319
+ function askQuestionWithMinBond(uint256 template_id, string memory question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce, uint256 min_bond)
320
+ // stateNotCreated is enforced by the internal _askQuestion
321
+ public payable returns (bytes32) {
322
+
323
+ require(templates[template_id] > 0, "template must exist");
324
+
325
+ bytes32 content_hash = keccak256(abi.encodePacked(template_id, opening_ts, question));
326
+ bytes32 question_id = keccak256(abi.encodePacked(content_hash, arbitrator, timeout, min_bond, address(this), msg.sender, nonce));
327
+
328
+ // We emit this event here because _askQuestion doesn't need to know the unhashed question.
329
+ // Other events are emitted by _askQuestion.
330
+ emit LogNewQuestion(question_id, msg.sender, template_id, question, content_hash, arbitrator, timeout, opening_ts, nonce, block.timestamp);
331
+ _askQuestion(question_id, content_hash, arbitrator, timeout, opening_ts, min_bond);
332
+
333
+ return question_id;
334
+ }
335
+
336
+ function _askQuestion(bytes32 question_id, bytes32 content_hash, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 min_bond)
337
+ stateNotCreated(question_id)
338
+ internal {
339
+
340
+ // A timeout of 0 makes no sense, and we will use this to check existence
341
+ require(timeout > 0, "timeout must be positive");
342
+ require(timeout < 365 days, "timeout must be less than 365 days");
343
+
344
+ uint256 bounty = msg.value;
345
+
346
+ // The arbitrator can set a fee for asking a question.
347
+ // This is intended as an anti-spam defence.
348
+ // The fee is waived if the arbitrator is asking the question.
349
+ // This allows them to set an impossibly high fee and make users proxy the question through them.
350
+ // This would allow more sophisticated pricing, question whitelisting etc.
351
+ if (arbitrator != NULL_ADDRESS && msg.sender != arbitrator) {
352
+ uint256 question_fee = arbitrator_question_fees[arbitrator];
353
+ require(bounty >= question_fee, "ETH provided must cover question fee");
354
+ bounty = bounty - question_fee;
355
+ balanceOf[arbitrator] = balanceOf[arbitrator] + question_fee;
356
+ }
357
+
358
+ questions[question_id].content_hash = content_hash;
359
+ questions[question_id].arbitrator = arbitrator;
360
+ questions[question_id].opening_ts = opening_ts;
361
+ questions[question_id].timeout = timeout;
362
+
363
+ if (bounty > 0) {
364
+ questions[question_id].bounty = bounty;
365
+ emit LogFundAnswerBounty(question_id, bounty, bounty, msg.sender);
366
+ }
367
+
368
+ if (min_bond > 0) {
369
+ questions[question_id].min_bond = min_bond;
370
+ emit LogMinimumBond(question_id, min_bond);
371
+ }
372
+
373
+ }
374
+
375
+ /// @notice Add funds to the bounty for a question
376
+ /// @dev Add bounty funds after the initial question creation. Can be done any time until the question is finalized.
377
+ /// @param question_id The ID of the question you wish to fund
378
+ function fundAnswerBounty(bytes32 question_id)
379
+ stateOpen(question_id)
380
+ external payable {
381
+ questions[question_id].bounty = questions[question_id].bounty + msg.value;
382
+ emit LogFundAnswerBounty(question_id, msg.value, questions[question_id].bounty, msg.sender);
383
+ }
384
+
385
+ /// @notice Submit an answer for a question.
386
+ /// @dev Adds the answer to the history and updates the current "best" answer.
387
+ /// May be subject to front-running attacks; Substitute submitAnswerCommitment()->submitAnswerReveal() to prevent them.
388
+ /// @param question_id The ID of the question
389
+ /// @param answer The answer, encoded into bytes32
390
+ /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
391
+ function submitAnswer(bytes32 question_id, bytes32 answer, uint256 max_previous)
392
+ stateOpen(question_id)
393
+ bondMustDoubleAndMatchMinimum(question_id)
394
+ previousBondMustNotBeatMaxPrevious(question_id, max_previous)
395
+ external payable {
396
+ _addAnswerToHistory(question_id, answer, msg.sender, msg.value, false);
397
+ _updateCurrentAnswer(question_id, answer);
398
+ }
399
+
400
+ /// @notice Submit an answer for a question, crediting it to the specified account.
401
+ /// @dev Adds the answer to the history and updates the current "best" answer.
402
+ /// May be subject to front-running attacks; Substitute submitAnswerCommitment()->submitAnswerReveal() to prevent them.
403
+ /// @param question_id The ID of the question
404
+ /// @param answer The answer, encoded into bytes32
405
+ /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
406
+ /// @param answerer The account to which the answer should be credited
407
+ function submitAnswerFor(bytes32 question_id, bytes32 answer, uint256 max_previous, address answerer)
408
+ stateOpen(question_id)
409
+ bondMustDoubleAndMatchMinimum(question_id)
410
+ previousBondMustNotBeatMaxPrevious(question_id, max_previous)
411
+ external payable {
412
+ require(answerer != NULL_ADDRESS, "answerer must be non-zero");
413
+ _addAnswerToHistory(question_id, answer, answerer, msg.value, false);
414
+ _updateCurrentAnswer(question_id, answer);
415
+ }
416
+
417
+ // @notice Verify and store a commitment, including an appropriate timeout
418
+ // @param question_id The ID of the question to store
419
+ // @param commitment The ID of the commitment
420
+ function _storeCommitment(bytes32 question_id, bytes32 commitment_id)
421
+ internal
422
+ {
423
+ require(commitments[commitment_id].reveal_ts == COMMITMENT_NON_EXISTENT, "commitment must not already exist");
424
+
425
+ uint32 commitment_timeout = questions[question_id].timeout / COMMITMENT_TIMEOUT_RATIO;
426
+ commitments[commitment_id].reveal_ts = uint32(block.timestamp) + commitment_timeout;
427
+ }
428
+
429
+ /// @notice Submit the hash of an answer, laying your claim to that answer if you reveal it in a subsequent transaction.
430
+ /// @dev Creates a hash, commitment_id, uniquely identifying this answer, to this question, with this bond.
431
+ /// The commitment_id is stored in the answer history where the answer would normally go.
432
+ /// Does not update the current best answer - this is left to the later submitAnswerReveal() transaction.
433
+ /// @param question_id The ID of the question
434
+ /// @param answer_hash The hash of your answer, plus a nonce that you will later reveal
435
+ /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
436
+ /// @param _answerer If specified, the address to be given as the question answerer. Defaults to the sender.
437
+ /// @dev Specifying the answerer is useful if you want to delegate the commit-and-reveal to a third-party.
438
+ function submitAnswerCommitment(bytes32 question_id, bytes32 answer_hash, uint256 max_previous, address _answerer)
439
+ stateOpen(question_id)
440
+ bondMustDoubleAndMatchMinimum(question_id)
441
+ previousBondMustNotBeatMaxPrevious(question_id, max_previous)
442
+ external payable {
443
+
444
+ bytes32 commitment_id = keccak256(abi.encodePacked(question_id, answer_hash, msg.value));
445
+ address answerer = (_answerer == NULL_ADDRESS) ? msg.sender : _answerer;
446
+ _storeCommitment(question_id, commitment_id);
447
+ _addAnswerToHistory(question_id, commitment_id, answerer, msg.value, true);
448
+
449
+ }
450
+
451
+ /// @notice Submit the answer whose hash you sent in a previous submitAnswerCommitment() transaction
452
+ /// @dev Checks the parameters supplied recreate an existing commitment, and stores the revealed answer
453
+ /// Updates the current answer unless someone has since supplied a new answer with a higher bond
454
+ /// msg.sender is intentionally not restricted to the user who originally sent the commitment;
455
+ /// For example, the user may want to provide the answer+nonce to a third-party service and let them send the tx
456
+ /// NB If we are pending arbitration, it will be up to the arbitrator to wait and see any outstanding reveal is sent
457
+ /// @param question_id The ID of the question
458
+ /// @param answer The answer, encoded as bytes32
459
+ /// @param nonce The nonce that, combined with the answer, recreates the answer_hash you gave in submitAnswerCommitment()
460
+ /// @param bond The bond that you paid in your submitAnswerCommitment() transaction
461
+ function submitAnswerReveal(bytes32 question_id, bytes32 answer, uint256 nonce, uint256 bond)
462
+ stateOpenOrPendingArbitration(question_id)
463
+ external {
464
+
465
+ bytes32 answer_hash = keccak256(abi.encodePacked(answer, nonce));
466
+ bytes32 commitment_id = keccak256(abi.encodePacked(question_id, answer_hash, bond));
467
+
468
+ require(!commitments[commitment_id].is_revealed, "commitment must not have been revealed yet");
469
+ require(commitments[commitment_id].reveal_ts > uint32(block.timestamp), "reveal deadline must not have passed");
470
+
471
+ commitments[commitment_id].revealed_answer = answer;
472
+ commitments[commitment_id].is_revealed = true;
473
+
474
+ if (bond == questions[question_id].bond) {
475
+ _updateCurrentAnswer(question_id, answer);
476
+ }
477
+
478
+ emit LogAnswerReveal(question_id, msg.sender, answer_hash, answer, nonce, bond);
479
+
480
+ }
481
+
482
+ function _addAnswerToHistory(bytes32 question_id, bytes32 answer_or_commitment_id, address answerer, uint256 bond, bool is_commitment)
483
+ internal
484
+ {
485
+ bytes32 new_history_hash = keccak256(abi.encodePacked(questions[question_id].history_hash, answer_or_commitment_id, bond, answerer, is_commitment));
486
+
487
+ // Update the current bond level, if there's a bond (ie anything except arbitration)
488
+ if (bond > 0) {
489
+ questions[question_id].bond = bond;
490
+ }
491
+ questions[question_id].history_hash = new_history_hash;
492
+
493
+ emit LogNewAnswer(answer_or_commitment_id, question_id, new_history_hash, answerer, bond, block.timestamp, is_commitment);
494
+ }
495
+
496
+ function _updateCurrentAnswer(bytes32 question_id, bytes32 answer)
497
+ internal {
498
+ questions[question_id].best_answer = answer;
499
+ questions[question_id].finalize_ts = uint32(block.timestamp) + questions[question_id].timeout;
500
+ }
501
+
502
+ // Like _updateCurrentAnswer but without advancing the timeout
503
+ function _updateCurrentAnswerByArbitrator(bytes32 question_id, bytes32 answer)
504
+ internal {
505
+ questions[question_id].best_answer = answer;
506
+ questions[question_id].finalize_ts = uint32(block.timestamp);
507
+ }
508
+
509
+ /// @notice Notify the contract that the arbitrator has been paid for a question, freezing it pending their decision.
510
+ /// @dev The arbitrator contract is trusted to only call this if they've been paid, and tell us who paid them.
511
+ /// @param question_id The ID of the question
512
+ /// @param requester The account that requested arbitration
513
+ /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
514
+ function notifyOfArbitrationRequest(bytes32 question_id, address requester, uint256 max_previous)
515
+ onlyArbitrator(question_id)
516
+ stateOpen(question_id)
517
+ previousBondMustNotBeatMaxPrevious(question_id, max_previous)
518
+ external {
519
+ require(questions[question_id].finalize_ts > UNANSWERED, "Question must already have an answer when arbitration is requested");
520
+ questions[question_id].is_pending_arbitration = true;
521
+ emit LogNotifyOfArbitrationRequest(question_id, requester);
522
+ }
523
+
524
+ /// @notice Cancel a previously-requested arbitration and extend the timeout
525
+ /// @dev Useful when doing arbitration across chains that can't be requested atomically
526
+ /// @param question_id The ID of the question
527
+ function cancelArbitration(bytes32 question_id)
528
+ onlyArbitrator(question_id)
529
+ statePendingArbitration(question_id)
530
+ external {
531
+ questions[question_id].is_pending_arbitration = false;
532
+ questions[question_id].finalize_ts = uint32(block.timestamp) + questions[question_id].timeout;
533
+ emit LogCancelArbitration(question_id);
534
+ }
535
+
536
+ /// @notice Submit the answer for a question, for use by the arbitrator.
537
+ /// @dev Doesn't require (or allow) a bond.
538
+ /// If the current final answer is correct, the account should be whoever submitted it.
539
+ /// If the current final answer is wrong, the account should be whoever paid for arbitration.
540
+ /// However, the answerer stipulations are not enforced by the contract.
541
+ /// @param question_id The ID of the question
542
+ /// @param answer The answer, encoded into bytes32
543
+ /// @param answerer The account credited with this answer for the purpose of bond claims
544
+ function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer)
545
+ onlyArbitrator(question_id)
546
+ statePendingArbitration(question_id)
547
+ public {
548
+
549
+ require(answerer != NULL_ADDRESS, "answerer must be provided");
550
+ emit LogFinalize(question_id, answer);
551
+
552
+ questions[question_id].is_pending_arbitration = false;
553
+ _addAnswerToHistory(question_id, answer, answerer, 0, false);
554
+ _updateCurrentAnswerByArbitrator(question_id, answer);
555
+
556
+ }
557
+
558
+ /// @notice Submit the answer for a question, for use by the arbitrator, working out the appropriate winner based on the last answer details.
559
+ /// @dev Doesn't require (or allow) a bond.
560
+ /// @param question_id The ID of the question
561
+ /// @param answer The answer, encoded into bytes32
562
+ /// @param payee_if_wrong The account to by credited as winner if the last answer given is wrong, usually the account that paid the arbitrator
563
+ /// @param last_history_hash The history hash before the final one
564
+ /// @param last_answer_or_commitment_id The last answer given, or the commitment ID if it was a commitment.
565
+ /// @param last_answerer The address that supplied the last answer
566
+ function assignWinnerAndSubmitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address payee_if_wrong, bytes32 last_history_hash, bytes32 last_answer_or_commitment_id, address last_answerer)
567
+ external {
568
+ bool is_commitment = _verifyHistoryInputOrRevert(questions[question_id].history_hash, last_history_hash, last_answer_or_commitment_id, questions[question_id].bond, last_answerer);
569
+
570
+ address payee;
571
+ // If the last answer is an unrevealed commit, it's always wrong.
572
+ // For anything else, the last answer was set as the "best answer" in submitAnswer or submitAnswerReveal.
573
+ if (is_commitment && !commitments[last_answer_or_commitment_id].is_revealed) {
574
+ require(commitments[last_answer_or_commitment_id].reveal_ts < uint32(block.timestamp), "You must wait for the reveal deadline before finalizing");
575
+ payee = payee_if_wrong;
576
+ } else {
577
+ payee = (questions[question_id].best_answer == answer) ? last_answerer : payee_if_wrong;
578
+ }
579
+ submitAnswerByArbitrator(question_id, answer, payee);
580
+ }
581
+
582
+
583
+ /// @notice Report whether the answer to the specified question is finalized
584
+ /// @param question_id The ID of the question
585
+ /// @return Return true if finalized
586
+ function isFinalized(bytes32 question_id)
587
+ view public returns (bool) {
588
+ uint32 finalize_ts = questions[question_id].finalize_ts;
589
+ return ( !questions[question_id].is_pending_arbitration && (finalize_ts > UNANSWERED) && (finalize_ts <= uint32(block.timestamp)) );
590
+ }
591
+
592
+ /// @notice (Deprecated) Return the final answer to the specified question, or revert if there isn't one
593
+ /// @param question_id The ID of the question
594
+ /// @return The answer formatted as a bytes32
595
+ function getFinalAnswer(bytes32 question_id)
596
+ stateFinalized(question_id)
597
+ external view returns (bytes32) {
598
+ return questions[question_id].best_answer;
599
+ }
600
+
601
+ /// @notice Return the final answer to the specified question, or revert if there isn't one
602
+ /// @param question_id The ID of the question
603
+ /// @return The answer formatted as a bytes32
604
+ function resultFor(bytes32 question_id)
605
+ stateFinalized(question_id)
606
+ public view returns (bytes32) {
607
+ return questions[question_id].best_answer;
608
+ }
609
+
610
+ /// @notice Returns whether the question was answered before it had an answer, ie resolved to UNRESOLVED_ANSWER
611
+ /// @param question_id The ID of the question
612
+ function isSettledTooSoon(bytes32 question_id)
613
+ public view returns(bool) {
614
+ return (resultFor(question_id) == UNRESOLVED_ANSWER);
615
+ }
616
+
617
+ /// @notice Like resultFor(), but errors out if settled too soon, or returns the result of a replacement if it was reopened at the right time and settled
618
+ /// @param question_id The ID of the question
619
+ function resultForOnceSettled(bytes32 question_id)
620
+ external view returns(bytes32) {
621
+ bytes32 result = resultFor(question_id);
622
+ if (result == UNRESOLVED_ANSWER) {
623
+ // Try the replacement
624
+ bytes32 replacement_id = reopened_questions[question_id];
625
+ require(replacement_id != bytes32(0x0), "Question was settled too soon and has not been reopened");
626
+ // We only try one layer down rather than recursing to keep the gas costs predictable
627
+ result = resultFor(replacement_id);
628
+ require(result != UNRESOLVED_ANSWER, "Question replacement was settled too soon and has not been reopened");
629
+ }
630
+ return result;
631
+ }
632
+
633
+ /// @notice Asks a new question reopening a previously-asked question that was settled too soon
634
+ /// @dev A special version of askQuestion() that replaces a previous question that was settled too soon
635
+ /// @param template_id The ID number of the template the question will use
636
+ /// @param question A string containing the parameters that will be passed into the template to make the question
637
+ /// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
638
+ /// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
639
+ /// @param opening_ts If set, the earliest time it should be possible to answer the question.
640
+ /// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
641
+ /// @param min_bond The minimum bond that can be used to provide the first answer.
642
+ /// @param reopens_question_id The ID of the question this reopens
643
+ /// @return The ID of the newly-created question, created deterministically.
644
+ function reopenQuestion(uint256 template_id, string memory question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce, uint256 min_bond, bytes32 reopens_question_id)
645
+ // stateNotCreated is enforced by the internal _askQuestion
646
+ public payable returns (bytes32) {
647
+
648
+ require(isSettledTooSoon(reopens_question_id), "You can only reopen questions that resolved as settled too soon");
649
+
650
+ bytes32 content_hash = keccak256(abi.encodePacked(template_id, opening_ts, question));
651
+
652
+ // A reopening must exactly match the original question, except for the nonce and the creator
653
+ require(content_hash == questions[reopens_question_id].content_hash, "content hash mismatch");
654
+ require(arbitrator == questions[reopens_question_id].arbitrator, "arbitrator mismatch");
655
+ require(timeout == questions[reopens_question_id].timeout, "timeout mismatch");
656
+ require(opening_ts == questions[reopens_question_id].opening_ts , "opening_ts mismatch");
657
+ require(min_bond == questions[reopens_question_id].min_bond, "min_bond mismatch");
658
+
659
+ // If the the question was itself reopening some previous question, you'll have to re-reopen the previous question first.
660
+ // This ensures the bounty can be passed on to the next attempt of the original question.
661
+ require(!reopener_questions[reopens_question_id], "Question is already reopening a previous question");
662
+
663
+ // A question can only be reopened once, unless the reopening was also settled too soon in which case it can be replaced
664
+ bytes32 existing_reopen_question_id = reopened_questions[reopens_question_id];
665
+
666
+ // Normally when we reopen a question we will take its bounty and pass it on to the reopened version.
667
+ bytes32 take_bounty_from_question_id = reopens_question_id;
668
+ // If the question has already been reopened but was again settled too soon, we can transfer its bounty to the next attempt.
669
+ if (existing_reopen_question_id != bytes32(0)) {
670
+ require(isSettledTooSoon(existing_reopen_question_id), "Question has already been reopened");
671
+ // We'll overwrite the reopening with our new question and move the bounty.
672
+ // Once that's done we'll detach the failed reopener and you'll be able to reopen that too if you really want, but without the bounty.
673
+ reopener_questions[existing_reopen_question_id] = false;
674
+ take_bounty_from_question_id = existing_reopen_question_id;
675
+ }
676
+
677
+ bytes32 question_id = askQuestionWithMinBond(template_id, question, arbitrator, timeout, opening_ts, nonce, min_bond);
678
+
679
+ reopened_questions[reopens_question_id] = question_id;
680
+ reopener_questions[question_id] = true;
681
+
682
+ questions[question_id].bounty = questions[take_bounty_from_question_id].bounty + questions[question_id].bounty;
683
+ questions[take_bounty_from_question_id].bounty = 0;
684
+
685
+ emit LogReopenQuestion(question_id, reopens_question_id);
686
+
687
+ return question_id;
688
+ }
689
+
690
+ /// @notice Return the final answer to the specified question, provided it matches the specified criteria.
691
+ /// @dev Reverts if the question is not finalized, or if it does not match the specified criteria.
692
+ /// @param question_id The ID of the question
693
+ /// @param content_hash The hash of the question content (template ID + opening time + question parameter string)
694
+ /// @param arbitrator The arbitrator chosen for the question (regardless of whether they are asked to arbitrate)
695
+ /// @param min_timeout The timeout set in the initial question settings must be this high or higher
696
+ /// @param min_bond The bond sent with the final answer must be this high or higher
697
+ /// @return The answer formatted as a bytes32
698
+ function getFinalAnswerIfMatches(
699
+ bytes32 question_id,
700
+ bytes32 content_hash, address arbitrator, uint32 min_timeout, uint256 min_bond
701
+ )
702
+ stateFinalized(question_id)
703
+ external view returns (bytes32) {
704
+ require(content_hash == questions[question_id].content_hash, "content hash must match");
705
+ require(arbitrator == questions[question_id].arbitrator, "arbitrator must match");
706
+ require(min_timeout <= questions[question_id].timeout, "timeout must be long enough");
707
+ require(min_bond <= questions[question_id].bond, "bond must be high enough");
708
+ return questions[question_id].best_answer;
709
+ }
710
+
711
+ /// @notice Assigns the winnings (bounty and bonds) to everyone who gave the accepted answer
712
+ /// Caller must provide the answer history, in reverse order
713
+ /// @dev Works up the chain and assign bonds to the person who gave the right answer
714
+ /// If someone gave the winning answer earlier, they must get paid from the higher bond
715
+ /// That means we can't pay out the bond added at n until we have looked at n-1
716
+ /// The first answer is authenticated by checking against the stored history_hash.
717
+ /// One of the inputs to history_hash is the history_hash before it, so we use that to authenticate the next entry, etc
718
+ /// Once we get to a null hash we'll know we're done and there are no more answers.
719
+ /// Usually you would call the whole thing in a single transaction, but if not then the data is persisted to pick up later.
720
+ /// @param question_id The ID of the question
721
+ /// @param history_hashes Second-last-to-first, the hash of each history entry. (Final one should be empty).
722
+ /// @param addrs Last-to-first, the address of each answerer or commitment sender
723
+ /// @param bonds Last-to-first, the bond supplied with each answer or commitment
724
+ /// @param answers Last-to-first, each answer supplied, or commitment ID if the answer was supplied with commit->reveal
725
+ function claimWinnings(
726
+ bytes32 question_id,
727
+ bytes32[] memory history_hashes, address[] memory addrs, uint256[] memory bonds, bytes32[] memory answers
728
+ )
729
+ stateFinalized(question_id)
730
+ public {
731
+
732
+ require(history_hashes.length > 0, "at least one history hash entry must be provided");
733
+
734
+ // These are only set if we split our claim over multiple transactions.
735
+ address payee = question_claims[question_id].payee;
736
+ uint256 last_bond = question_claims[question_id].last_bond;
737
+ uint256 queued_funds = question_claims[question_id].queued_funds;
738
+
739
+ // Starts as the hash of the final answer submitted. It'll be cleared when we're done.
740
+ // If we're splitting the claim over multiple transactions, it'll be the hash where we left off last time
741
+ bytes32 last_history_hash = questions[question_id].history_hash;
742
+
743
+ bytes32 best_answer = questions[question_id].best_answer;
744
+
745
+ uint256 i;
746
+ for (i = 0; i < history_hashes.length; i++) {
747
+
748
+ // Check input against the history hash, and see which of 2 possible values of is_commitment fits.
749
+ bool is_commitment = _verifyHistoryInputOrRevert(last_history_hash, history_hashes[i], answers[i], bonds[i], addrs[i]);
750
+
751
+ queued_funds = queued_funds + last_bond;
752
+ (queued_funds, payee) = _processHistoryItem(
753
+ question_id, best_answer, queued_funds, payee,
754
+ addrs[i], bonds[i], answers[i], is_commitment);
755
+
756
+ // Line the bond up for next time, when it will be added to somebody's queued_funds
757
+ last_bond = bonds[i];
758
+
759
+ // Burn (just leave in contract balance) a fraction of all bonds except the final one.
760
+ // This creates a cost to increasing your own bond, which could be used to delay resolution maliciously
761
+ if (last_bond != questions[question_id].bond) {
762
+ last_bond = last_bond - last_bond / BOND_CLAIM_FEE_PROPORTION;
763
+ }
764
+
765
+ last_history_hash = history_hashes[i];
766
+
767
+ }
768
+
769
+ if (last_history_hash != NULL_HASH) {
770
+ // We haven't yet got to the null hash (1st answer), ie the caller didn't supply the full answer chain.
771
+ // Persist the details so we can pick up later where we left off later.
772
+
773
+ // If we know who to pay we can go ahead and pay them out, only keeping back last_bond
774
+ // (We always know who to pay unless all we saw were unrevealed commits)
775
+ if (payee != NULL_ADDRESS) {
776
+ _payPayee(question_id, payee, queued_funds);
777
+ queued_funds = 0;
778
+ }
779
+
780
+ question_claims[question_id].payee = payee;
781
+ question_claims[question_id].last_bond = last_bond;
782
+ question_claims[question_id].queued_funds = queued_funds;
783
+ } else {
784
+ // There is nothing left below us so the payee can keep what remains
785
+ _payPayee(question_id, payee, queued_funds + last_bond);
786
+ delete question_claims[question_id];
787
+ }
788
+
789
+ questions[question_id].history_hash = last_history_hash;
790
+
791
+ }
792
+
793
+ function _payPayee(bytes32 question_id, address payee, uint256 value)
794
+ internal {
795
+ balanceOf[payee] = balanceOf[payee] + value;
796
+ emit LogClaim(question_id, payee, value);
797
+ }
798
+
799
+ function _verifyHistoryInputOrRevert(
800
+ bytes32 last_history_hash,
801
+ bytes32 history_hash, bytes32 answer, uint256 bond, address addr
802
+ )
803
+ internal pure returns (bool) {
804
+ if (last_history_hash == keccak256(abi.encodePacked(history_hash, answer, bond, addr, true)) ) {
805
+ return true;
806
+ }
807
+ if (last_history_hash == keccak256(abi.encodePacked(history_hash, answer, bond, addr, false)) ) {
808
+ return false;
809
+ }
810
+ revert("History input provided did not match the expected hash");
811
+ }
812
+
813
+ function _processHistoryItem(
814
+ bytes32 question_id, bytes32 best_answer,
815
+ uint256 queued_funds, address payee,
816
+ address addr, uint256 bond, bytes32 answer, bool is_commitment
817
+ )
818
+ internal returns (uint256, address) {
819
+
820
+ // For commit-and-reveal, the answer history holds the commitment ID instead of the answer.
821
+ // We look at the referenced commitment ID and switch in the actual answer.
822
+ if (is_commitment) {
823
+ bytes32 commitment_id = answer;
824
+ // If it's a commit but it hasn't been revealed, it will always be considered wrong.
825
+ if (!commitments[commitment_id].is_revealed) {
826
+ delete commitments[commitment_id];
827
+ return (queued_funds, payee);
828
+ } else {
829
+ answer = commitments[commitment_id].revealed_answer;
830
+ delete commitments[commitment_id];
831
+ }
832
+ }
833
+
834
+ if (answer == best_answer) {
835
+
836
+ if (payee == NULL_ADDRESS) {
837
+
838
+ // The entry is for the first payee we come to, ie the winner.
839
+ // They get the question bounty.
840
+ payee = addr;
841
+
842
+ if (best_answer != UNRESOLVED_ANSWER && questions[question_id].bounty > 0) {
843
+ _payPayee(question_id, payee, questions[question_id].bounty);
844
+ questions[question_id].bounty = 0;
845
+ }
846
+
847
+ } else if (addr != payee) {
848
+
849
+ // Answerer has changed, ie we found someone lower down who needs to be paid
850
+
851
+ // The lower answerer will take over receiving bonds from higher answerer.
852
+ // They should also be paid the takeover fee, which is set at a rate equivalent to their bond.
853
+ // (This is our arbitrary rule, to give consistent right-answerers a defence against high-rollers.)
854
+
855
+ // There should be enough for the fee, but if not, take what we have.
856
+ // There's an edge case involving weird arbitrator behaviour where we may be short.
857
+ uint256 answer_takeover_fee = (queued_funds >= bond) ? bond : queued_funds;
858
+ // Settle up with the old (higher-bonded) payee
859
+ _payPayee(question_id, payee, queued_funds - answer_takeover_fee);
860
+
861
+ // Now start queued_funds again for the new (lower-bonded) payee
862
+ payee = addr;
863
+ queued_funds = answer_takeover_fee;
864
+
865
+ }
866
+
867
+ }
868
+
869
+ return (queued_funds, payee);
870
+
871
+ }
872
+
873
+ /// @notice Convenience function to assign bounties/bonds for multiple questions in one go, then withdraw all your funds.
874
+ /// Caller must provide the answer history for each question, in reverse order
875
+ /// @dev Can be called by anyone to assign bonds/bounties, but funds are only withdrawn for the user making the call.
876
+ /// @param question_ids The IDs of the questions you want to claim for
877
+ /// @param lengths The number of history entries you will supply for each question ID
878
+ /// @param hist_hashes In a single list for all supplied questions, the hash of each history entry.
879
+ /// @param addrs In a single list for all supplied questions, the address of each answerer or commitment sender
880
+ /// @param bonds In a single list for all supplied questions, the bond supplied with each answer or commitment
881
+ /// @param answers In a single list for all supplied questions, each answer supplied, or commitment ID
882
+ function claimMultipleAndWithdrawBalance(
883
+ bytes32[] memory question_ids, uint256[] memory lengths,
884
+ bytes32[] memory hist_hashes, address[] memory addrs, uint256[] memory bonds, bytes32[] memory answers
885
+ )
886
+ stateAny() // The finalization checks are done in the claimWinnings function
887
+ public {
888
+
889
+ uint256 qi;
890
+ uint256 i;
891
+ for (qi = 0; qi < question_ids.length; qi++) {
892
+ bytes32 qid = question_ids[qi];
893
+ uint256 ln = lengths[qi];
894
+ bytes32[] memory hh = new bytes32[](ln);
895
+ address[] memory ad = new address[](ln);
896
+ uint256[] memory bo = new uint256[](ln);
897
+ bytes32[] memory an = new bytes32[](ln);
898
+ uint256 j;
899
+ for (j = 0; j < ln; j++) {
900
+ hh[j] = hist_hashes[i];
901
+ ad[j] = addrs[i];
902
+ bo[j] = bonds[i];
903
+ an[j] = answers[i];
904
+ i++;
905
+ }
906
+ claimWinnings(qid, hh, ad, bo, an);
907
+ }
908
+ withdraw();
909
+ }
910
+
911
+ /// @notice Returns the questions's content hash, identifying the question content
912
+ /// @param question_id The ID of the question
913
+ function getContentHash(bytes32 question_id)
914
+ public view returns(bytes32) {
915
+ return questions[question_id].content_hash;
916
+ }
917
+
918
+ /// @notice Returns the arbitrator address for the question
919
+ /// @param question_id The ID of the question
920
+ function getArbitrator(bytes32 question_id)
921
+ public view returns(address) {
922
+ return questions[question_id].arbitrator;
923
+ }
924
+
925
+ /// @notice Returns the timestamp when the question can first be answered
926
+ /// @param question_id The ID of the question
927
+ function getOpeningTS(bytes32 question_id)
928
+ public view returns(uint32) {
929
+ return questions[question_id].opening_ts;
930
+ }
931
+
932
+ /// @notice Returns the timeout in seconds used after each answer
933
+ /// @param question_id The ID of the question
934
+ function getTimeout(bytes32 question_id)
935
+ public view returns(uint32) {
936
+ return questions[question_id].timeout;
937
+ }
938
+
939
+ /// @notice Returns the timestamp at which the question will be/was finalized
940
+ /// @param question_id The ID of the question
941
+ function getFinalizeTS(bytes32 question_id)
942
+ public view returns(uint32) {
943
+ return questions[question_id].finalize_ts;
944
+ }
945
+
946
+ /// @notice Returns whether the question is pending arbitration
947
+ /// @param question_id The ID of the question
948
+ function isPendingArbitration(bytes32 question_id)
949
+ public view returns(bool) {
950
+ return questions[question_id].is_pending_arbitration;
951
+ }
952
+
953
+ /// @notice Returns the current total unclaimed bounty
954
+ /// @dev Set back to zero once the bounty has been claimed
955
+ /// @param question_id The ID of the question
956
+ function getBounty(bytes32 question_id)
957
+ public view returns(uint256) {
958
+ return questions[question_id].bounty;
959
+ }
960
+
961
+ /// @notice Returns the current best answer
962
+ /// @param question_id The ID of the question
963
+ function getBestAnswer(bytes32 question_id)
964
+ public view returns(bytes32) {
965
+ return questions[question_id].best_answer;
966
+ }
967
+
968
+ /// @notice Returns the history hash of the question
969
+ /// @param question_id The ID of the question
970
+ /// @dev Updated on each answer, then rewound as each is claimed
971
+ function getHistoryHash(bytes32 question_id)
972
+ public view returns(bytes32) {
973
+ return questions[question_id].history_hash;
974
+ }
975
+
976
+ /// @notice Returns the highest bond posted so far for a question
977
+ /// @param question_id The ID of the question
978
+ function getBond(bytes32 question_id)
979
+ public view returns(uint256) {
980
+ return questions[question_id].bond;
981
+ }
982
+
983
+ /// @notice Returns the minimum bond that can answer the question
984
+ /// @param question_id The ID of the question
985
+ function getMinBond(bytes32 question_id)
986
+ public view returns(uint256) {
987
+ return questions[question_id].min_bond;
988
+ }
989
+
990
+ }