forked from qubic/qubic-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquottery.cpp
More file actions
2056 lines (1756 loc) · 68.1 KB
/
Copy pathquottery.cpp
File metadata and controls
2056 lines (1756 loc) · 68.1 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
#include <cinttypes>
#include <cstring>
#include <cstdio>
#include <ctime>
#include "stdint.h"
#include "quottery.h"
#include "prompt.h"
#include "structs.h"
#include "key_utils.h"
#include "node_utils.h"
#include "k12_and_key_utils.h"
#include "connection.h"
#include "logger.h"
#include "wallet_utils.h"
constexpr int QUOTTERY_CONTRACT_ID = 2;
/**
* @return pack DateAndTime data from year, month, day, hour, minute, second, millisec, microsec to a uint64_t
* Bit layout: year(18) | month(4) | day(5) | hour(5) | minute(6) | second(6) | millisec(10) | microsec(10)
*/
static void packDateTime(uint32_t _year, uint32_t _month, uint32_t _day, uint32_t _hour, uint32_t _minute, uint32_t _second, uint32_t _millisec, uint32_t _microsec, uint64_t& res)
{
res = ((uint64_t)_year << 46) | ((uint64_t)_month << 42) | ((uint64_t)_day << 37) | ((uint64_t)_hour << 32)
| ((uint64_t)_minute << 26) | ((uint64_t)_second << 20) | ((uint64_t)_millisec << 10) | (uint64_t)_microsec;
}
#define DATETIME_GET_YEAR(data) ((data >> 46))
#define DATETIME_GET_MONTH(data) ((data >> 42) & 0b1111)
#define DATETIME_GET_DAY(data) ((data >> 37) & 0b11111)
#define DATETIME_GET_HOUR(data) ((data >> 32) & 0b11111)
#define DATETIME_GET_MINUTE(data) ((data >> 26) & 0b111111)
#define DATETIME_GET_SECOND(data) ((data >> 20) & 0b111111)
#define DATETIME_GET_MILLISEC(data) ((data >> 10) & 0b1111111111)
#define DATETIME_GET_MICROSEC(data) ((data) & 0b1111111111)
/**
* @return unpack DateAndTime from uint64 to year, month, day, hour, minute, second, millisec, microsec
*/
void unpackDateTime(uint32_t& _year, uint8_t& _month, uint8_t& _day, uint8_t& _hour, uint8_t& _minute, uint8_t& _second, uint16_t& _millisec, uint16_t& _microsec, uint64_t data)
{
_year = DATETIME_GET_YEAR(data); // 18 bits
_month = DATETIME_GET_MONTH(data); // 4 bits
_day = DATETIME_GET_DAY(data); // 5 bits
_hour = DATETIME_GET_HOUR(data); // 5 bits
_minute = DATETIME_GET_MINUTE(data); // 6 bits
_second = DATETIME_GET_SECOND(data); // 6 bits
_millisec = DATETIME_GET_MILLISEC(data); // 10 bits
_microsec = DATETIME_GET_MICROSEC(data); // 10 bits
}
// QTRY PROCEDURES
#define QTRY_CREATE_EVENT 1
#define QTRY_ADD_ASK_ORDER 2
#define QTRY_REMOVE_ASK_ORDER 3
#define QTRY_ADD_BID_ORDER 4
#define QTRY_REMOVE_BID_ORDER 5
#define QTRY_PUBLISH_RESULT 6
#define QTRY_TRY_FINALIZE_EVENT 7
#define QTRY_DISPUTE 8
#define QTRY_RESOLVE_DISPUTE 9
#define QTRY_USER_CLAIM_REWARD 10
#define QTRY_GO_FORCE_CLAIM_REWARD 11
#define QTRY_TRANSFER_QUSD 12
#define QTRY_TRANSFER_SHARE_MANAGEMENT_RIGHTS 13
#define QTRY_CLEAN_MEMORY 14
#define QTRY_TRANSFER_QTRYGOV 15
#define QTRY_UPDATE_FEE_DISCOUNT_LIST 20
#define QTRY_PROPOSAL_VOTE 100
// QTRY FUNCTIONS
#define QTRY_GET_BASIC 1
#define QTRY_GET_EVENT 2
#define QTRY_GET_ORDERS 3
#define QTRY_GET_ACTIVE_EVENTS 4
#define QTRY_GET_EVENT_BATCH 5
#define QUOTTERY_GET_USER_POSITION 6
#define QTRY_GET_APPROVED_AMOUNT 7
#define QTRY_GET_TOP_PROPOSALS 8
#define QUOTTERY_EO_GET_OPTION(eo) ((eo) >> 63)
#define QUOTTERY_EO_GET_EVENTID(eo) ((eo) & 0x3FFFFFFFFFFFFFFFULL)
static int64_t getBalanceNumber(QCPtr& qc, const uint8_t* publicKey) {
struct {
RequestResponseHeader header;
RequestedEntity req;
} packet;
packet.header.setSize(sizeof(packet));
packet.header.randomizeDejavu();
packet.header.setType(REQUEST_ENTITY);
memcpy(packet.req.publicKey, publicKey, 32);
qc->sendData((uint8_t*)&packet, packet.header.size());
auto result = qc->receivePacketWithHeaderAs<RespondedEntity>();
return result.entity.incomingAmount - result.entity.outgoingAmount;
}
void quotteryGetBasicInfo(QCPtr& qc, qtryBasicInfo_output& result)
{
memset(&result, 0, sizeof(result));
// Note: the QCPtr overload is preserved so we can pass an already-open connection.
// We reuse runContractFunction by extracting nodeIp/nodePort would not be possible here;
// for callers that have only nodeIp/nodePort, prefer quotteryGetBasicInfoByIp().
struct {
RequestResponseHeader header;
RequestContractFunction rcf;
} packet;
packet.header.setSize(sizeof(packet));
packet.header.randomizeDejavu();
packet.header.setType(RequestContractFunction::type());
packet.rcf.inputSize = 0;
packet.rcf.inputType = QTRY_GET_BASIC;
packet.rcf.contractIndex = QUOTTERY_CONTRACT_ID;
qc->sendData((uint8_t*)&packet, packet.header.size());
try
{
result = qc->receivePacketWithHeaderAs<qtryBasicInfo_output>();
}
catch (std::logic_error)
{
memset(&result, 0, sizeof(qtryBasicInfo_output));
}
}
void quotteryPrintBasicInfo(const char* nodeIp, const int nodePort)
{
qtryBasicInfo_output result{};
if (!runContractFunction(nodeIp, nodePort, QUOTTERY_CONTRACT_ID, QTRY_GET_BASIC, nullptr, 0, &result, sizeof(result)))
{
LOG("Failed to get basic info\n");
return;
}
LOG("Operation Fee: %.2f%%\n", result.operationFee / 10.0);
LOG("Shareholders fee: %.2f%%\n", result.shareholderFee / 10.0);
LOG("Burn fee: %.2f%%\n", result.burnFee / 10.0);
LOG("================\n");
LOG("Number of issued events: %" PRIu64 "\n", result.nIssuedEvent);
LOG("Shareholders revenue: %" PRIu64 "\n", result.shareholdersRevenue);
LOG("Operation revenue: %" PRIu64 "\n", result.operationRevenue);
LOG("Burned amount: %" PRIu64 "\n", result.burnedAmount);
LOG("feePerDay: %" PRIu64 "\n", result.feePerDay);
LOG("antiSpamAmount: %" PRIu64 "\n", result.antiSpamAmount);
LOG("depositAmountForDispute: %" PRIu64 "\n", result.depositAmountForDispute);
char buf[64] = { 0 };
getIdentityFromPublicKey(result.gameOperator, buf, false);
LOG("Game operator ID: %s\n", buf);
}
void quotteryGetActiveEvents(const char* nodeIp, int nodePort, getActiveEvent_output& result)
{
memset(&result, 0, sizeof(result));
if (!runContractFunction(nodeIp, nodePort, QUOTTERY_CONTRACT_ID, QTRY_GET_ACTIVE_EVENTS, nullptr, 0, &result, sizeof(result)))
{
memset(&result, 0, sizeof(result));
}
}
void quotteryPrintActiveEvents(const char* nodeIp, int nodePort)
{
getActiveEvent_output result{};
quotteryGetActiveEvents(nodeIp, nodePort, result);
if (isArrayZero(reinterpret_cast<uint8_t*>(&result), sizeof(result)))
{
LOG("Failed to get recent active events\n");
return;
}
LOG("Recent active event IDs:\n");
bool hasAny = false;
for (size_t i = 0; i < QUOTTERY_MAX_CONCURRENT_EVENT; ++i)
{
if (result.recentActiveEvent[i] == uint64_t(-1))
continue;
LOG("%" PRIu64 "\n", result.recentActiveEvent[i]);
hasAny = true;
}
if (!hasAny)
{
LOG("(none)\n");
}
}
#define QTRY_GET_YEAR(data) ((data >> 26)+24)
#define QTRY_GET_MONTH(data) ((data >> 22) & 0b1111)
#define QTRY_GET_DAY(data) ((data >> 17) & 0b11111)
#define QTRY_GET_HOUR(data) ((data >> 12) & 0b11111)
#define QTRY_GET_MINUTE(data) ((data >> 6) & 0b111111)
#define QTRY_GET_SECOND(data) ((data) & 0b111111)
/**
* @return unpack qtry datetime from uin32 to year, month, day, hour, minute, secon
*/
void unpackQuotteryDate(uint8_t& _year, uint8_t& _month, uint8_t& _day, uint8_t& _hour, uint8_t& _minute, uint8_t& _second, uint32_t data)
{
_year = QTRY_GET_YEAR(data); // 6 bits
_month = QTRY_GET_MONTH(data); //4bits
_day = QTRY_GET_DAY(data); //5bits
_hour = QTRY_GET_HOUR(data); //5bits
_minute = QTRY_GET_MINUTE(data); //6bits
_second = QTRY_GET_SECOND(data); //6bits
}
struct QuotteryCreateEvent_input
{
uint64_t eid;
uint64_t openDate; // submitted date
uint64_t endDate; // stop receiving result from OPs
uint8_t desc[128];
uint8_t option0Desc[64];
uint8_t option1Desc[64];
};
void quotteryCreateEvent(const char* nodeIp, int nodePort, const char* seed,
const std::string eventDesc,
const std::string opt0Desc,
const std::string opt1Desc,
const std::string endDate,
uint16_t tagId,
uint32_t scheduledTickOffset)
{
QuotteryCreateEvent_input cei{};
// Copy desc text, but cap at 128 bytes; pack tagId as uint16 LE into desc[126:128]
memcpy(cei.desc, eventDesc.c_str(), std::min(int(eventDesc.size()), 128));
cei.desc[126] = (uint8_t)(tagId & 0xFF);
cei.desc[127] = (uint8_t)((tagId >> 8) & 0xFF);
memcpy(cei.option0Desc, opt0Desc.c_str(), std::min(int(opt0Desc.size()), 64));
memcpy(cei.option1Desc, opt1Desc.c_str(), std::min(int(opt1Desc.size()), 64));
{
auto buff = endDate.data();
if (strlen(buff) != 19 || buff[4] != '-' || buff[7] != '-' || buff[10] != ' ' || buff[13] != ':' ||
buff[16] != ':' ||
!isdigit(buff[0]) || !isdigit(buff[1]) || !isdigit(buff[2]) || !isdigit(buff[3]) ||
!isdigit(buff[5]) || !isdigit(buff[6]) || !isdigit(buff[8]) || !isdigit(buff[9]) ||
!isdigit(buff[11]) || !isdigit(buff[12]) || !isdigit(buff[14]) || !isdigit(buff[15]) ||
!isdigit(buff[17]) || !isdigit(buff[18])) {
LOG("Error: Invalid date-time format. Please follow the format: YYYY-MM-DD hh:mm:ss\n");
exit(EXIT_FAILURE);
}
uint32_t year = (buff[0] - 48) * 1000 + (buff[1] - 48) * 100 + (buff[2] - 48) * 10 + (buff[3] - 48);
uint8_t month = (buff[5] - 48) * 10 + (buff[6] - 48);
uint8_t day = (buff[8] - 48) * 10 + (buff[9] - 48);
uint8_t hour = (buff[11] - 48) * 10 + (buff[12] - 48);
uint8_t minute = (buff[14] - 48) * 10 + (buff[15] - 48);
uint8_t sec = (buff[17] - 48) * 10 + (buff[18] - 48);
packDateTime(year, month, day, hour, minute, sec, 0, 0, cei.endDate);
}
// eid and openDate are set by the SC
cei.eid = 0;
cei.openDate = 0;
LOG("Crafting transaction...\n");
LOG("Tag ID: %u\n", tagId);
makeContractTransaction(nodeIp, nodePort, seed,
QUOTTERY_CONTRACT_ID,
QTRY_CREATE_EVENT,
/*amount=*/0,
sizeof(cei), &cei,
scheduledTickOffset);
}
void _quotteryGetEventInfo(QCPtr& qc, uint64_t eventId, getEventInfo_output& result)
{
// Kept for callers that already hold a QCPtr.
struct {
RequestResponseHeader header;
RequestContractFunction rcf;
getEventInfo_input input;
} packet;
packet.header.setSize(sizeof(packet));
packet.header.randomizeDejavu();
packet.header.setType(RequestContractFunction::type());
packet.rcf.inputSize = sizeof(getEventInfo_input);
packet.rcf.inputType = QTRY_GET_EVENT;
packet.rcf.contractIndex = QUOTTERY_CONTRACT_ID;
packet.input.eventId = eventId;
qc->sendData((uint8_t*)&packet, packet.header.size());
try
{
result = qc->receivePacketWithHeaderAs<getEventInfo_output>();
}
catch (std::logic_error)
{
memset(&result, 0, sizeof(getEventInfo_output));
result.resultByGO = -1;
}
}
void quotteryGetEventInfo(const char* nodeIp, const int nodePort, uint64_t eventId, getEventInfo_output& result)
{
getEventInfo_input input{};
input.eventId = eventId;
memset(&result, 0, sizeof(result));
if (!runContractFunction(nodeIp, nodePort, QUOTTERY_CONTRACT_ID, QTRY_GET_EVENT,
&input, sizeof(input), &result, sizeof(result)))
{
memset(&result, 0, sizeof(result));
result.resultByGO = -1;
}
}
static void quotteryPrintEventMetaData(const QtryEventInfo& result, uint64_t requestedEventId)
{
if (result.eid != requestedEventId)
{
LOG("EventId #%" PRIu64 " doesn't exist\n", requestedEventId);
return;
}
char buf[128] = { 0 };
LOG("Event Id: %" PRIu64 "\n", result.eid);
{
memset(buf, 0, sizeof(buf));
memcpy(buf, result.desc, sizeof(result.desc));
LOG("Event description: %s\n", buf);
}
{
memset(buf, 0, sizeof(buf));
memcpy(buf, result.option0Desc, sizeof(result.option0Desc));
LOG("Option 0: %s\n", buf);
}
{
memset(buf, 0, sizeof(buf));
memcpy(buf, result.option1Desc, sizeof(result.option1Desc));
LOG("Option 1: %s\n", buf);
}
{
uint32_t year;
uint8_t month, day, hour, minute, second;
uint16_t _millisec;
uint16_t _microsec;
unpackDateTime(year, month, day, hour, minute, second, _millisec, _microsec, result.openDate);
LOG("Open date: %04u-%02u-%02u %02u:%02u:%02u\n", year, month, day, hour, minute, second);
unpackDateTime(year, month, day, hour, minute, second, _millisec, _microsec, result.endDate);
LOG("End date: %04u-%02u-%02u %02u:%02u:%02u\n", year, month, day, hour, minute, second);
}
}
static void quotteryPrintEventInfoRecord(const getEventInfo_output& result, uint64_t requestedEventId)
{
if (result.qei.eid != requestedEventId)
{
LOG("EventId #%" PRIu64 " doesn't exist\n", requestedEventId);
return;
}
quotteryPrintEventMetaData(result.qei, requestedEventId);
LOG("Result by GO: %" PRId32 "\n", result.resultByGO);
if (result.resultByGO != -1)
{
if (result.publishTickTime == 0xffffffffu) {
LOG("This event is already finalized and waiting for cleanup\n");
}
else {
LOG("Publish tick time: %" PRIu32 "\n", result.publishTickTime);
}
}
if (!isZeroPubkey(result.disputerInfo.pubkey))
{
char disputerId[128] = { 0 };
getIdentityFromPublicKey(result.disputerInfo.pubkey, disputerId, false);
LOG("Disputer: %s\n", disputerId);
LOG("Dispute amount: %" PRIu64 "\n", result.disputerInfo.amount);
LOG("Computors vote 0: %" PRIu32 "\n", result.computorsVote0);
LOG("Computors vote 1: %" PRIu32 "\n", result.computorsVote1);
}
}
void quotteryPrintEventInfo(const char* nodeIp, const int nodePort, uint64_t eventId)
{
getEventInfo_output result;
memset(&result, 0, sizeof(getEventInfo_output));
LOG("Getting eventId #%" PRIu64 " info...\n", eventId);
quotteryGetEventInfo(nodeIp, nodePort, eventId, result);
if (isArrayZero((uint8_t*)&result, sizeof(getEventInfo_output)))
{
LOG("Failed to get\n");
return;
}
quotteryPrintEventInfoRecord(result, eventId);
}
void quotteryGetEventInfoBatch(const char* nodeIp, int nodePort, const uint64_t* eventIds, GetEventInfoBatch_output& result)
{
GetEventInfoBatch_input input{};
for (size_t j = 0; j < 64; ++j)
{
input.eventIds[j] = eventIds[j];
}
memset(&result, 0, sizeof(result));
if (!runContractFunction(nodeIp, nodePort, QUOTTERY_CONTRACT_ID, QTRY_GET_EVENT_BATCH,
&input, sizeof(input), &result, sizeof(result)))
{
memset(&result, 0, sizeof(result));
}
}
void quotteryPrintEventInfoBatch(const char* nodeIp, int nodePort, const uint64_t* eventIds, size_t count)
{
if (count == 0)
{
LOG("Error: no event ids provided\n");
return;
}
uint64_t paddedEventIds[64] = {};
for (size_t i = 0; i < count && i < 64; ++i)
{
paddedEventIds[i] = eventIds[i];
}
GetEventInfoBatch_output result{};
memset(&result, 2, sizeof(GetEventInfoBatch_output));
LOG("Getting %zu event(s) info in batch...\n", count);
quotteryGetEventInfoBatch(nodeIp, nodePort, paddedEventIds, result);
if (isArrayZero(reinterpret_cast<uint8_t*>(&result), sizeof(result)))
{
LOG("Failed to get batch event info\n");
return;
}
for (size_t i = 0; i < count && i < 64; ++i)
{
LOG("\n================\n");
LOG("Requested eventId: %" PRIu64 "\n", paddedEventIds[i]);
quotteryPrintEventMetaData(result.aqei[i], paddedEventIds[i]);
}
}
struct qtryOrderAction_input
{
uint64_t eventId;
uint64_t option;
uint64_t amount;
uint64_t price;
};
template <int functionNumber>
void qtryOrderAction(const char* nodeIp, int nodePort,
const char* seed,
uint64_t eventId, uint64_t option, uint64_t amount, int64_t price,
uint64_t antiSpamAmount,
uint32_t scheduledTickOffset)
{
auto qc = make_qc(nodeIp, nodePort);
qtryBasicInfo_output qbi{};
quotteryGetBasicInfo(qc, qbi);
antiSpamAmount = qbi.antiSpamAmount;
LOG("\n-------------------------------------\n\n");
LOG("Sending QTRY order action - functionNumber: %d\n", functionNumber);
LOG("eventId: %" PRIu64 "\n", eventId);
LOG("option: %" PRIu64 "\n", option);
LOG("amount: %" PRIu64 "\n", amount);
LOG("price: %" PRId64 "\n", price);
LOG("antiSpamAmount: %" PRIu64 "\n", antiSpamAmount);
LOG("\n-------------------------------------\n\n");
qtryOrderAction_input input{};
input.eventId = eventId;
input.option = option;
input.amount = amount;
input.price = price;
makeContractTransaction(nodeIp, nodePort, seed,
QUOTTERY_CONTRACT_ID,
functionNumber,
/*amount=*/(int64_t)antiSpamAmount,
sizeof(input), &input,
scheduledTickOffset,
&qc);
}
void qtryAddToAskOrder(const char* nodeIp, int nodePort, const char* seed,
uint64_t eventId, uint64_t option, uint64_t amount, int64_t price,
uint64_t antiSpamAmount, uint32_t scheduledTickOffset)
{
qtryOrderAction<QTRY_ADD_ASK_ORDER>(nodeIp, nodePort, seed, eventId, option, amount, price, antiSpamAmount, scheduledTickOffset);
}
void qtryAddToBidOrder(const char* nodeIp, int nodePort, const char* seed,
uint64_t eventId, uint64_t option, uint64_t amount, int64_t price,
uint64_t antiSpamAmount, uint32_t scheduledTickOffset)
{
qtryOrderAction<QTRY_ADD_BID_ORDER>(nodeIp, nodePort, seed, eventId, option, amount, price, antiSpamAmount, scheduledTickOffset);
}
void qtryRemoveAskOrder(const char* nodeIp, int nodePort, const char* seed,
uint64_t eventId, uint64_t option, uint64_t amount, int64_t price,
uint64_t antiSpamAmount, uint32_t scheduledTickOffset)
{
qtryOrderAction<QTRY_REMOVE_ASK_ORDER>(nodeIp, nodePort, seed, eventId, option, amount, price, antiSpamAmount, scheduledTickOffset);
}
void qtryRemoveBidOrder(const char* nodeIp, int nodePort, const char* seed,
uint64_t eventId, uint64_t option, uint64_t amount, int64_t price,
uint64_t antiSpamAmount, uint32_t scheduledTickOffset)
{
qtryOrderAction<QTRY_REMOVE_BID_ORDER>(nodeIp, nodePort, seed, eventId, option, amount, price, antiSpamAmount, scheduledTickOffset);
}
void qtryGetOrders(const char* nodeIp, int nodePort,
uint64_t eventId, uint64_t option, uint64_t isBid, uint64_t offset,
qtryGetOrders_output& result)
{
qtryGetOrders_input input{};
input.eventId = eventId;
input.option = option;
input.isBid = isBid;
input.offset = offset;
memset(&result, 0, sizeof(result));
if (!runContractFunction(nodeIp, nodePort, QUOTTERY_CONTRACT_ID, QTRY_GET_ORDERS,
&input, sizeof(input), &result, sizeof(result)))
{
memset(&result, 0, sizeof(result));
}
}
void quotteryPrintOrders(const char* nodeIp, int nodePort,
uint64_t eventId, uint64_t option, uint64_t isBid, uint64_t offset)
{
qtryGetOrders_output result;
memset(&result, 0, sizeof(qtryGetOrders_output));
qtryGetOrders(nodeIp, nodePort, eventId, option, isBid, offset, result);
int N = sizeof(result.orders) / sizeof(result.orders[0]);
LOG("%s orders for eventId %" PRIu64 " option %" PRIu64 " (offset %" PRIu64 "):\n",
isBid ? "Bid" : "Ask", eventId, option, offset);
LOG("Entity\t\t\t\t\t\t\t\tPrice\tAmount\n");
for (int i = 0; i < N; i++)
{
if (isZeroPubkey(result.orders[i].qo.entity))
{
break;
}
char iden[128] = { 0 };
getIdentityFromPublicKey(result.orders[i].qo.entity, iden, false);
LOG("%s\t%" PRId64 "\t%" PRIu64 "\n", iden, result.orders[i].price, result.orders[i].qo.amount);
}
}
struct getUserPosition_input
{
uint8_t uid[32];
};
void quotteryGetUserPosition(const char* nodeIp, int nodePort, const char* identity, getUserPosition_output& result)
{
getUserPosition_input input{};
getPublicKeyFromIdentity(identity, input.uid);
memset(&result, 0, sizeof(result));
if (!runContractFunction(nodeIp, nodePort, QUOTTERY_CONTRACT_ID, QUOTTERY_GET_USER_POSITION,
&input, sizeof(input), &result, sizeof(result)))
{
memset(&result, 0, sizeof(result));
}
}
void quotteryPrintUserPosition(const char* nodeIp, int nodePort, const char* identity)
{
getUserPosition_output result;
memset(&result, 0, sizeof(getUserPosition_output));
quotteryGetUserPosition(nodeIp, nodePort, identity, result);
LOG("Positions for %s (count: %" PRId64 "):\n", identity, result.count);
LOG("EventId\tOption\tAmount\n");
for (int64_t i = 0; i < result.count; i++)
{
uint64_t eventId = QUOTTERY_EO_GET_EVENTID(result.p[i].eo);
uint64_t option = QUOTTERY_EO_GET_OPTION(result.p[i].eo);
LOG("%" PRIu64 "\t%" PRIu64 "\t%" PRId64 "\n", eventId, option, result.p[i].amount);
}
}
struct qtryPublishResult_input
{
uint64_t eventId;
uint64_t option;
};
struct qtryTryFinalizeEvent_input
{
uint64_t eventId;
};
static bool isCurrentUtcAfterPackedDateTime(uint64_t packedDateTime)
{
uint32_t endYear;
uint8_t endMonth, endDay, endHour, endMinute, endSecond;
uint16_t endMillisec, endMicrosec;
unpackDateTime(endYear, endMonth, endDay, endHour, endMinute, endSecond, endMillisec, endMicrosec, packedDateTime);
std::time_t nowTs = std::time(nullptr);
std::tm nowUtc{};
#if defined(_WIN32)
gmtime_s(&nowUtc, &nowTs);
#else
gmtime_r(&nowTs, &nowUtc);
#endif
const uint32_t nowYear = static_cast<uint32_t>(nowUtc.tm_year + 1900);
const uint8_t nowMonth = static_cast<uint8_t>(nowUtc.tm_mon + 1);
const uint8_t nowDay = static_cast<uint8_t>(nowUtc.tm_mday);
const uint8_t nowHour = static_cast<uint8_t>(nowUtc.tm_hour);
const uint8_t nowMinute = static_cast<uint8_t>(nowUtc.tm_min);
const uint8_t nowSecond = static_cast<uint8_t>(nowUtc.tm_sec);
uint64_t nowPacked = 0;
packDateTime(nowYear, nowMonth, nowDay, nowHour, nowMinute, nowSecond, 0, 0, nowPacked);
return nowPacked >= packedDateTime;
}
void qtryPublishResult(const char* nodeIp, int nodePort, const char* seed, uint32_t scheduledTickOffset, uint64_t eventId, uint64_t result)
{
if (result != 0 && result != 1)
{
LOG("Error: result can only be 0 or 1\n");
return;
}
auto qc = make_qc(nodeIp, nodePort);
uint8_t privateKey[32] = { 0 };
uint8_t sourcePublicKey[32] = { 0 };
uint8_t subSeed[32] = { 0 };
char sourceIdentity[128] = { 0 };
char goIdentity[128] = { 0 };
getSubseedFromSeed((uint8_t*)seed, subSeed);
getPrivateKeyFromSubSeed(subSeed, privateKey);
getPublicKeyFromPrivateKey(privateKey, sourcePublicKey);
getIdentityFromPublicKey(sourcePublicKey, sourceIdentity, false);
qtryBasicInfo_output basic{};
quotteryGetBasicInfo(qc, basic);
if (isArrayZero((uint8_t*)&basic, sizeof(basic)))
{
LOG("Error: failed to get Quottery basic info\n");
return;
}
if (memcmp(sourcePublicKey, basic.gameOperator, 32) != 0)
{
getIdentityFromPublicKey(basic.gameOperator, goIdentity, false);
LOG("Error: seed is not the game operator\n");
LOG("Current identity: %s\n", sourceIdentity);
LOG("Game operator: %s\n", goIdentity);
return;
}
getEventInfo_output eventInfo{};
_quotteryGetEventInfo(qc, eventId, eventInfo);
if (isArrayZero((uint8_t*)&eventInfo, sizeof(eventInfo)))
{
LOG("Error: failed to get event info for eventId %" PRIu64 "\n", eventId);
return;
}
if (eventInfo.qei.eid == (uint64_t)-1)
{
LOG("Error: eventId %" PRIu64 " does not exist\n", eventId);
return;
}
if (!isCurrentUtcAfterPackedDateTime(eventInfo.qei.endDate))
{
uint32_t year;
uint8_t month, day, hour, minute, second;
uint16_t millisec, microsec;
unpackDateTime(year, month, day, hour, minute, second, millisec, microsec, eventInfo.qei.endDate);
LOG("Error: event %" PRIu64 " has not ended yet\n", eventId);
LOG("End date (UTC): %04u-%02u-%02u %02u:%02u:%02u\n", year, month, day, hour, minute, second);
return;
}
qtryPublishResult_input input{};
input.eventId = eventId;
input.option = result;
LOG("\n-------------------------------------\n\n");
LOG("Sending QTRY publish result\n");
LOG("eventId: %" PRIu64 "\n", eventId);
LOG("result: %" PRIu64 "\n", result);
LOG("depositAmountForDispute: %" PRIu64 "\n", basic.depositAmountForDispute);
LOG("\n-------------------------------------\n\n");
makeContractTransaction(nodeIp, nodePort, seed,
QUOTTERY_CONTRACT_ID,
QTRY_PUBLISH_RESULT,
/*amount=*/(int64_t)basic.depositAmountForDispute,
sizeof(input), &input,
scheduledTickOffset,
&qc);
}
void qtryTryFinalizeEvent(const char* nodeIp, int nodePort, const char* seed, uint32_t scheduledTickOffset, uint64_t eventId)
{
auto qc = make_qc(nodeIp, nodePort);
uint8_t privateKey[32] = { 0 };
uint8_t sourcePublicKey[32] = { 0 };
uint8_t subSeed[32] = { 0 };
char sourceIdentity[128] = { 0 };
char goIdentity[128] = { 0 };
getSubseedFromSeed((uint8_t*)seed, subSeed);
getPrivateKeyFromSubSeed(subSeed, privateKey);
getPublicKeyFromPrivateKey(privateKey, sourcePublicKey);
getIdentityFromPublicKey(sourcePublicKey, sourceIdentity, false);
qtryBasicInfo_output basic{};
quotteryGetBasicInfo(qc, basic);
if (isArrayZero((uint8_t*)&basic, sizeof(basic)))
{
LOG("Error: failed to get Quottery basic info\n");
return;
}
if (memcmp(sourcePublicKey, basic.gameOperator, 32) != 0)
{
getIdentityFromPublicKey(basic.gameOperator, goIdentity, false);
LOG("Error: seed is not the game operator\n");
LOG("Current identity: %s\n", sourceIdentity);
LOG("Game operator: %s\n", goIdentity);
return;
}
getEventInfo_output eventInfo{};
_quotteryGetEventInfo(qc, eventId, eventInfo);
if (isArrayZero((uint8_t*)&eventInfo, sizeof(eventInfo)))
{
LOG("Error: failed to get event info for eventId %" PRIu64 "\n", eventId);
return;
}
if (eventInfo.qei.eid != eventId)
{
LOG("Error: eventId %" PRIu64 " does not exist\n", eventId);
return;
}
if (eventInfo.resultByGO == -1)
{
LOG("Error: event %" PRIu64 " does not have a published result yet\n", eventId);
return;
}
if (!isZeroPubkey(eventInfo.disputerInfo.pubkey))
{
LOG("Error: event %" PRIu64 " is under dispute and cannot be finalized\n", eventId);
return;
}
const uint32_t currentTick = getTickNumberFromNode(qc);
const uint32_t scheduledTick = currentTick + scheduledTickOffset;
if (eventInfo.publishTickTime + 1000 > scheduledTick)
{
LOG("Error: event %" PRIu64 " cannot be finalized yet\n", eventId);
LOG("Publish tick: %" PRIu32 "\n", eventInfo.publishTickTime);
LOG("Earliest finalize tick: %" PRIu32 "\n", eventInfo.publishTickTime + 1000);
LOG("Scheduled tick: %" PRIu32 "\n", scheduledTick);
return;
}
qtryTryFinalizeEvent_input input{};
input.eventId = eventId;
LOG("\n-------------------------------------\n\n");
LOG("Sending QTRY try finalize event\n");
LOG("eventId: %" PRIu64 "\n", eventId);
LOG("publishTickTime: %" PRIu32 "\n", eventInfo.publishTickTime);
LOG("\n-------------------------------------\n\n");
makeContractTransaction(nodeIp, nodePort, seed,
QUOTTERY_CONTRACT_ID,
QTRY_TRY_FINALIZE_EVENT,
/*amount=*/0,
sizeof(input), &input,
scheduledTickOffset,
&qc);
}
struct qtryDispute_input
{
uint64_t eventId;
};
void qtryDispute(const char* nodeIp, int nodePort, const char* seed, uint32_t scheduledTickOffset, uint64_t eventId)
{
auto qc = make_qc(nodeIp, nodePort);
uint8_t privateKey[32] = { 0 };
uint8_t sourcePublicKey[32] = { 0 };
uint8_t subSeed[32] = { 0 };
getSubseedFromSeed((uint8_t*)seed, subSeed);
getPrivateKeyFromSubSeed(subSeed, privateKey);
getPublicKeyFromPrivateKey(privateKey, sourcePublicKey);
qtryBasicInfo_output basic{};
quotteryGetBasicInfo(qc, basic);
if (isArrayZero((uint8_t*)&basic, sizeof(basic)))
{
LOG("Error: failed to get Quottery basic info\n");
return;
}
const uint64_t depositAmount = basic.depositAmountForDispute;
// Fetch event info to validate dispute preconditions
getEventInfo_output eventInfo{};
_quotteryGetEventInfo(qc, eventId, eventInfo);
if (isArrayZero((uint8_t*)&eventInfo, sizeof(eventInfo)))
{
LOG("Error: failed to get event info for eventId %" PRIu64 "\n", eventId);
return;
}
if (eventInfo.qei.eid != eventId)
{
LOG("Error: eventId %" PRIu64 " does not exist\n", eventId);
return;
}
if (eventInfo.resultByGO == -1)
{
LOG("Error: event %" PRIu64 " does not have a published result yet. Nothing to dispute.\n", eventId);
return;
}
if (eventInfo.publishTickTime == 0xffffffffu)
{
LOG("Error: event %" PRIu64 " is already finalized. Cannot dispute.\n", eventId);
return;
}
if (!isZeroPubkey(eventInfo.disputerInfo.pubkey))
{
char existingDisputer[128] = { 0 };
getIdentityFromPublicKey(eventInfo.disputerInfo.pubkey, existingDisputer, false);
LOG("Error: event %" PRIu64 " is already being disputed by %s\n", eventId, existingDisputer);
return;
}
const uint32_t currentTick = getTickNumberFromNode(qc);
const uint32_t scheduledTick = currentTick + scheduledTickOffset;
if (eventInfo.publishTickTime + 1000 <= scheduledTick)
{
LOG("Warning: dispute window may have passed for event %" PRIu64 "\n", eventId);
LOG("Publish tick: %" PRIu32 ", finalize eligible at tick: %" PRIu32 ", scheduled tick: %" PRIu32 "\n",
eventInfo.publishTickTime, eventInfo.publishTickTime + 1000, scheduledTick);
LOG("The event may already be finalized by the time this transaction executes.\n");
}
{
long long balance = getBalanceNumber(qc, sourcePublicKey);
if (balance < 0)
{
LOG("Error: failed to query balance\n");
return;
}
if (static_cast<uint64_t>(balance) < depositAmount)
{
LOG("Error: insufficient balance for dispute deposit\n");
LOG("Required: %" PRIu64 ", available: %lld\n", depositAmount, balance);
return;
}
}
qtryDispute_input input{};
input.eventId = eventId;
LOG("\n-------------------------------------\n\n");
LOG("Sending QTRY Dispute\n");
LOG("eventId: %" PRIu64 "\n", eventId);
LOG("depositAmountForDispute: %" PRIu64 "\n", depositAmount);
LOG("\n-------------------------------------\n\n");
makeContractTransaction(nodeIp, nodePort, seed,
QUOTTERY_CONTRACT_ID,
QTRY_DISPUTE,
/*amount=*/(int64_t)depositAmount,
sizeof(input), &input,
scheduledTickOffset,
&qc);
}
struct qtryResolveDispute_input
{
uint64_t eventId;
int64_t vote;
};
void qtryResolveDispute(const char* nodeIp, int nodePort, const char* seed, uint32_t scheduledTickOffset, uint64_t eventId, int64_t vote)
{
if (vote != 0 && vote != 1)
{
LOG("Error: vote must be 0 or 1\n");
return;
}
auto qc = make_qc(nodeIp, nodePort);
uint8_t privateKey[32] = { 0 };
uint8_t sourcePublicKey[32] = { 0 };
uint8_t subSeed[32] = { 0 };
char sourceIdentity[128] = { 0 };
getSubseedFromSeed((uint8_t*)seed, subSeed);
getPrivateKeyFromSubSeed(subSeed, privateKey);
getPublicKeyFromPrivateKey(privateKey, sourcePublicKey);
getIdentityFromPublicKey(sourcePublicKey, sourceIdentity, false);
getEventInfo_output eventInfo{};
_quotteryGetEventInfo(qc, eventId, eventInfo);
if (isArrayZero((uint8_t*)&eventInfo, sizeof(eventInfo)))
{
LOG("Error: failed to get event info for eventId %" PRIu64 "\n", eventId);
return;
}
if (eventInfo.qei.eid != eventId)
{
LOG("Error: eventId %" PRIu64 " does not exist\n", eventId);
return;
}
if (isZeroPubkey(eventInfo.disputerInfo.pubkey))
{
LOG("Error: event %" PRIu64 " is not under dispute\n", eventId);
return;
}
constexpr int64_t MIN_INVOCATION_REWARD = 10000000;
{
long long balance = getBalanceNumber(qc, sourcePublicKey);
if (balance < 0)
{
LOG("Error: failed to query balance\n");
return;
}
if (static_cast<uint64_t>(balance) < static_cast<uint64_t>(MIN_INVOCATION_REWARD))
{
LOG("Error: insufficient balance\n");
LOG("Required (refunded if computor): %" PRId64 ", available: %lld\n", MIN_INVOCATION_REWARD, balance);
return;
}
}
qtryResolveDispute_input input{};
input.eventId = eventId;
input.vote = vote;
LOG("\n-------------------------------------\n\n");
LOG("Sending QTRY ResolveDispute\n");
LOG("Caller: %s\n", sourceIdentity);
LOG("eventId: %" PRIu64 "\n", eventId);
LOG("vote: %" PRId64 " (%s)\n", vote, vote == 0 ? "No" : "Yes");
LOG("invocationReward: %" PRId64 " (refunded if caller is a computor)\n", MIN_INVOCATION_REWARD);
LOG("\n-------------------------------------\n\n");
makeContractTransaction(nodeIp, nodePort, seed,
QUOTTERY_CONTRACT_ID,
QTRY_RESOLVE_DISPUTE,
/*amount=*/MIN_INVOCATION_REWARD,
sizeof(input), &input,
scheduledTickOffset,
&qc);
LOG("Note: only computors can resolve disputes. If the caller is not a computor, the invocation reward will NOT be refunded.\n");
}
struct qtryUserClaimReward_input
{
uint64_t eventId;